#Library functions for flash scripts

#Load logging functions and definitions
. "$IEP_LIB_PATH/iep-logging"

_action "Reticulating splines..."
FLASH_MOUNT="/tmp/___flash"
WORKSPACE="/tmp/___flash-workspace"
_data "Image-path: $FLASH_MOUNT"
_data "Workspace: $WORKSPACE"

#$1: The image's path
setup () {
    _action "Creating temporary partitions and mounting image..."
    mkdir -p "$WORKSPACE"
    mkdir -p "$FLASH_MOUNT"
    mount -o loop,ro "$1" "$FLASH_MOUNT"
}

teardown () {
    _action "Removing tempfiles and restoring previous state..."
    umount "$FLASH_MOUNT" || {
        _warn "Unable to unmount image; this is benign"
        return 0
    }
    rm -rf "$FLASH_MOUNT" || _warn "Unable to remove $FLASH_MOUNT; this is benign"
    rm -rf "$WORKSPACE" || _warn "Unable to remove $WORKSPACE; this is benign"
}

#$1: Whether or not update-mode should be used (1 or 0); in update-mode, only
#    a result where (code & 1 == 1) is considered a failure
execute () {
    _action "Turning control over to the image..."
    mode_e=0
    if echo $- | grep -q "e"; then
        mode_e=1
        set +e
    fi
    "$FLASH_MOUNT/init" "$FLASH_MOUNT" "$WORKSPACE"
    result=$?
    if [ $mode_e -eq 1 ]; then
        set -e
    fi
    
    success=1
    if [ -z "$1" ] || [ "$1" -ne 1 ]; then
        if [ $result -ne 0 ]; then
            success=0
            result=1 #Legacy value
        fi
    else
        if [ $(expr $result % 2) -eq 1 ]; then
            success=0
        fi
    fi
    
    [ $success -eq 1 ] && {
        _notice "Procedure successful"
    } || {
        _error "Procedure failed"
        _print "###################################################"
        _print
        _print " #######  #    ### #       #     # ######  ####### "
        _print " #       # #    #  #       #     # #     # #       "
        _print " #      #   #   #  #       #     # #     # #       "
        _print " ##### #     #  #  #       #     # ######  #####   "
        _print " #     #######  #  #       #     # #   #   #       "
        _print " #     #     #  #  #       #     # #    #  #       "
        _print " #     #     # ### #######  #####  #     # ####### "
        _print
        _print "###################################################"
    }
    return $result
}

#$1: path to be unmounted
unmount () {
    _path="$(realpath "$1")" &&
    mountpoint -q "$_path" && {
        _action "Unmounting $_path..." &&
        umount "$_path"
    }
    return 0
}
