#!/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/
# scp generate_image_v2025.sh web:/www/repo/anyhelpers
#
# To flash the initial image: (first check if /dev/sda is correct with lsblk)
# sudo dd if=2025-10-01-raspios-trixie-arm64-lite.img of=/dev/sda bs=4M conv=fsync oflag=direct status=progress
# Initialize with user: pi, passwd: raspberry
# 
# To bootstrap:
# sudo raspi-config nonint do_wifi_country FR
# sudo raspi-config nonint do_ssh 0
# sudo nmcli dev wifi connect SSID password PASSWORD
# wget https://debian.rossinienergy.com/anyhelpers/generate_image_v2025.sh
# sudo bash generate_image_v2025.sh

set -euo pipefail

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

# The scripts expects to run as root inside the main user home
cd /home/pi

# Prompt for version
read -p "Enter the version to write into the image, like v0.0.1: " VERSION
echo "${VERSION}" > /etc/re_version

# 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="[generate_image] ";
    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;
}


log "-[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 external programs"
apt install -y mutt vim expect tmux byobu wireguard kitty-terminfo python3-dev mosh
log "[1.4] apt install neovim separately"
apt install -y neovim
log "[1.5] apt install and configure postfix for cron email logs"
debconf-set-selections <<< "postfix postfix/mailname string raspberrypi"
debconf-set-selections <<< "postfix postfix/main_mailer_type string 'local-only'"
apt install -y postfix

log "-[2]- Download support files"
log "[2.1] downloading vim and nvim config from anyhelpers"
wget --output-document /home/pi/.vimrc http://debian.rossinienergy.com/anyhelpers/vimrc
chown pi:pi /home/pi/.vimrc
mkdir -p /home/pi/.config/nvim
wget --output-document /home/pi/.config/nvim/init.vim http://debian.rossinienergy.com/anyhelpers/init.vim
chown -R pi:pi /home/pi/.config

log "-[3]- Configure RossiniEnergy repository" 
log "[3.1] downloading gpg repo key"
wget http://debian.rossinienergy.com/rossinienergydpkg1.gpg
log "[3.2] importing gpg repo key to root keyring for copy"
gpg --import rossinienergydpkg1.gpg
log "[3.3] importing gpg repo key into apt keyring"
mv rossinienergydpkg1.gpg /etc/apt/keyrings/
log "[3.4] add RossiniEnergy repository to apt sources"
echo "deb [signed-by=/etc/apt/keyrings/rossinienergydpkg1.gpg] http://debian.rossinienergy.com/repos/v2025 /" > /etc/apt/sources.list.d/rossinienergy.list

# 5. update, upgrade, install standard-image-suite
log "-[4]- Install RossiniEnergy softwares"
log "[4.1] apt updating"
apt update -y
log "[4.2] apt upgrading"
apt upgrade -y

PACKAGE="vivaldi-client"
log "[4.3] apt installing ${PACKAGE} as enabled with service mask"
systemctl mask "${PACKAGE}.service"
apt install -y "${PACKAGE}"
systemctl unmask "${PACKAGE}.service"
systemctl enable "${PACKAGE}"

log "[4.4] apt installing standard-image-suite"
apt install -y standard-image-suite
log "[4.4.1] temporary allow incoming ssh"
ufw allow ssh

PACKAGE="standard-raspberry"
log "[4.5] apt installing ${PACKAGE} as disabled with service mask"
systemctl mask "${PACKAGE}.service"
apt install -y "${PACKAGE}"
systemctl unmask "${PACKAGE}.service"
systemctl disable --now "${PACKAGE}"

log "[4.6] apt installing modbus helper scripts"
apt install -y re-modbus-tools

PACKAGE="bonknet-client"
log "[4.7] apt installing ${PACKAGE} as enabled with service mask"
systemctl mask "${PACKAGE}.service"
apt install -y "${PACKAGE}"
systemctl unmask "${PACKAGE}.service"
systemctl enable "${PACKAGE}"

log "[4.8] apt installing re-supervisor"
apt install -y re-supervisor
log "[W] re-supervisor will try to send data during this session"

log "[4.9] apt installing watchdog-client"
apt install -y watchdog-client

log "-[5]- Configure WWAN"
# log "[5.1] downloading Huawei setup script"
# wget "http://debian.rossinienergy.com/anyhelpers/setup_eg25.sh"
# log "[5.2] running Huawei setup script"
# bash ./setup_eg25.sh
log "[5.3] install Webbing configuration"
nmcli c a type gsm ifname '*' con-name webbing apn wbdata

log "-[6]- Configure WLAN"
log "[6.1] set wifi country to FR"
raspi-config nonint do_wifi_country FR
log "[6.2] disable wifi power save"
raspi-config nonint do_wifi_power_save 1

# log "[6.3] configuring network/interfaces file for proper wifi handling"
# 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

log "-[7]- Configure Hardware Interfaces"
# log "[7.1] configuring the serial port ON but without Login Shell"
# raspi-config nonint do_serial_cons 1
# raspi-config nonint do_serial_hw 0
# log "[7.2] configuring the SPI"
# raspi-config nonint do_spi 0
# log "[7.3] configuring the I2C ON"
# raspi-config nonint do_i2c 0
log "[7.4] disabling bluetooth"
echo "dtoverlay=disable-bt" >> /boot/firmware/config.txt
log "[7.5] expose UART0 RTS on GPIO 17"
echo "gpio=17=a3" >> /boot/firmware/config.txt
log "[7.6] throttle I2C"
echo "dtparam=i2c_arm_baudrate=10000" >> /boot/firmware/config.txt
log "[7.7] enable internal watchdog"
echo "dtparam=watchdog=on" >> /boot/firmware/config.txt

log "-[8]- Finalization"
log "[8.1] enabling first boot service"
systemctl enable first_boot.service
log "[8.2] assure SSH is configured"
raspi-config nonint do_ssh 0
log "[8.3] remove SSH temporary allow from firewall"
ufw delete allow ssh

log "[8.4] clearing the journal"
sudo journalctl --rotate --vacuum-files 1

log "### Image Generated, you can delete this file, poweroff and take the image ###"
