#!/bin/bash


TITLE='Euro3G - Fatture fornitori'
APPIMAGE="./FattureFornitoriE3G-x86_64.AppImage"
cd /opt/euro-beta

if [ -n "$1" ]
then 
  APPIMAGE=$1
fi

if [ -n "$2" ]
then 
  TITLE="$2"
fi


source /opt/euro-beta/set3g_env
if ! which sysquery >/dev/null 2>&1
then
  PATH=$PATH:/opt/euro-beta
fi
if [ -z "$DISPLAY" ]
then
  export DISPLAY=:0
fi




UBUNTU=`lsb_release -a 2>/dev/null | grep -qi "Ubuntu" && echo "1"`
PLATFORM64=`uname -a 2>/dev/null | grep -qi "_64" && echo "1"`


if [ "$UBUNTU" -a "$PLATFORM64" ]
then

{

  SHOULD_DOWNLOAD="0"
  if [ ! -f "./$APPIMAGE" ]
  then

    
    sysquery "$TITLE" "<b>Volete installare l'applicazione $TITLE ?</b>" "Si, procedere" "No, non fare niente"
    if [ $? != 0 ]
    then
      exit 0
    fi
    SHOULD_DOWNLOAD="1"
  fi

  if [ "$APPIMAGE" ]
  then

    wget -qO /tmp/appimage_md5 www.spintec.it/storage/e3g_install/${APPIMAGE}.md5
    NEW_MD5=`cat /tmp/appimage_md5`
    ACT_MD5=`md5sum ./$APPIMAGE | cut -d ' ' -f1`
    if [ "$NEW_MD5" != "$ACT_MD5" ]
    then
      sysquery "$TITLE" "<b>Volete aggiornare l'applicazione $TITLE alla versione piu' recente ?</b>" "Si, procedere" "No, non fare niente"
      if [ $? -eq 0 ]
      then
        SHOULD_DOWNLOAD="1"
        cp ${APPIMAGE} ${APPIMAGE}.old
        rm -f ${APPIMAGE}
      fi
    fi

    if [ "$SHOULD_DOWNLOAD" == "1" ]
    then
      TMPRUN=`mktemp`
      echo "#!/bin/bash" > $TMPRUN
      echo "wget -nv --show-progress www.spintec.it/storage/e3g_install/$APPIMAGE" >> $TMPRUN
      echo "chmod +x ./$APPIMAGE" >> $TMPRUN
      chmod +x $TMPRUN
#      ./show_process_output -T "Installazione di $TITLE" $TMPRUN
      ./show_process_output -T "Installazione di $TITLE" $TMPRUN
      rm -f $TMPRUN
    fi

    CURR_DESKTOP=`wmctrl -d | grep '*' | cut -d' ' -f 1`
    CURR_DESKTOP=$(( $CURR_DESKTOP + 0 ))
    wmctrl -s 2
    ./$APPIMAGE

    FF=$!
    for ((i=0; i<20; i++))
    do
      sleep 0.1
      wmctrl -r "$TITLE" -t 2
      wmctrl -a "$TITLE"
    done
    wait $FF
    wmctrl -s $CURR_DESKTOP
  fi
} &

else
  ./sysmsg "$TITLE" "Applicazione e' disponibile solo per UBUNTU 18 (64bit) o superiore"  
fi

