#!/bin/bash

newMd5=""
oldMd5=""

doLog() {
   logTime=$(date "+%Y-%m-%d %H:%M:%S")
   echo "$*"
   echo "${logTime}: $*">>/opt/ty/log/update.log
}

execThenRm() {
   cmd=$1

   if [ -e "$cmd" ]; then
      $cmd

      if [ -L "$cmd" ]; then
         rm $cmd
      fi
   fi
}

doTar() {
   srcPath="$3"
   md5="$4"

   if [ -z "$srcPath" ]; then
      srcPath="$1"
   else
      if [ -e "$srcPath" ]; then
         doLog "rm $srcPath"
         rm $srcPath
      fi

      doLog "cp -a $1 $srcPath"
      cp -a "$1" $srcPath
   fi

   if ! [ -z "$md5" ]; then
      srcMd5=$(md5sum "$srcPath")
      doLog "Check md5: $md5 <-> $srcMd5"

      if [ "${md5:0:32}" != "${srcMd5:0:32}" ]; then
         doLog "MD5 checksum does not match£º${md5:0:32} != ${srcMd5:0:32}"
         srcPath=""
         newMd5=""
      fi
   fi

   if ! [ -z "$srcPath" ]; then
      doLog "extract $srcPath to $2"
      tar zxvf "$srcPath" -C $2
   fi
}

doUpdate() {
   cmd=$1
   newMd5=""
   oldMd5=""

   if [ -e "$3" ]; then
      oldMd5=$(cat "$3")
   fi

   if [ -e "$4" ]; then
      newMd5=$(cat "$4")
   else
      newMd5=$(md5sum "$2")
   fi

   if [ "$oldMd5" == "$newMd5" ]; then
      if [ "$cmd" == "tar" ]; then
         doLog "$2 has extracted to /!"
      else
         doLog "$2 has executed!"
      fi

      doLog "No need for an update!"
   else
      ## echo "$newMd5">$3

      if [ "$cmd" == "tar" ]; then
         doLog "extract $2 to /"
         ## $cmd zxvf "$2" -C /
         doTar "$2" / "/opt/ty/bin/update.tz" "$newMd5"
      elif [ "$cmd" == "tdz" ]; then
         doLog "extract $2 to /opt"
         ## tar zxvf "$2" -C /opt
         doTar "$2" /opt "/opt/ty/bin/update.tdz" "$newMd5"
      elif [ -z "$5" ]; then
         doLog "execute $2"
         $cmd "$2"
      else
         doLog "execute $2 in $5"
         $cmd "$2" $5
      fi

      if ! [ -z "$newMd5" ]; then
         echo "$newMd5">$3
      fi
   fi
}

if ! [ -z "$1" ]; then
   ExecPath="$1"
elif [ -z "$updatePath" ]; then
   ExecPath=$(dirname "$0")
elif [ -z "$i" ]; then
   ExecPath="${updatePath}"
else
   ExecPath="$i/${updatePath}"
fi

if [ -e "${ExecPath}/update.tdz" ]; then
   doUpdate tdz "${ExecPath}/update.tdz" "/opt/ty/bin/update.md5" "${ExecPath}/update.md5"
elif [ -e "${ExecPath}/update.tz" ]; then
   doUpdate tar "${ExecPath}/update.tz" "/opt/ty/bin/update.md5" "${ExecPath}/update.md5"
else
   echo "No update found!"
fi

sleep 1

if [ -e "/opt/ty/update/init.sh" ]; then
   echo "Exec /opt/ty/update/init.sh"
   execThenRm "/opt/ty/update/init.sh"
fi
