#!/bin/bash
#
# Copyright (c) 2019 Clementine Computing LLC.
# 
# This file is part of PopuFare.
# 
# PopuFare is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# PopuFare is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with PopuFare.  If not, see <https://www.gnu.org/licenses/>.
#

update_file="$1"
update_checksum="$2"
file_size="$3"
server_path="$4"
file_version="$5"

. /home/bus/bin/common_values.sh

# Confirm we have a checksum that differs from our existing checksum
#
if [[ -f /home/bus/config/$update_file.checksum ]] ; then
  existing_checksum=`cat /home/bus/config/$update_file.checksum`
  if [[ "$update_checksum" == "$existing_checksum" ]] ; then
    echo "We already HAVE an update $update_file with checksum $update_checksum, aborting install"
    exit 1
  fi
fi

local_checksum=`md5sum $update_file | cut -d' ' -f1`

# We are doing a 'legacy' install, so unpack the package locally and only
# check for appropriate files in the 'config' directory.
#
if [[ "$update_checksum" == "$local_checksum" ]] ; then

  tar -zxf $update_file install.sh

  if [ -n "$PACKAGE_OWNER_STRING" ]; then
    chown $PACKAGE_OWNER_STRING install.sh
  fi

  chmod $PACKAGE_BIN_PERMISSIONS install.sh

  if (./install.sh); then
    echo "$local_checksum" > /home/bus/config/$update_file.checksum
    echo "$file_version" > /home/bus/config/$update_file.version

    if [ "$FIX_PACKAGE_PERMS" -ne "0" ]; then

      if [ -f $EXTRACT_PATH_FILE ]; then
        pkg_path="`cat $EXTRACT_PATH_FILE`"
        echo "Fixing permissions from package specified path $pkg_path";
      else
        pkg_path="$DEFAULT_EXTRACT_PATH"
        echo "Fixing permissions from default path $pkg_path";
      fi

      /home/bus/bin/fix_pkg_perm.sh $update_file $pkg_path
    fi

    echo "Update $update_file successfully installed"
    rm -f $update_file
    rm -f $EXTRACT_PATH_FILE
    if [ -f /tmp/reboot_flag ]; then
      killall diu_minder
      echo "Tearing down network connection"
      if [ -f $SSH_TUNNEL_PIDFILE ]; then kill `cat $SSH_TUNNEL_PIDFILE`; sleep 30; fi
      /usr/bin/poff gprs
      shutdown -r now;
      sleep 1000;
    fi
    exit 0
  else
    echo "Update $update_file failed"
    rm -f $update_file
    exit 1
  fi
else
  echo "Update $update_file appears to be BOGUS:  Server MD5=$update_checksum Local MD5=$local_checksum"
  rm -f $update_file
  exit 1
fi

exit 1
