#!/usr/bin/sh
#
# Copyright 2021 IoT.bzh.
#
# Authors:
#  * Ronan Le Martret <ronan.lemartret@iot.bzh>
#  * Pierre Marzin <pierre.marzin@iot.bzh>
#
#
# The following script will run all the scriptlets found in /var/lib/rp-firstboot.

firstboot_dir="/var/lib/rp-firstboot"

POSTINST_LOGGING=1
LOG_FILE="/var/log/`basename ${firstboot_dir}`.log"
REBOOT_FILE="/tmp/rp-firstboot.reboot"
REBOOT_delay_s=15

[ -e $LOG_FILE ] && mv ${LOG_FILE} ${LOG_FILE}.old.$(date +%F--%H%M.%S)

exec_postinst_scriptlets() {
    for i in `ls -p $firstboot_dir | grep -v /`; do
        i=$firstboot_dir/$i
        echo "Running firstboot scriplet $i..."
        [ "$POSTINST_LOGGING" = "1" ] && eval echo "Running firstboot scriplet $i..." | tee -a $LOG_FILE
        if [ -x $i ]; then
            eval sh -c $i | tee -a $LOG_FILE
            if [ ! $? -eq 0 ]; then
                echo "ERROR: firstboot scriplet $i failed."
                [ "$POSTINST_LOGGING" = "1" ] && eval echo "ERROR: firstboot scriplet $i failed." | tee -a $LOG_FILE
            fi
        else
            echo "ERROR: firstboot scriplet $i do not exists or do not have execute permission."
            [ "$POSTINST_LOGGING" = "1" ] && eval echo "ERROR: firstboot scriplet $i do not exists or do not have execute permission." | tee -a $LOG_FILE
        fi
    done
}

exec_save_work() {
    systemctl daemon-reload

    if [ -f $REBOOT_FILE ]; then
        # Reboot the system after intalling all scriptlets if needed
        echo "WARN: System need to reboot in order to switch into read-only mode."
        echo "WARN: System will reboot in $REBOOT_delay_s seconds..."
        rm -f $REBOOT_FILE
        sleep $REBOOT_delay_s && systemctl reboot
    fi
}

exec_postinst_scriptlets
exec_save_work
