#!/usr/bin/bash
# firstboot [/absolute/path/to/scriptlets] [--reconfig]
FBLOG="/root/install/FirstBoot.log"
mkdir -p /root/install/
echo "Initializing $0 Scripts.."
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

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

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

if [ -f $PROG/Started ] ; then
    # Started exists but Done does not — firstboot was interrupted (e.g. mid-run reboot).
    # Remove the stale lock and restart firstboot from the beginning.
    log "Previous firstboot run was interrupted. Restarting."
    rm -f $PROG/Started
fi

touch $PROG/Started

# execute firstboot scriptlets with back navigation support
# preferred_order defines execution sequence — needed because Back navigation
# requires 21-addpass < 40-hostname < 30-network ordering
# which 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
    20-adduser 21-addpass 40-hostname 30-network
    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]}"
    BACK_TO=""
    source $script $OPTS
    rc=$?
    sleep .1

    if [ "$rc" == "69" ] ; then
        echo "$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
done
# Creating Completed Firstboot script by creating $PROG/Done file and Removing $PROG/Started
log "Creating Completed Firstboot script by creating $PROG/Done file and Removing $PROG/Started"
touch $PROG/Done 
/bin/rm -f $PROG/Started
sleep .3

systemctl disable slos-firstboot.service
rm -f /etc/systemd/system/default.target.wants/slos-firstboot.service

wall "System Setup in progress, wait for completion." 2>/dev/null

rc=0
# restart interfaces to pickup new IP
systemctl enable NetworkManager || { rc=1; log "Firstboot: failed to enable NetworkManager"; }
systemctl start NetworkManager || { rc=1; log "Firstboot: failed to start NetworkManager"; }
# restart SSH daemon to pickup new IP
systemctl enable sshd || { rc=1; log "Firstboot: failed to enable sshd"; }
systemctl start sshd || { 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/
    /bin/rm -f /{var/run,etc,run}/nologin 2>/dev/null
    touch $PROG/securityDone && /bin/rm -f $PROG/securityStarted
fi
echo "End slos-security.service"
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
systemctl disable console-getty.service
systemctl unmask getty\@tty1.service 2>/dev/null || true
systemctl enable getty\@tty1.service
systemctl restart getty\@tty1.service 2>/dev/null || systemctl start getty\@tty1.service
systemctl start getty.target 2>/dev/null || 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 
systemctl daemon-reload
if [ $? -ne 0 ] ; then
   echo 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\nRebooting now into full system.\n\n"
dmesg -n "$OLD_PRINTK" >/dev/null 2>&1 || true
/sbin/reboot -n -f -d 1

