#!/bin/sh

mkdir -p /tmp
swupdate_enabled() {
    for file in /run/media/storage/*.swu; do
        if [ -f "$file" ]; then
            info "swupdate file found: $file"
            return 0
        fi
    done
    if [ -f /tmp/swupdate_enabled ]; then
        info "swupdate enabled from previous boot"
        return 0
    elif [ -n "$bootparam_swupdate" ]; then
        info "swupdate enabled from bootparam"
        return 0
    else
        # swupdate not enabled. Set variable so its enabled in the final slot.
        echo "yes" > /tmp/swupdate_enabled
        return 1
    fi
}

function get_slot {
    for i in `cat /proc/cmdline`; do
        if [[ $i == bootslot=* ]]; then
            CURRENT_SLOT="${i: -1}"
        fi;
    done
    # if recovery flag is set, use the other slot
    if [ "$CURRENT_SLOT" = "1" ]; then
        export UPDATE_SLOT="0";
        [ -f /boot/recovery ] && export UPDATE_SLOT="1";
    else
        export UPDATE_SLOT="1";
        [ -f /boot/recovery ] && export UPDATE_SLOT="0";
    fi
}

run_swupd() {
    . /etc/default/swupdate
    get_slot

    for file in /run/media/storage/*.swu; do
        rm -rf "/tmp/$(basename $file)"
        mv -f $file "/tmp/$(basename $file)" && file="/tmp/$(basename $file)"
    done
    for file in /run/media/*/*.swu; do
        if [ -f "$file" ]; then info "Found swu file $file. Running swupdate"; fi
    done
    umount -f /dev/disk/by-label/storage; umount -f /dev/disk/by-partlabel/storage; umount -f /dev/disk/by-label/boot; umount -f /dev/disk/by-partlabel/boot;

    selection="recovery,slot${UPDATE_SLOT}"
    info "Running swupdate with selection: $selection"
    if [ -f "$file" ] && [ -f /tmp/swupdate_enabled ]; then
        info "Found swu file $file. Running swupdate"
        swupdate -v -H ${hardware}:1.0 -f /etc/swupdate.cfg -e "$selection" -i $file -p 'sync; echo b >/proc/sysrq-trigger' || msg "swupdate from media file failed"
    fi
    # dl_url="https://github.com/VideologyInc/scailx_yocto/releases/latest/download/scailx-image-swupdate-${hardware}.swu"
    # swupdate -v -H ${hardware}:1.0 -f /etc/swupdate.cfg -e "$selection" -d "--url $dl_url" -p 'sync; echo b >/proc/sysrq-trigger' || msg "swupdate from URL failed"
    swupdate -v -H ${hardware}:1.0 -f /etc/swupdate.cfg -e "$selection" -w ""              -p 'sync; echo b >/proc/sysrq-trigger' || msg "swupdate from web failed"
}

swupdate_run() {
    # if we're in an error condition, format the disk
    [ -f "/tmp/initrd_error" ] && echo "boot error. Updating" > /dev/kmsg

    # get dhcp lease
    udhcpc || udhcpc -i end0
    run_swupd
}
