#!/usr/bin/bash
# slos-security [/absolute/path/to/scriptlets] [--reconfig]
SecLog="/root/install/security.log"
mkdir -p /root/install
echo "Initializing slos-security Scripts.."
sleep .1
wipefiles() {
   shred -n 13 -z -u /tmp/slossec.conf /tmp/test$$ "$@" 2>/dev/null
}

trap "wipefiles /tmp/test*" 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/securityDone $PROG/securityStarted
        ;;
    *)
        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

if [ -e $PROG/securityDone ] ; then
   systemctl disable slos-security.service
   systemctl enable getty\@tty1.service

   echo "Note: $0 has previously been run. exiting." >> $SecLog
   echo "Note: $0 has previously been run. exiting."
   exit
fi
if [ -f $PROG/securityStarted ] ; then
    echo "$0 is in progress, please wait to complete"
    echo "$0 is in progress, please wait to complete" >> $SecLog
    sleep 2
    touch $PROG/securityDone ; /bin/rm -f $PROG/securityStarted

else
    touch $PROG/securityStarted
fi

# execute slos-security scriptlets
echo 1. execute slos-security scriptlets
log 1. execute slos-security scriptlets
sleep .1
for script in $PROG/[0-9][0-9]-* ;  do
    if [ -e $script ] ; then
        # source each script, all env vars live across all scripts
          echo "BEG: $script" >> $SecLog
          source $script $OPTS
          echo "END: $script" >> $SecLog
        # If a script exits with 69, it means quit slos-security
        if [ "$RC" == "69" ] ; then
            echo "$0: Error $script exiting...!!!" ; sleep 3
            break
        fi
    fi
done

log "2. Completed slos-security scriptlets"
sleep .1
# Cleanup the slos-security scripts
# /bin/rm -f $PROG/*
touch $PROG/securityDone && /bin/rm -f $PROG/securityStarted

systemctl disable slos-security.service
systemctl enable getty\@tty1.service
echo "$0 completed" >> $SecLog
echo "$0 completed"
sleep .1

# Reboot necessary for security configurations setup and firstboot. For ex. Selinux, SCAP-USGCB
printf "\nRebooting now into full system.\n\n"
read -t 10 A
if [ "$A" == "q" ] ; then
    /bin/bash
else
echo    /sbin/reboot -n -f -d 1
fi

