#!/bin/bash
#by Ruhsen K.

progname=$(<.progname)
progold=$progname"_old"
DLPROGDIR="tmp"
front="::"
file_updateinfo=".updateinfo"
prgrunok=".prgrunok"
while :
do
  echo $front "Executing" "'"$progname $@"'"
  rm -f $prgrunok
  ./$progname $@
  ret=$?
  echo $front "Exit code is" $ret
  if [ $ret -ne 9 ] && [ $ret -ne 99 ]; then
    if test -f $prgrunok; then
      echo $front "$prgrunok exist, normally exit"
    else
      echo $front "$prgrunok NOT exist, checking" $progold "..."
      if test -f $progold; then
        echo $front $progold "exist, Updated program was FAULTY. Previous program loaded ..."
        echo "0,Updated program was FAULTY. Previous program loaded ...">$file_updateinfo
        rm -f $progname
        mv $progold $progname
        continue
      else
        echo $front $progold "NOT exist, normally exit"
      fi
    fi
    break
  fi
  if [[ $ret -eq 99 ]]; then
    echo $front "Updating ..."
    if test -f $DLPROGDIR/$progname; then
      rm -f $progold
      mv $progname $progold
      cp $DLPROGDIR/$progname .
      chmod +x $progname
      echo "1,Update SUCCESS">$file_updateinfo
    else
      echo $front $DLPROGDIR/$progname "not found!"
      echo "0,$DLPROGDIR/$progname not found!">$file_updateinfo
    fi
  else
    echo $front "Restarting ..."
  fi
  sleep 1
done
