#! /bin/sh

checkProcess ()
{
  FOUND="0"
  for i in $(ps ax | grep $1 | grep -v grep | awk '{print $1}')
  do
    FOUND="1"
  done
  if [ "$FOUND" -eq "1" ]; then
    return 1
  else
    return 0
  fi
}

# check temp file system
clearTemp() {
  CT_TMP_DIR_FILES="/var/log/*"
  for f in $CT_TMP_DIR_FILES
  do
    if [[ -f $f ]]; then
      minimumsize=20000
      maximumsize=30000
      actualsize=$(wc -c <"$f")
      if [ $actualsize -ge $maximumsize ]; then
          CT_TMP_FILE="/tmp/log.tmp"
          echo size  of $f is over $maximumsize bytes
          echo 1 > $f
#          tail -c $minimumsize $f > $CT_TMP_FILE
#          mv $CT_TMP_FILE $f
      fi
    fi
  done
  
  #drop caches
  sync && echo 3 > /proc/sys/vm/drop_caches
}

APP=hafa
iCnt=0
HAFA_DIR=/mnt/dezign
errFile=${HAFA_DIR}/work/err.log
START_LOG=/tmp/dzStart.log

iptables -F
iptables-restore < /etc/iptables/rules.v4

echo "deZign watchdog running (v1.0)"

echo "set system time to year 2000"
date -s "01/01/2000 12:00:00"
hwclock -w

if ! mount | grep /mnt/dezign > /dev/null; then
    echo "not mounted, wait a while"
    sleep 10
else
    echo "mounted"
fi

case $(uname -r) in
  '3.8.13-bone67' )
    echo 'old system (kernel 3.8.13)'
    systemctl stop apache2.service

    SYS_CAPE_MGR=/sys/devices/bone_capemgr.8
    
    if [ -d /sys/devices/bone_capemgr.9 ] ; then
      SYS_CAPE_MGR=/sys/devices/bone_capemgr.9
      echo "use cape manager 9"
    else
      echo "use cape manager 8"
    fi

    # has to be loaded first
    if ! cat ${SYS_CAPE_MGR}/slots | grep "DM-GPIO-Test" > /dev/null; then
      cp /home/root/de/dt/DM-GPIO-Test-00A0.dtbo /lib/firmware/
      sync
      echo "DM-GPIO-Test" > ${SYS_CAPE_MGR}/slots
    fi
    
    # analog ins: 
    if ! cat ${SYS_CAPE_MGR}/slots | grep "cape-bone-iio" > /dev/null; then
      echo "cape-bone-iio" > ${SYS_CAPE_MGR}/slots
    fi
    
    # spi for epdc
    if ! cat ${SYS_CAPE_MGR}/slots | grep "BB-SPI0-01" > /dev/null; then
      echo "BB-SPI0-01" > ${SYS_CAPE_MGR}/slots
    fi
    
    #we do not use lcd any more
    #if ! cat ${SYS_CAPE_MGR}/slots | grep "BB-SPI1-01" > /dev/null; then
    #  echo "BB-SPI1-01" > ${SYS_CAPE_MGR}/slots
    #fi
    
    # will become serial aux interface in rev03
    if ! cat ${SYS_CAPE_MGR}/slots | grep "BB-UART1" > /dev/null; then
      echo "BB-UART1" > ${SYS_CAPE_MGR}/slots
    fi

    if [ -f /etc/init.d/local.flash.dezign ]; then
      echo "remove dezign flasher start script"
      rm /etc/init.d/local.flash.dezign
    fi
    ;;
  '5.2.7-dezign' )
    echo 'new system (kernel 5.2.7)'
#    exit 0;
    ;;
esac

echo "deZign watchdog loop start"

mkdir -p ${HAFA_DIR}/update
mkdir -p ${HAFA_DIR}/work/ovpn

START_REASON='no app running'

INFO_TEST=""
if [ -f /home/root/test_epdc ]; then
  INFO_TEST="epdc"
  echo "init device for test" > /tmp/test.log
  tail -f /tmp/test.log &
fi

while true; do

  count=$(ls -l ${HAFA_DIR}/work/*.7z 2>/dev/null | wc -l)

  if [ -f /tmp/dzFlash.log ]; then
    rm /tmp/dzFlash.log
  fi

  if [ -f /opt/aristech/aritts/bin/aritts ]; then
    #check aristech server is running

    checkProcess /opt/aristech/aritts/bin/aritts
    if [ "$?" -eq "0" ]; then
      mkdir -p /var/log/aristech
      echo ""
      echo ""
      echo ""
      echo "***************************************************************"
      echo "aristech tts server not running, start the server"
      echo "***************************************************************"
      sleep 0.5
      /etc/init.d/aritts.sh start
    fi
  fi
  
  clearTemp

  killall -q -s KILL dzFlash

  if [ $count != 0 ]; then
    sleep 1
    echo "found new firmware (${count} files)"
    echo "activate high power"
    
    if ! command -v /usr/bin/cpufreq-set &> /dev/null
    then
        echo "cpufreq-set could not be found"
        if [ -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed ]; then
          echo 1000000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed
        fi
    else
      echo "activate high power"
      /usr/bin/cpufreq-set -f 1000MHz
    fi

#    killall $APP
    echo "advise application to exit graceful"
    /usr/bin/mqueue_push -m /dzMsgIn -p "exit application (delay:10)"
    sleep 20
    /usr/bin/mqueue_push -m /dzMsgIn -p "exit application"
    sleep 10
    killall -s KILL $APP

    for entry in ${HAFA_DIR}/work/*.7z
    do
      cd ${HAFA_DIR}
      
      rm -rf ${HAFA_DIR}/update

      if [ ! -d ${HAFA_DIR}/update ]; then
        mkdir ${HAFA_DIR}/update
      fi

      echo "extract files from update package : ${entry}"
      7za x -y $entry -o${HAFA_DIR}/update/
      
      echo "remove update package : ${entry}"
      rm $entry
      sync

      if [ -f ${HAFA_DIR}/update/update.sh ]; then
        chmod 755 ${HAFA_DIR}/update/update.sh
        echo "$(date) - process file ${entry}" >> ${HAFA_DIR}/work/device.history
        ${HAFA_DIR}/update/update.sh
      fi
      
      rm -r ${HAFA_DIR}/update/*
      START_REASON='new firmware'
    done
  fi

  # check other stuff
  if [ -d ${HAFA_DIR} ]; then

    checkProcess $APP
    if [ "$?" -eq "0" ]; then
      echo ""
      echo ""
      echo ""
      echo "***************************************************************"
      echo "deZign application not running"
      echo "***************************************************************"
      sleep 0.5
      if [ -f /usr/bin/hafa ]; then
        echo "starting deZign application"
        iCnt=$((iCnt + 1))
        $APP -serial/dev/ttyO1 -path${HAFA_DIR}/work/ -test=${INFO_TEST} -info"${START_REASON}" -cnt${iCnt} > /dev/null 2>&1 &
        echo "restartet application, wait a little bit longer"
        sleep 120
      else
        echo "app not present"
      fi
    fi

#    /usr/bin/mqueue_push -m /dzMsgIn -p "wdt: test"

    if [ -f /tmp/hafa.check ]; then
      rm /tmp/hafa.check
    else
      echo "hafa is not responding, kill it"
      killall -s KILL $APP
      echo "$(date) - killed hafa" >> /tmp/hafa.kill.log
      START_REASON='app killed, because not responding'
    fi
  else
    echo "no hafa work directory"
  fi


  sleep 60
done
