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

echo "# Popufare DIU package installer script"

tarball="package.tgz"

BINDIR="/home/bus/bin"
CONFIGDIR="/home/bus/config"
BINLIST="avls billdb client_supervisor debug_client diu_minder gps_minder ipc_server paddlemgr passdb piu_minder send_billing_record send_magstrip"
SCRIPTLIST="apply_update.sh apply_update_legacy.sh apply_update_popufare.sh common_values.sh connection_tether.sh fix_pkg_perm.sh get_net_ids.sh init_bus.sh update_loop.sh showmessage setup-serial.py"

if [[ ! -e /home/bus/config/popufare.witness ]] ; then
  echo "# Popufare system is not detected! Assuming legacy system and aborting install but populating checksum and version files"
  exit 0
fi

killall client_supervisor ; sleep 5 ;

tmpdir=`mktemp -d`
tar -C $tmpdir -zxf $tarball
pushd $tmpdir > /dev/null

  if [[ ! -e ./popufare.witness ]] ; then
    echo "# Could not find local 'popufare.witness'. Are you sure you're installing this from a package?"
    echo ""

    popd > /dev/null

    rm -rf $tmpdir
    exit 1
  fi

  ./build_all.sh native

  # These represent the most common files that are going to need to be
  # updated.
  # Other system files, like rc.local, the PPP config files, etc.
  # can also be updated as needed, but for now the focus is on
  # the binaries and scripts located in /home/bus/.
  #
  for binfn in $BINDLIST ; do
    rm -f $BINDIR/$binfn
    cp -L bin/native/$binfn $BINDIR/$binfn
  done

  for scriptfn in $SCRIPTLIST ; do
    rm -f $BINDIR/$scriptfn
    cp -L scripts/$scriptfn $BINDIR/$scriptfn
  done

  rm -rf $CONFIGDIR/html
  cp -L -R DIUv2/html $CONFIGDIR/

  # Misc. scripts/programs missed by the above
  #
  rm -f $BINDIR/diu_kiosk
  cp -L DIUv2/diu_kiosk $BINDIR/

  rm -f $BINDIR/reset-gps
  cp -L scripts/reset-gps.py $BINDIR/reset-gps

  # Indicate we have a Popufare installation
  #
  touch $CONFIGDIR/popufare.witness

  # install site specific files
  #
  for fn in `find site -type f` ; do
    dstfn=`echo $fn | sed 's;^site;;'`
    cp -L $fn $dstfn
  done

popd > /dev/null

sleep 1
touch /tmp/reboot_flag

echo "Done."

exit 0
