#!/usr/bin/bash
# firstboot [/absolute/path/to/scriptlets] [--reconfig]
FBLOG="/root/install/FirstBoot.log"
mkdir -p /root/install/ 2>/dev/null || true
echo "Initializing $0 Scripts.." >> $FBLOG
date >> $FBLOG
sleep .1
# define log early so runner loop works before 00-screen is sourced
# 00-screen will redefine log() to use $LOG once it is sourced
log() { echo "$@" >> $FBLOG ; }
# reduce kernel console noise while dialog UI is active
OLD_PRINTK="$(cat /proc/sys/kernel/printk 2>/dev/null | awk '{print $1}')"
[ -n "$OLD_PRINTK" ] || OLD_PRINTK="4"
dmesg -n 1 >/dev/null 2>&1 || true

wipefiles() {
   shred -n 13 -z -u /tmp/slossec.conf /tmp/test$$ "$@" 2>/dev/null
   return 0
}

trap "wipefiles $tempfile" 0 1 2 5 15

OPTS=
PROG=
# parse cmd line opts
while [ $# -gt 0 ] ; do
    case $1 in
    /*)
        PROG=$1
        ;;
    --reconfig)
        if [ -z $2 ] ; then
            echo "Usage: $0 [--reconfig] PathToScripts" >&2
            exit 1
        fi
        PROG="$2"
        /bin/rm -f $PROG/Done $PROG/Started
        ;;
    *)
        echo "Usage: $0 [--reconfig] PathToScripts" >&2
        exit 1
    esac
    shift
done

if [ "$PROG" == "" ] ; then
   echo "ERROR: $0 requires argument as path to scriptlets."
   echo "Usage: $0 [--reconfig] PathToScripts" >&2
   exit 1
fi

# Save firstboot scripts directory to verify completion later
FIRSTBOOT_PROG="$PROG"

#Setting up the getty/console/screen
echo "1.Setting up the getty/console/screen" >> $FBLOG
log "1. Setting up the getty/console/screen"
sleep 2
if [ -e $PROG/Done ] ; then
    systemctl disable slos-firstboot.service >> "$FBLOG" 2>&1
    systemctl unmask getty\@tty1.service >> "$FBLOG" 2>&1 || true
    systemctl enable getty\@tty1.service >> "$FBLOG" 2>&1
    systemctl restart getty\@tty1.service >> "$FBLOG" 2>&1 || systemctl start getty\@tty1.service >> "$FBLOG" 2>&1
    systemctl start getty.target >> "$FBLOG" 2>&1 || true

    log "Note: $0 has previously been run. exiting."
   exit
fi

FIRSTBOOT_RESUME=0
if [ -f $PROG/Started ] ; then
    # Started exists but Done does not — firstboot was interrupted (e.g. mid-run reboot).
    # Force mode selection on this run.
    FIRSTBOOT_RESUME=1
    # Remove the stale lock and restart firstboot from the beginning.
    log "Previous firstboot run was interrupted. Restarting."
    rm -f $PROG/Started 2>/dev/null || true
fi

touch $PROG/Started 2>/dev/null || true

# execute firstboot scriptlets with back navigation support
# preferred_order defines execution sequence — needed because Back navigation
# requires 40-hostname < 30-network < 21-addpass ordering so that network is
# configured (machine has an IP) before the password/SSH-key prompts, which
# download the public key over the network; this differs from numeric filename order
declare -a script_array
declare -A script_pos

preferred_order=(
    00-screen 01-backtitle 01-quit 01-addpass 01-adduser
    05-autoinst 06-skipinst
    40-hostname 30-network 20-adduser 21-addpass
    50-xterm 51-sshd_config 99-exit
)

# Build script array: preferred order first, then any remaining scripts
idx=0
for b in "${preferred_order[@]}" ; do
    [ -x "$PROG/$b" ] || continue
    script_array[$idx]="$PROG/$b"
    script_pos["$b"]=$idx
    idx=$((idx+1))
done
for s in $PROG/[0-9][0-9]-* ; do
    b=$(basename "$s")
    [ -x "$s" ] && [ -z "${script_pos[$b]}" ] || continue
    script_array[$idx]="$s"
    script_pos["$b"]=$idx
    idx=$((idx+1))
done

idx=0
while [ $idx -lt ${#script_array[@]} ] ; do
    script="${script_array[$idx]}"
    source $script $OPTS
    rc=$?
    sleep .1

    if [ "$rc" == "69" ] ; then
        log "$0: $script exiting..." ; sleep .1
        break
    fi

    # Back navigation: only when script explicitly sets BACK_TO
    if [ "$rc" == "1" ] && [ -z "$AUTOINST" ] && [ -n "$BACK_TO" ] ; then
        log "firstboot: back from $(basename $script) to $BACK_TO"
        if [ -n "${script_pos[$BACK_TO]}" ] ; then
            idx=${script_pos[$BACK_TO]}
        else
            idx=$((idx+1))
        fi
    else
        idx=$((idx+1))
    fi
    
    # Clear BACK_TO after navigation is complete for next iteration
    BACK_TO=""
done

systemctl disable slos-firstboot.service >> "$FBLOG" 2>&1
rm -f /etc/systemd/system/default.target.wants/slos-firstboot.service 2>/dev/null || true

log "System setup in progress, wait for completion."

# Keep a clean status UI visible while backend services/configuration finish.
$DIALOG --backtitle "$BT" --title "Firstboot" --infobox "\nPlease wait while we finish the final settings.\n" $H1 $W1

rc=0
# restart interfaces to pickup new IP
systemctl enable NetworkManager >> "$FBLOG" 2>&1 || { rc=1; log "Firstboot: failed to enable NetworkManager"; }
systemctl start NetworkManager >> "$FBLOG" 2>&1 || { rc=1; log "Firstboot: failed to start NetworkManager"; }
# restart SSH daemon to pickup new IP
systemctl enable sshd >> "$FBLOG" 2>&1 || { rc=1; log "Firstboot: failed to enable sshd"; }
systemctl start sshd >> "$FBLOG" 2>&1 || { rc=1; log "Firstboot: failed to start sshd"; }
# report any failure
if [ $rc -ne 0 ] ; then
    echo "Firstboot: Failures in network configuration" >>$FBLOG
fi
date >> $FBLOG

log "Begin slos-security Configuration" >>$FBLOG
PROG="/etc/hardening/hardening06/"
if [ -f /etc/slossec.conf ] && [ -x /etc/hardening/slos-enablesecurity ] ; then
    /etc/hardening/slos-enablesecurity /etc/hardening/hardening06/ >> /root/install/security.log 2>&1
    /bin/rm -f /{var/run,etc,run}/nologin 2>/dev/null
    touch $PROG/securityDone 2>/dev/null || true
    /bin/rm -f $PROG/securityStarted 2>/dev/null || true
fi
log "End slos-security.service" >>$FBLOG

#Setting up the getty/console/screen
log "2. Setting up the getty/console/screen" >> $FBLOG
mkdir -p /etc/systemd/system/getty.target.wants 2>/dev/null || true
systemctl disable console-getty.service >> "$FBLOG" 2>&1
systemctl unmask getty\@tty1.service >> "$FBLOG" 2>&1 || true
systemctl enable getty\@tty1.service >> "$FBLOG" 2>&1
systemctl restart getty\@tty1.service >> "$FBLOG" 2>&1 || systemctl start getty\@tty1.service >> "$FBLOG" 2>&1
systemctl start getty.target >> "$FBLOG" 2>&1 || true
#ln -sf /usr/lib/systemd/system/getty\@.service /etc/systemd/system/getty.target.wants/getty\@tty1.service
sleep .1
#systemctl enable console-getty.service

## Reload the system daemon 
if ! systemctl daemon-reload >> "$FBLOG" 2>&1 ; then
    log "SystemDaemon reload failed"
    sleep .1
fi
# Give sufficent time for other systemd process to finish.
echo "$0 completed" >>$FBLOG

log "\n\nFirstboot & Security setup completed.\n\n"
# Repaint final status screen while the last setup steps finish.
$DIALOG --backtitle "$BT" --title "Firstboot" --infobox "\nPlease wait while we finish the final settings.\n\nThe system will reboot automatically when complete.\n" $H1 $W1
sleep 2
# Mark firstboot complete after all setup is done.
log "Marking firstboot as complete and preparing to continue."
touch $FIRSTBOOT_PROG/Done 2>/dev/null || true
/bin/rm -f $FIRSTBOOT_PROG/Started 2>/dev/null || true

# Verify Done file was created before rebooting
if [ ! -f "$FIRSTBOOT_PROG/Done" ] ; then
    log "Firstboot did not complete properly. Restarting firstboot service to preserve state."
    systemctl restart slos-firstboot.service
    exit 1
fi

/sbin/reboot -n -f -d 1 >/dev/null 2>&1
