#!/usr/bin/env bash
# REMEMBER WHEN YOU EDIT THIS SCRIPT TO UPLOAD THE NEW VERSION ON
# debian.rossinienergy.com SERVER: web FOLDER: /www/repo/anyhelpers/

set -euo pipefail

if [[ $EUID -ne 0 ]];
then
    echo "Run as root"
    exit 1
fi

case "$1" in
    pilotage|standard-raspberry|standard_raspberry|stdrpi)
        PACKAGE="standard-raspberry"
        ;;
    ipsum)
        PACKAGE="ipsum"
        ;;
    *)
        echo "invalid param \"$PACKAGE\". Choose between pilotage/standard-raspberry and ipsum"
        exit 1
esac


# log [echo-args] [--no-header] <text>...
# Prints <text> to stderr.
# - echo-args: an arbitrary number of arguments starting with '-' to pass to `echo`.
# - --no-header: avoid writing the header in the message
# - <text>: an arbitrary number of arguments to print
#
# Forwards to 'echo' each argument starting with `-`, then an header
#  unless --no-header is specified, then the <text>. The whole output is
#  redirected to stderr.
function log {
    local echo_args="";
    local header="[first-boot] ";
    while [[ $# -gt 0 ]] && [[ $(echo "${1}x" | head -c 1) == '-' ]];
    do
        if [[ "$1" == "--no-header" ]];
        then
            header="";
        else
            echo_args="${echo_args} $1";
        fi;
        shift;
    done;
    echo $(printf "%s" "${echo_args}") "${header}"$@ | tee -a build.log >&2;
}


# 1. install the required software
log "[1.1] apt updating"
apt update -y
log "[1.2] apt upgrading"
apt upgrade -y
log "[1.3] apt installing needed programs"
apt install -y mutt vim neovim expect tmux byobu avrdude
debconf-set-selections <<< "postfix postfix/mailname string raspberrypi"
debconf-set-selections <<< "postfix postfix/main_mailer_type string 'local-only'"
apt-get install --assume-yes postfix

log "[1.4] downloading vimrc"
wget --output-document /home/pi/.vimrc http://debian.rossinienergy.com/anyhelpers/vimrc
mkdir -p /home/pi/.config/nvim
wget --output-document /home/pi/.config/nvim/init.vim http://debian.rossinienergy.com/anyhelpers/init.vim

# 2. download and import the gpg repo key
# 3. import the gpg repo key into apt's keyring
log "[2.1] downloading gpg repo key"
wget http://debian.rossinienergy.com/rossinienergydpkg1.gpg
log "[2.2] importing gpg repo key"
gpg --import rossinienergydpkg1.gpg
log "[3.1] importing gpg repo key into apt keyring"
apt-key add rossinienergydpkg1.gpg

# 4. add the RE repo to the sources list
log "[4.1] add RossiniEnergy repository"
echo "deb http://debian.rossinienergy.com/ /" > /etc/apt/sources.list.d/rossinienergy.list

# 5. update, upgrade, install standard-image-suite
log "[5.1] apt updating"
apt update -y
log "[5.2] apt upgrading"
apt upgrade -y
log "[5.3] apt installing standard-image-suite"
apt install -y standard-image-suite

# 6. install pilotage/ipsum
log "[6.1] apt installing software '${PACKAGE}'"
apt install "${PACKAGE}"
if [[ "${PACKAGE}" == "standard-raspberry" ]];
then
    systemctl disable --now "${PACKAGE}"
fi

log "[7.1] (nothing)"

# 8.
log "[8.1] configuring journal"
journal_file="/etc/systemd/journald.conf"
journal_size="2G"
if grep -q 'Storage=' "${journal_file}";
then
    echo 'Storage=persistent'
    sudo mkdir -p /var/log/journal
    sudo systemd-tmpfiles --create --prefix /var/log/journal
else
    sed -i "s/.*Storage=.*/Storage=persistent/g" "${journal_file}"
fi

if grep -q 'SystemMaxUse=' "${journal_file}";
then
    echo "SystemMaxUse=${journal_size}" >> "${journal_file}"
else
    sed -i "s/.*SystemMaxUse=.*/SystemMaxUse=${journal_size}/g" "${journal_file}"
fi

log "[8.2] restarting the journald service"
systemctl restart systemd-journald

# (download stuff for lechacal - other 13.x will be performed later)
log "[13.1] downloading lechacal software"
wget lechacal.com/RPICT/tools/lcl-upload-sketch_v2.zip

# 9. install the 3G key stuff
log "[9.1] downloading the 3G key stuff"
wget "http://debian.rossinienergy.com/anyhelpers/setup_eg25.sh"
log "[9.2] installing the 3G key stuff"
bash ./setup_eg25.sh

log "[9.3] configuring the interfaces"
sed -i 's/auto wlan0/#auto wlan0/g' /etc/network/interfaces
sed -i 's/allow-hotplug wlan0/#allow-hotplug wlan0/g' /etc/network/interfaces
sed -i 's/iface wlan0 inet dhcp/#iface wlan0 inet dhcp/g' /etc/network/interfaces
# if grep -q 'wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf';
# then
#     echo "wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf" >> /etc/network/interfaces
# else
#     sed -i 's/.*(wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf).*/\1/g' /etc/network/interfaces
# fi

# 10. configure the serial port
log "[10.1] configuring the serial port"
raspi-config nonint do_serial 2
log "[10.2] disabling bluetooth"
echo "dtoverlay=pi3-disable-bt" >> /boot/config.txt
stty -F /dev/ttyAMA0 raw speed 38400

# 11. configure SPI
log "[11.1] configuring the SPI"
raspi-config nonint do_spi 0

# 12. 13.
# wget http://debian.rossinienergy.com/anyhelpers/lcl-rpict-config.py
# wget http://debian.rossinienergy.com/anyhelpers/rpict8.conf
# wget http://debian.rossinienergy.com/anyhelpers/rpict8stack.conf
log "[12.1] (nothing)"

# From: https://wiki.rossinienergy.com/en/software/how_to_configure_measurement_board
log "[13.2] unzipping and installing lechacal software"
unzip lcl-upload-sketch_v2.zip
cd lcl-upload-sketch
sudo ./install.sh
cd

# 14.
# readonly this_station_mac="$(ip addr show eth0 | grep ether | awk '{ print $2 }')"
# sed -i "s/(readonly first_image_mac=).+/\1'${this_station_mac}'/g" /usr/bin/first_boot.sh
log "[14.1] enabling first boot service"
systemctl enable first_boot.service

# 15. clear the journal
log "[15.1] clearing the journal"
sudo journalctl --rotate --vacuum-files 1
