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

. /usr/local/bin/telem/functions

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

FOLDER_BIN=/usr/bin		# Executables
FOLDER_LIB=/usr/lib		# Shared libraries
FOLDER_TEMP=/tmp		# Temporary files
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"
        cd $FOLDER_TEMP
        logger -s -p "user.info" -t "$0" "Extracting tarball"
        /usr/bin/tar -x $ARC_FILTER -f $TARBALL

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





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
            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
            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 && {
                    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
	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

    UPDATE_FOLDER=notset

    return 1
}



###############################################################################
#                                                                             #
#                                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
    if [ -e /dev/mmcblk0p1 ]; then
        mkdir -p $SDD
        mount /dev/mmcblk0p1 $SDD
    else
        ln -s /dev/null $SDD
    fi



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

            #
            #   Run update
            #
            run_update

        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 $?
