#!/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

  echo "$local_checksum" > /home/bus/config/$update_file.checksum
  echo "$file_version" > /home/bus/config/$update_file.version

  tar -zxf $update_file

  if [[ ! -d ./mnt/data2/config ]] ; then
    echo "Legacy update did not find 'mnt/data2/config', not going further"
    exit 0
  fi

  # We are specifically only interested in:
  # - *.paddle
  # - avls_freq.txt
  # - drivers.txt
  # - init.scm
  # - rules.scm
  # - rfid_patterns.txt
  #
  # only look for those files and deposit them in the appropriate place
  #

  find ./mnt/data2/config -name '*.paddle' -type f | \
    xargs -n1 -I{} cp -f {} /home/bus/config

  if [[ -e ./mnt/data2/config/avls_freq.txt ]] ; then
    cp -f ./mnt/data2/config/avls_freq.txt /home/bus/config/avls_freq.txt
  fi

  if [[ -e ./mnt/data2/config/drivers.txt ]] ; then
    cp -f ./mnt/data2/config/drivers.txt /home/bus/config/drivers.txt
  fi

  if [[ -e ./mnt/data2/config/init.scm ]] ; then
    cp -f ./mnt/data2/config/init.scm /home/bus/config/init.scm
  fi

  if [[ -e ./mnt/data2/config/rules.scm ]] ; then
    cp -f ./mnt/data2/config/rules.scm /home/bus/config/rules.scm
  fi

  if [[ -e ./mnt/data2/config/rfid_patterns.txt ]] ; then
    cp -f ./mnt/data2/config/rfid_patterns.txt /home/bus/config/rfid_patterns.txt
  fi


  exit 0
fi

exit 1
