####################################
#                                  #
# AnaPico Software Management Tool #
#                                  #
# (c) 2011-2021 by AnaPico AG      #
#                                  #
####################################

if ! $(tail -n 2 $0 | grep "# ~~ last line verification ~~" > /dev/null)
then
        echo "$0 is corrupted (incomplete)"
        exit 1
fi

if ! $(grep -q -e "tastit" -e "taskit" /proc/cpuinfo)
then
        echo "is not taskit; skipping $0"
        exit 0
fi

########################################################
# clean directory structure                            #
########################################################
rm /gmon.out
cd /root
mkdir -p ./temp

########################################################
# kill background processes                            #
########################################################

killall httpd
killall vsftpd
killall AP_websockify

# kill current fw (probably)
# -> try to prevent interference with write / protect ap
killall $(cat /etc/rc5.d/S61ap_run)

#########################################################
# extract sources if necessary                          #
#########################################################
cd ./temp
if [ ! -e "../schoggibroedli.tar" ]
then
        # new base janitor will keep schoggibroedli untouched
        # legacy janitor will call this after unpacking
        # -> if we are here, we are upgrading janitor

        # chmod +x ./janitor/check_platform.sh
        # ./janitor/check_platform.sh
        # if [ $? -ne 0 ]
        # then
        #         echo "check_platform returned mismatch"
        #         exit 1
        #         # legacy janitor will terminate as well after this
        # fi
        # -> SOC only

        chmod +x ./janitor/janitor_upgrade.sh
        ./janitor/janitor_upgrade.sh
        retval=$?
        if [ $retval -eq 2 ]
        then
                # janitor broken
                echo "This is an issue. Need GUI update to reduce package size before it can work."
                exit 1
        fi
        if [ $retval -eq 1 ]
        then
                # something broken, but not janitor
                echo "This is fine. Won't be required on next update attempt."
                exit 1
        fi
        # schoggibroedli should now exist, and ~/temp be delete

        # end by exit 1 in any case 
        # -> legacy janitor thinks it failed and terminates. (no need to run)
        terminate_legacy=1
fi

if [ -e "../schoggibroedli.tar" ]
then
        cd /root
        rm -r ./temp
        mkdir -p ./temp
        cd ./temp
        # only unpack what's needed
        write_ap
        # partition subject to unexplained spontaneous write protection
        # -> just hope this works?
        mv ../schoggibroedli.tar /anapico/schoggibroedli.tar
        # protect_ap  -- apparently ap is expected to be writeable down the line
        tar -xvf /anapico/schoggibroedli.tar payload updater packageinfo janitor matching.txt
        write_ap
        rm /anapico/schoggibroedli.tar
        # protect_ap
        # remove janitor transition and soc stuff
        rm ./janitor/janitor_upgrade.sh
        rm ./janitor/ahti
else
        echo "update package does not seem to exist"
        exit 1
fi

#########################################################
# check firmware update prerequisites                   #
#########################################################
if [ "$(uname -a)" == "Linux instr0 2.6.33 #58 PREEMPT Tue May 12 15:05:59 CEST 2015 armv5tejl unknown" ]
then
    echo "Running on a 12.05.2015 kernel, checking firmware compatibility"
    if [ -n "$(cat ./packageinfo | grep linux_kernel=12.05.2015)" ]
    then
            echo "Firmware supports 12.05.2015 kernel"
    else
            echo "Error: Firmware does not support 12.05.2015 kernel"
            cd ../
            rm -r ./temp
            exit 1
    fi
fi

if [ -e "/bin/write_root" ]
then
        echo "Read-only root file system, checking firmware compatibility"
        if [ -e ./packageinfo ]
        then
                if [ -n "$(cat ./packageinfo | grep ro_root_support=yes)" ]
                then
                        echo "Firmware supports read-only root file systems"
                else
                        echo "Error: Firmware does not support read-only root file systems"
                        cd ../
                        rm -r ./temp
                        exit 1
                fi
        else
                echo "Error: Missing package information file"
                echo "Error: Assume firmware does not support read-only root file systems"
                cd ../
                rm -r ./temp
                exit 1
        fi
else
        echo "Read-write root file system, skipping firmware compatibility check"
fi

for filename in ./janitor/*.sh
do
    case $(basename "$filename") in
        armcont_janitor.sh|janitor_upgrade.sh|"$0") continue ;;
    esac
    if [ -f "$filename" ]
    then
        echo "Executing janitor check script $filename"
	    chmod 777 $filename
	    $filename
        rc=$?
	    rm $filename
        if [[ $rc != 0 ]]
        then
            echo "Update cancelled by janitor check script $filename"
            cd ../
            rm -r ./temp
            exit 1
        fi
    fi
done


#########################################################
# update payload                                        #
#########################################################
echo "Check if package needs to be decrypted"
if [ -f ./payload ]
then
    echo "Running decryptor (updater)"
    ./updater
    rm payload
fi
tar -xvf payload.tar

#########################################################
# clean previous firmware upgrade logs                  #
#########################################################
rm "/anapico/dev/fwupdate"

#########################################################
# execute shell script delivered with software          #
#########################################################
for filename in ./*.sh
do
    echo "Executing $filename"
	chmod 777 $filename
	$filename
	rm $filename
done

if [ $terminate_legacy ]
then
        echo combined upgrade + update process done, rebooting now...
        rm /root/schoggibroedli.tar
        rm -rf /root/temp
        reboot
        # for some ungodly reason the script continues to run...
        # but old janitor will stop if we exit with "error" here
        echo "updater about to have exited nominally. Ignore further errors."
        exit 1
fi

echo "updater exited nominally."
exit 0

# ~~ last line verification ~~
