#!/bin/bash
# shellcheck source=rootfs/usr/lib/lwr/lwr-update-functions.sh
source "/usr/lib/lwr/lwr-update-functions.sh"
set -uE
trap 'echo >&2 "Error - ${BASH_SOURCE[0]}:${FUNCNAME:-""} exited with status $? at line $LINENO:" &&
         pr -tn ${BASH_SOURCE[0]} | tail -n+$((LINENO - 2)) | head -n5' ERR


function help() {
# If you change the format, or line nubbers, the README could break, check it 
    echo \ "
Usage: lwr-update <subcommand> [argument]

Full update manually:
    lwr-update full-update '</path/to/lfp2 | url-to-lfp2>'

Available subcommands:
    validate:                    sanity and compatibility check
    prepare [force]:             prepare update (create backup, write upload-finished file)
    perform:                     reboot and perform update
    clean:                       remove all related files
    status:                      Idle|Package uploading|Package ready|Package incompatible|Package prepared|Performing update|Failed
    progress:                    Prints actual progress of getting package in JSON format ({\"full\": \"2214\",\"processed\": \"1422\",\"percent\": \"64\"})
    get <lfp2> [size]:           get new firmware from lfp2 ('-', filepath on device or url on http(s) server), size could be given, for better progress feedback
    full-update <lfp2> [size]:   get the given fw, prepare and perform it (lwr-update clean && lwr-update get '</path/to/lfp2 | url-to-lfp2>' && lwr-update prepare && lwr-update perform)
    checkcompatible <script>:    runs the given script ('-', filepath on device or url on http(s) server) in safe enviroment to check if product is compatible with package.
"
}

function fail() {
    echo "Error: $1" >&2
    help
    exit 1
}

[[ $# -eq 0 ]] && fail "Missing subcommand"
case "${1}" in
    "validate")
        lwr_update_validate
        ;;
    "prepare")
        is_forced="0"
        if [[ "$#" -eq 2 && "${2}" = "force" ]]; then
            is_forced="1"
        fi
        lwr_update_prepare "${is_forced}"
        ;;
    "perform")
        lwr_update_perform
        ;;
    "clean")
        lwr_update_cleanup
        ;;
    "status")
        trap - ERR
        lwr_update_status
        ;;
    "progress")
        trap - ERR
        lwr_update_progress
        ;;
    "get")
        lwr_update_get "${2:?"Missing file path or url"}" "${3:-"N/A"}"
        ;;
    "full-update")
        lwr_update_full_update "${2:?"Missing file path or url"}" "${3:-"N/A"}"
        ;;
    "checkcompatible")
        lwr_update_checkcompatible "${2:?"Missing file path or url"}"
        ;;
    "help"|"-h"|"--help")
        help
        ;;
    *)
        fail "Unknown update subcommand: ${1}"
        ;;
esac
