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

GITURL="https://tree.clementinecomputing.com/clementinecomputing/popufare"

echo ""
echo '  _____                   __               '
echo ' |  __ \                 / _|              '
echo ' | |__) |__  _ __  _   _| |_ __ _ _ __ ___ '
echo ' |  ___/ _ \| '"'"'_ \| | | |  _/ _` | '"'"'__/ _ \'
echo ' | |  | (_) | |_) | |_| | || (_| | | |  __/'
echo ' |_|   \___/| .__/ \__,_|_| \__,_|_|  \___|'
echo '            | |                            '
echo '            |_|                            '
echo ""
echo "This script attempts to setup a default installation of Popufare on a busunit (a Raspberry Pi, say)"
echo "by setting up and configuring the system."
echo ""
echo "THIS SCRIPT CHANGES SYSTEM WIDE PARAMETERS AND COULD HAVE SERIOUS CONSEQUENCES TO THE MACHINE IT'S RUN"
echo "ON."
echo ""
echo "As such, this scripts needs root access (via sudo)."
echo "This script is meant to be a 'helper' script and isn't meant to be all encompassing. Among other things,"
echo "this script will:"
echo ""
echo "  * setup a 'bus' user and group"
echo "  * add the 'pi' user to the 'bus' group"
echo "  * clone the Popufare repo, build it's binaries and install them in the '/home/bus' user directory"
echo "  * copy over appropriate config files to the appropriate locations in the '/hom/ebus' user directory"
echo "  * setup ssh keys and credentials"
echo "  * setup the PPP config files"
echo "  * alter /boot/config.txt and /etc/modules to enable serial and sound setup"
echo "  * setup a 'kiosk' service for the front end DIU"
echo "  * setup 'rc.local' to start and monitor bus Popufare services on startup"
echo "  * setup legacy data directories in '/mnt/data2'"
echo ""
echo "Most parameters have options to prompt the user for installation."
echo ""
echo "This script should be used with caution and as a helper for an installation rather than a 'turn key' soluation."
echo "For example, the ssh keys default to the UNSECURE 'snakeoil' default keys provided the repo for easy setup and"
echo "MUST BE CHANGED for a production installation."
echo ""
echo "In addition, the host and other config file options should be set on a per installation basis, as should the custom"
echo "DIU interface, rules, drivers.txt entries, etc."
echo ""
echo "This script should help in getting a Raspberry Pi ready for use with Popufare but should be thought of also as a"
echo "record of what relevant files there are to change and where to look."
echo ""
echo "As Popufare matures, this installation script or something similar can accomodate a more seamless installation but"
echo "this is what is provided now."
echo ""
echo "Popufare is free software so please feel free to contribute at:"
echo ""
echo "           https://tree.clementinecomputing.com/clementinecomputing/popufare"
echo ""

echo -n "Hit return to continue [ok]: "
read hitreturn

###### basic sanity checks to make sure we're installing on a Raspberry Pi
######

if [[ ! -e /etc/os-release ]] ; then

  echo -n "Are you sure you want to install? '/etc/os-release' does not exist and this system might not be a Raspberry Pi. Continue? [y/N]: "
  read fnfok

  if [[ ! "$fnfok" =~ ^[yY]$ ]] ; then
    echo "cancelling installalation"
    echo ""
    exit
  else
    echo "ok, continuing installation..."
  fi

else

  grep -P '^PRETTY_NAME="Raspbian' /etc/os-release 2>&1 > /dev/null
  r=$?
  if [[ $r != 0  ]] ; then

    echo -n "Raspbian not detected in '/etc/os-release'. This might not be Raspberry Pi. Continue with installation? [y/N]: "
    read okcontinue

    if [[ ! "$okcontinue" =~ ^[yY]$ ]] ; then
      echo "cancelling installation"
      echo ""
      exit
    else
      echo "ok, continuing installation..."
    fi

  fi

fi

echo ""

######
######

echo -n "Create 'bus' user? [Y/n]: "
read createbususer

if [[ "$createbususer" =~ ^[yY]?$ ]]; then
  echo "... creating 'bus' user and group"
  sudo adduser bus
  sudo usermod -a -G dialout bus
fi

echo ""

echo -n "Add 'pi' to 'bus' group? [Y/n]: "
read addpibus

if [[ "$addpibus" =~ ^[yY]$ ]]; then
  echo "... add 'pi' to 'bus' group"
  sudo usermod -a -G bus pi
fi

echo ""

echo "Creating /home/bus/(bin|database|config) with group write permissions"

sudo mkdir -p /home/bus/bin
sudo mkdir -p /home/bus/database
sudo mkdir -p /home/bus/config

sudo chown -R bus:bus /home/bus/bin
sudo chown -R bus:bus /home/bus/database
sudo chown -R bus:bus /home/bus/config

sudo chmod -R g+w /home/bus/bin
sudo chmod -R g+w /home/bus/database
sudo chmod -R g+w /home/bus/config

echo ""

echo -n "Repo path (hit return to automatically clone the repo and use that) []: "
read repolocation

tmpdir=""
if [[ "$repolocation" == "" ]] ; then
  tmpdir=`mktemp -d`
  repolocation="$tmpdir/popufare"

  pushd $tmpdir
  git clone "$GITURL"
  popd
fi

echo "Setting up binaries..."

bd=/home/bus/popufare/busunit
d=/home/bus/popufare/busunit/bin/native
diudir=/home/bus/popufare/busunit/DIUv2
tc=/home/bus/popufare/busunit/testing/config

sudo cp -R $repolocation /home/bus
sudo chown -R bus:bus /home/bus/popufare
sudo bash -c " su - bus -c ' cd /home/bus/popufare/busunit ; ./build_all.sh native ; ' "
sudo bash -c " cd /home/bus/bin ; ln -sf $d/avls . ; ln -sf $d/billdb . ; ln -sf $d/client_supervisor . ; ln -sf $d/debug_client . ; ln -sf $d/diu_minder . ; ln -sf $d/ipc_server . "
sudo bash -c " cd /home/bus/bin ; ln -sf $d/paddlemgr . ; ln -sf $d/passdb . ; ln -sf $d/piu_minder . ; ln -sf $d/send_billing_record . ; ln -sf $d/send_magstripe . "
sudo bash -c " cd /home/bus/bin ; ln -sf $d/gps_minder . "

sudo bash -c " cd /home/bus/bin ; ln -sf $bd/DIUv2/diu_kiosk . "

sudo bash -c " cd /home/bus/bin ; ln -sf $bd/scripts/init_bus.sh . ; ln -sf $bd/scripts/update_loop.sh . ; ln -sf $bd/scripts/setup-serial.py . ; ln -sf $bd/scripts/get_net_ids.sh . "
sudo bash -c " cd /home/bus/bin ; ln -sf $bd/scripts/connection_tether.sh . ; ln -sf $bd/scripts/reset-gps.py ./reset-gps "

sudo bash -c " cd /home/bus/bin ; ln -sf $bd/scripts/apply_update.sh . ; ln -sf $bd/scripts/apply_update_legacy.sh . ; ln -sf $bd/scripts/apply_update_popufare.sh "
sudo bash -c " cd /home/bus/bin ; ln -sf $bd/scripts/fix_pkg_perm.sh . "

sudo bash -c " cd /home/bus/config ; ln -sf $diudir/html . ; "
sudo bash -c " cd /home/bus/config ; cp $bd/passdb/init.scm . ; cp $bd/passdb/rfid_patterns.txt . ; cp $bd/avls/avls_freq.txt . "
sudo bash -c " cd /home/bus/config ; cp $bd/passdb/init.scm . ; cp $bd/passdb/rfid_patterns.txt . ; cp $bd/avls/avls_freq.txt . "

sudo bash -c " cd /home/bus/config ; cp $tc/equipnum.txt . ; cp $tc/serial.txt serial_num "

sudo bash -c " rm -f /home/bus/bin/common_values.sh ; cp $bd/scripts/common_values.sh /home/bus/bin "

## server endpoint config files
##
## sync_server_desc, sync_target, server_list, syn_port
sudo cp /home/bus/popufare/busunit/testing/config/config.tgz.checksum /home/bus/config/config.tgz.checksum
sudo cp /home/bus/popufare/busunit/testing/config/config.tgz.version /home/bus/config/config.tgz.version
sudo cp /home/bus/popufare/busunit/testing/config/firmware.tgz.checksum /home/bus/config/firmware.tgz.checksum
sudo cp /home/bus/popufare/busunit/testing/config/firmware.tgz.version /home/bus/config/firmware.tgz.version
sudo cp /home/bus/popufare/busunit/testing/config/package.tgz.checksum /home/bus/config/package.tgz.checksum
sudo cp /home/bus/popufare/busunit/testing/config/package.tgz.version /home/bus/config/package.tgz.version

sudo mkdir -p /home/bus/config/server

echo ""

##### paddle setup
#####

echo -n "Setup paddles? [Y/n]: "
read setuppaddles

if [[ "$setuppaddles" =~ ^[yY]?$ ]] ; then
  echo -n "Paddle location? (blank for default testing paddles) []: "
  read paddlocation

  if [[ "$paddlelocation" == "" ]] ; then
    paddlelocation=$bd/busunit/testing
  fi

  echo "Using '$paddlelocation/*.paddle'..."

  sudo bash -c " cd /home/bus/config ; cp $bd/testing/*.paddle . "
fi

echo ""

##### rules setup
#####

echo -n "Setup rules? [Y/n]: "
read setuprules

if [[ "$setuprules" =~ ^[yY]?$ ]] ; then
  echo -n "Rule file? (blank for default testing rules) []: "
  read rulelocation

  if [[ "$rulelocation" == "" ]] ; then
    rulelocation=$bd/testing/rules-ORG.scm
  fi

  echo "Setting up rules from '$rulelocation'..."

  sudo bash -c " cd /home/bus/config ; cp $rulelocation rules.scm "
fi

echo ""

##### equipment number setup
#####

echo -n "Equipment number? [9999]: "
read equipnum

if [[ "$equipnum" == "" ]] ; then
  equipnum=9999

fi

echo "Setting equipment number to '$equipnum'..."
sudo bash -c " echo $equipnum > /home/bus/config/equipnum.txt "

echo ""

##### key setup
#####

echo -n "Setup secure communcation setup? [Y/n]: "
read tunnelsetup

if [[ "$tunnelsetup" =~ ^[yY]?$ ]] ; then

  echo -n "  'id_rsa' private key location? (default to snakeoil) []: "
  read keylocation

  if [[ "$keylocation" == "" ]] ; then
    keylocation=/home/bus/popufare/server/docker/snakeoil_id_rsa
  fi

  echo "  Using '$keylocation' for private key..."

  sudo mkdir -p /home/bus/.ssh
  sudo chown -R bus:bus /home/bus/.ssh

  sudo cp $keylocation /home/bus/.ssh/id_rsa_bus
  sudo chown bus:bus /home/bus/.ssh/id_rsa_bus
  sudo chmod 400 /home/bus/.ssh/id_rsa_bus

  echo ""

  echo -n "  Tunnel port? [6055]: "
  read tunnelport

  if [[ "$tunnelport" == "" ]] ; then
    tunnelport=6055
  fi

  echo ""

  echo -n "  Tunnel user and host? [bus@example.com]: "
  read tunnelhost

  if [[ "$tunnelhost" == "" ]] ; then
    tunnelhost='bus@example.com'
  fi

  echo ""

  echo -n "  Adding values to '/home/bus/bin/common_values.sh'..."

  sed -i 's;^SSH_DEFAULT_TARGET=;#SSH_DEFAULT_TARGET=;g' /home/bus/bin/common_values.sh
  sed -i 's;^SSH_DEFAULT_PORT=;#SSH_DEFAULT_PORT=;g' /home/bus/bin/common_values.sh
  sed -i 's;^SSH_DEFAULT_IDENTITY=;#SSH_DEFAULT_IDENTITY=;g' /home/bus/bin/common_values.sh

  sed -i 's;^SSH_TARGET=;#SSH_TARGET=;g' /home/bus/bin/common_values.sh
  sed -i 's;^SSH_PORT=;#SSH_PORT=;g' /home/bus/bin/common_values.sh
  sed -i 's;^SSH_IDENTITY=;#SSH_IDENTITY=;g' /home/bus/bin/common_values.sh

  echo 'SSH_DEFAULT_TARGET="'"$tunnelhost"'"' >> /home/bus/bin/common_values.sh
  echo 'SSH_DEFAULT_PORT="'"$tunnelport"'"' >> /home/bus/bin/common_values.sh
  echo 'SSH_DEFAULT_IDENTITY="/home/bus/.ssh/id_rsa_bus"' >> /home/bus/bin/common_values.sh
  echo '' >> /home/bus/bin/common_values.sh
  echo 'SSH_TARGET="$SSH_DEFAULT_TARGET"' >> /home/bus/bin/common_values.sh
  echo 'SSH_PORT="$SSH_DEFAULT_PORT"' >> /home/bus/bin/common_values.sh
  echo 'SSH_IDENTITY="$SSH_DEFAULT_IDENTITY"' >> /home/bus/bin/common_values.sh

  echo ""

fi

echo ""

##### drivers setup
#####

echo -n "'drivers.txt' location? (default to test) []: "
read driverlocation

if [[ "$driverlocation" == "" ]] ; then
  driverlocation=/home/bus/popufare/busunit/DIUv2/drivers.txt
fi

echo "Using '$driverlocation' for drivers.txt ..."

sudo cp $driverlocation /home/bus/config

echo ""

##### setup fona ppp
#####

echo -n "Setup FONA ppp files? [Y/n]: "
read setupfona

if [[ "$setupfona" =~ ^[yY]?$ ]] ; then
  echo "  /home/bus/popufare/busunit/ppp-dialer/etc/ppp/peers/fona -> /etc/ppp/peers/gprs"
  echo "  /home/bus/popufare/busunit/ppp-dialer/etc/chatscripts/gprs -> /etc/chatscripts/gprs"

  sudo cp /home/bus/popufare/busunit/ppp-dialer/etc/ppp/peers/fona /etc/ppp/peers/gprs
  sudo cp /home/bus/popufare/busunit/ppp-dialer/etc/chatscripts/gprs /etc/chatscripts/gprs

  echo ""

fi

#echo -n "Setup FONA to connect at startup? [Y/n]: "
#read fonanetwork
#
#if [[ "$fonanetwork" =~ ^[yY]?$ ]] ; then
#  echo "  Creating '/etc/network/interfaces.d/fona'..."
#  sudo echo 'auto fona' > /etc/network/interfaces.d/fona
#  sudo echo 'iface fona inet ppp' >> /etc/network/interfaces.d/fona
#  sudo echo '  provider fona' >> /etc/network/interfaces.d/fona
#fi

##### Setup config.txt
#####

echo -n "Setup '/boot/config.txt'? (Note this could have serious consequences, use with caution) [y/N]: "
read setupconfig

if [[ "$setupconfig" =~ ^[yY]$ ]] ; then
  tmpfn=`mktemp`
  bfn=`basename $tmpfn`

  echo "  Saving 'config.txt' to /root/$bfn"
  sudo cp /boot/config.txt $tmpfn
  sudo mv $tmpfn /root/$bfn

  echo "  adding> enable_uart=1"
  sudo sed -i 's;^enable_uart=;#enable_uart=;g' /boot/config.txt
  sudo bash -c 'echo "enable_uart=1" >> /boot/config.txt'

  echo "  adding> dtoverlay=pi3-disable-bt"
  sudo sed -i 's;^dtoverlay=pi3-disable-bt;#dtoverlay=pi3-disable-bt;g' /boot/config.txt
  sudo bash -c 'echo "dtoverlay=pi3-disable-bt" >> /boot/config.txt'

  echo "  adding> dtoverlay=pi3-disable-wifi"
  sudo sed -i 's;^dtoverlay=pi3-disable-wifi;#dtoverlay=pi3-disable-wifi;g' /boot/config.txt
  sudo bash -c 'echo "dtoverlay=pi3-disable-wifi" >> /boot/config.txt'
fi

echo ""

##### Setup sound in modules file
#####

echo -n "Setup sound (alter '/etc/modules')? [y/N]: "
read setupsound

if [[ "$setupsound" =~ ^[yY]$ ]] ; then
  tmpfn=`mktemp`
  bfn=`basename $tmpfn`

  echo "  Saving 'modules' to /root/$bfn"
  sudo cp /etc/modules $tmpfn
  sudo mv $tmpfn /root/$bfn

  sudo sed -i 's;^snd-bcm2835;#snd-bcm2835;g' /etc/modules

  echo '  adding> snd-bcm2835'
  sudo bash -c 'echo "snd-bcm2835" >> /etc/modules'

  # disabled for now. Force audio to go through 3.5mm jack from 'raspi-config'.
  #
  # ...
  # trying to mitigate the 'first two seconds cutoff of audio' problem
  # https://github.com/alexa-pi/AlexaPi/wiki/Devices#raspberry-pi
  #
  #tfn=`mktemp`
  #echo '@reboot vcgencmd force_audio hdmi 1' > $tfn
  #echo "adding `cat $tfn`"
  #sudo crontab $tfn
  #rm $tfn

fi

##### Setup kiosk
#####

echo -n "Setup kiosk service? [Y/n]: "
read setupkiosk

if [[ "$setupkiosk" =~ ^[yY]?$ ]] ; then

  echo "  /home/bus/popufare/busunit/scripts/kiosk.service -> /lib/systemd/system/kiosk.service"
  sudo cp /home/bus/popufare/busunit/scripts/kiosk.service /lib/systemd/system/kiosk.service

  echo "  enabling kiosk.service ('systemctl enable kiosk.service')"
  sudo systemctl enable kiosk.service

fi

echo ""


##### Setup startup
#####

echo -n "Setup startup 'rc.local'? [Y/n]: "
read setupstartup

if [[ "$setupstartup" =~ ^[yY]?$ ]] ; then

  tmpfn=`mktemp`
  bfn=`basename $tmpfn`

  echo "  saving /etc/rc.local to /root/$bfn"
  sudo cp /etc/rc.local $tmpfn
  sudo mv $tmpfn /root/$bfn


  echo "  /home/bus/popufare/busunit/scripts/rc.local -> /etc/rc.local"
  sudo cp /home/bus/popufare/busunit/scripts/rc.local /etc/rc.local

fi

echo ""


##### setup legacy data directories
#####

echo -n "Setup legacy data directories? [y/N]: "
read setuplegacy

if [[ "$setuplegacy" =~ ^[yY]$ ]] ; then
  sudo mkdir -p /mnt/data
  sudo mkdir -p /mnt/data2

  sudo chown -R bus:bus /mnt/data
  sudo chown -R bus:bus /mnt/data2
fi

#####
#####



##### final permissions setup
#####

echo "Setting up final permission for /home/bus/(bin|database|config)"

sudo chown -R bus:bus /home/bus/bin
sudo chown -R bus:bus /home/bus/database
sudo chown -R bus:bus /home/bus/config

echo ""


if [[ "$tmpdir" != '' ]] ; then
  echo "... should remove $tmpdir"
  #rm -rf  $tmdpri
fi

echo "done"
