#!/bin/sh
###############################################################################
#                                                                             #
#                           Update gw software                                #
#                                                                             #
###############################################################################

. /usr/local/bin/telem/functions

boardname="$(/usr/local/bin/telem/boardname.sh)"

###############################################################################
#                                                                             #
#                         Gateway6 files and folders                          #
#                                                                             #
###############################################################################

FOLDER_BIN=/usr/bin		# Executables
FOLDER_LIB=/usr/lib		# Shared libraries
FOLDER_TEMP=/tmp/upd_tar	# Temporary files
# VMX25 with 64MB of RAM will not be enough if extracted to /tmp
[ "$boardname" == "VMX25" ] && FOLDER_TEMP=/home/martem/upd_tar
NET_UPD=/root/upd/



SDD=/mnt/sd
UPDATE_FOLDER=notset
UPD_ROOT=$FOLDER_TEMP/gwupd
UPD_LOG=$FOLDER_TEMP/res.txt
ERR_LOG=$FOLDER_TEMP/err.txt

kernel_update=0

STATS_DIR=/var/local/telem/stats

###############################################################################
#                                                                             #
#                             Script functions                                #
#                                                                             #
###############################################################################


# clears update directory from crap
clear_update_dir()
{
    if [ ! -e $UPD_ROOT ]; then
        return 1
    fi
    rm -r $UPD_ROOT
}

# extract software
extractsw()
{
    # location of tarball
    local SRC_DIR=$1

    clear_update_dir

    if [ ! -e $SRC_DIR ]; then
        return 1	
    fi

    test -e $SRC_DIR/Kernel && kernel_update=1

    cd $SRC_DIR
    md5sum -s -c $SRC_DIR/md5sums
    if [ "$?" = "0" ]; then
    #
    #	md5sum is OK, extract tarball
    #
        logger -s -p "user.info" -t "$0" "Checksum is OK"
        
        # detect archive type and select approriate filter
        if [ -e $SRC_DIR/upd.tar ]; then
                ARC_FILTER=""
                TARBALL=$SRC_DIR/upd.tar
        elif [ -e $SRC_DIR/upd.tar.gz ]; then
                ARC_FILTER="-z"
                TARBALL=$SRC_DIR/upd.tar.gz
        elif [ -e $SRC_DIR/upd.tar.bz2 ]; then
                ARC_FILTER="-j"
                TARBALL=$SRC_DIR/upd.tar.bz2
        elif [ -e $SRC_DIR/upd.tar.lzma ]; then
                ARC_FILTER="-a"
                TARBALL=$SRC_DIR/upd.tar.lzma
        fi

        logger -s -p "user.info" -t "$0" "Entering temporary folder"
        mkdir -p "$FOLDER_TEMP"
        cd $FOLDER_TEMP
        logger -s -p "user.info" -t "$0" "Extracting tarball"
        tar -x $ARC_FILTER -f $TARBALL

    else
        logger -s -p "user.info" -t "$0" "Checksum is BAD, aborting update!"
    fi
}

checkIfBadUpdate()
{
    [ -f "$1/md5sums" ] || { true; return; }
    local hash=$(awk '/upd/ {print $1}' "$1/md5sums")
    [ -f "/etc/.badfw" ] && grep -Fq -- "$hash" "/etc/.badfw"
}



run_update()
{
    if [ -e $UPD_ROOT/upd.sh ]; then
    #
    #	Update script exists, allow execution and execute
    #
        export UPGRADED=1
        chmod +x $UPD_ROOT/upd.sh

        logger -s -p "user.info" -t "$0" "Starting update script: $UPD_ROOT/upd.sh"
        
        local _version_before=`cat /usr/local/etc/telem/version`

        $UPD_ROOT/upd.sh $UPD_ROOT $UPD_LOG $ERR_LOG
        
        local _version_after=`cat /usr/local/etc/telem/version`
        
        if [ "_$_version_before" = "_$_version_after" ]; then
            # TODO: proper fix
            # Hard to tell if version did not change because:
            # 1) (good) firmware was found in done file and was not updated
            # 2) (bad)  firmware was not found in done file, but has same firmware version and was updated!!
            # Last one happens commonly with fresly flashed devices.
            # Currently workaround is available in new firmware UpdateSystem.sh script (called by $UPD_ROOT/upd.sh)
            return 0
        fi

        [ $kernel_update = 1 ] && return 0

        SETUP_FILENAME_NEW=setup.new.tar.xz
        SETUP_FILENAME=setup.tar.xz

        rm -f /etc/network/interfaces
        
        if [ -e /usr/local/etc/telem/$SETUP_FILENAME ]; then 
            # if tar.xz config file exists, reload it
            logger -s -p "user.info" -t "$0" "Reload $SETUP_FILENAME"
            mv /usr/local/etc/telem/$SETUP_FILENAME /usr/local/etc/telem/$SETUP_FILENAME_NEW
        else
            # if tar.xz config doesn't exist and binary exists, reload the binary version
            test -e /etc/init.d/S12telem-config-bin && {
                test -e /usr/local/etc/telem/gwSetup.bin && {
                    logger -s -p "user.info" -t "$0" "Reload gwSetup.bin"
                    mv /usr/local/etc/telem/gwSetup.bin /usr/local/etc/telem/gwSetup.bin.new
                }
            }
        fi

        chmod +x /usr/local/bin/telem/check_permissions

        /usr/local/bin/telem/check_permissions /

        clear_update_dir
    
        /usr/local/bin/telem/post_update.sh
    fi

}



LocateUpdateDirectory()
{
    # update from SD?
    UPDATE_FOLDER=$SDD/gwupd
    if [ -e $UPDATE_FOLDER ]; then
        ERR_LOG=$UPDATE_FOLDER/err.txt
        UPD_LOG=$UPDATE_FOLDER/res.txt
        # skip this to the end, if backup directory is set
        [ -d "$SDD/gwupd-bkp/" ] || return 0
    fi

    # look inside /root folder
    UPDATE_FOLDER=/root/gwupd
    if [ -e $UPDATE_FOLDER ]; then
	ERR_LOG=$UPDATE_FOLDER/err.txt
	UPD_LOG=$UPDATE_FOLDER/res.txt
	return 0
    fi

    # look inside /home/*user* folders
    for dir_name in /home/*; do
      if [ -d $dir_name ]; then
	  UPDATE_FOLDER=$dir_name/gwupd
	  if [ -e $UPDATE_FOLDER ]; then
	      ERR_LOG=$UPDATE_FOLDER/err.txt
	      UPD_LOG=$UPDATE_FOLDER/res.txt
	      return 0
	  fi
      fi
    done

    # last resort: use SD card
    UPDATE_FOLDER=$SDD/gwupd
    if [ -e $UPDATE_FOLDER ]; then
        ERR_LOG=$UPDATE_FOLDER/err.txt
        UPD_LOG=$UPDATE_FOLDER/res.txt
        return 0
    fi

    UPDATE_FOLDER=notset

    return 1
}

Locate7zUpdate() {
    command -v 7zr &>/dev/null || return 1
    local ret=1
    if [ -f '/root/firmware.new.web.7z' ]; then
        mkdir '/root/gwupd.web.tmp/' && \
        7zr x '/root/firmware.new.web.7z' -o'/root/gwupd.web.tmp/' && \
        mv '/root/gwupd.web.tmp/gwupd' '/root/gwupd' && \
        ret=0
    fi

    # cleanup
    rm '/root/firmware.new.web.7z'     &>/dev/null
    rm '/root/firmware.new.web.7z.tmp' &>/dev/null
    rm -r '/root/gwupd.web.tmp/'       &>/dev/null

    return $ret
}

###############################################################################
#                                                                             #
#                                The Script                                   #
#                                                                             #
###############################################################################



#
# $1 - log file location
#
updlog()
{
    echo -e $1 >> $UPD_LOG

    logg "$1"
}



##
# $1 - message
#
errlog()
{
    echo -e "$1" >> $ERR_LOG
    loggerr "$1"
}



start() {

    if [ -e $STATS_DIR/device-is-booted ]; then
        logger -s -p "user.info" -t "$0" "System already booted, restaring before startig update procedure"
        reboot
        exit 1
    fi

    logger -s -p "user.info" -t "$0" "Starting telem-update"

    ! umount $SDD
    rm -r $SDD

    # mount SD card if connected
    mountSDp1 || ln -s /dev/null $SDD

    # locate folder with new update
    LocateUpdateDirectory || {
        Locate7zUpdate && LocateUpdateDirectory;
    }
    if [ "$?" = "0" ]; then
        if [ "$UPDATE_FOLDER" != "notset" ]; then
            logger -s -p "user.info" -t "$0" "Update folder is: '$UPDATE_FOLDER'"

            extractsw $UPDATE_FOLDER

            if checkIfBadUpdate "$UPDATE_FOLDER"; then
                logger -s -p "user.info" -t "$0" "Bad or old firmware, stop update"
                echo "$(date) - Bad or old firmware, stop update" >> "$UPD_LOG"
                if [ "$UPDATE_FOLDER" != "/mnt/sd/gwupd" ]; then
                    mv $UPDATE_FOLDER ${UPDATE_FOLDER}_done
                fi
                clear_update_dir
            else
                run_update
            fi

        fi
    fi

    logger -s -p "user.info" -t "$0" "telem-update finished"
}
stop() {
    return 0
}
restart() {
    return 0
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit $?
