#!/bin/bash
# rhcsa-exam - runs the RHCSA practice exam on server1 the way the real exam runs:
#   the clock lives in the lab, time-up ends the exam whether you are done or not,
#   and grading happens automatically after a reboot. You never run the grader yourself.
#
#   sudo rhcsa-exam start     start the 3-hour exam (use --drill for 45 minutes)
#   rhcsa-exam status         time left
#   sudo rhcsa-exam end       end the exam now: reboot, then automatic grading
#   rhcsa-exam result         your result after grading
#   sudo rhcsa-exam reset     forget the current attempt (restore your exam-start snapshot instead if you can)
S=/var/lib/rhcsa-exam; G=/usr/local/lib/rhcsa-exam/check.sh
SITE=https://rhcsa-practice-exam.pages.dev
B=$'\e[1m'; Y=$'\e[1;33m'; GR=$'\e[1;32m'; RD=$'\e[1;31m'; N=$'\e[0m'
now(){ date +%s; }
need_root(){ [ "$(id -u)" = 0 ] || { echo "Run it with sudo: sudo rhcsa-exam $1"; exit 1; }; }
hms(){ local s=$1; [ "$s" -lt 0 ] && s=0; printf "%d:%02d:%02d" $((s/3600)) $((s%3600/60)) $((s%60)); }
state(){ cat $S/state 2>/dev/null || echo none; }
issue(){ mkdir -p /etc/issue.d /etc/motd.d; printf '%s\n' "$1" > /etc/issue.d/rhcsa-exam.issue; printf '%s\n' "$1" > /etc/motd.d/rhcsa-exam; }

banner_running(){ issue "
  RHCSA practice exam in progress. Log in to continue. Time left: rhcsa-exam status
"; }

case "$1" in
start)
  need_root start
  case "$(state)" in running) echo "An exam is already running. $(hms $(( $(cat $S/end) - $(now) ))) left."; exit 1;;
                     grading) echo "This exam is being graded. Reboot server1 to finish grading."; exit 1;;
                     graded) echo "This server already has a graded attempt. Restore your exam-start snapshot for a fresh exam (or: sudo rhcsa-exam reset)."; exit 1;; esac
  MIN=${RHCSA_MINUTES:-180}; [ "$2" = --drill ] && MIN=${RHCSA_MINUTES:-45}
  mkdir -p $S; [ "$2" = --drill ] && echo drill > $S/mode || echo full > $S/mode; echo $(now) > $S/start; echo $(( $(now) + MIN*60 )) > $S/end; : > $S/warned; echo running > $S/state
  systemctl enable --now rhcsa-exam.timer >/dev/null 2>&1
  banner_running
  cat <<EOF

${B}RHCSA EX200 practice exam started.${N}  Time allowed: ${Y}$(hms $((MIN*60)))${N}

  Important information (read it, just like on exam day):
  * You are working on ${B}server1${N}. The tasks are on the exam page: ${SITE}
  * The root password is unknown. Task 1 is to recover it.
  * ${B}repo.lab.example${N} (192.168.50.1) is already configured. Do not change it.
  * Your work is graded ${B}after a reboot${N}. Anything that does not survive a reboot scores zero.
  * No internet. man pages and /usr/share/doc are allowed.
  * When time is up the exam ends, server1 reboots and is graded, whether you are finished or not.
  * Finished early? Run: ${B}sudo rhcsa-exam end${N}

  Good luck.
EOF
  ;;
status)
  case "$(state)" in
    running) L=$(( $(cat $S/end) - $(now) )); echo "RHCSA practice exam: $(hms $L) left (ends $(date -d @"$(cat $S/end)" '+%H:%M'))";;
    grading) echo "Exam over. Grading runs after the reboot.";;
    graded)  echo "Exam graded. See: rhcsa-exam result";;
    *)       echo "No exam running. Start one with: sudo rhcsa-exam start";; esac
  ;;
end|timeup)
  need_root "$1"; [ "$(state)" = running ] || { echo "No exam is running."; exit 1; }
  if [ "$1" = end ] && [ -t 0 ]; then
    L=$(( $(cat $S/end) - $(now) )); read -r -p "End the exam now with $(hms $L) left? server1 will reboot and be graded. Type END to confirm: " a
    [ "$a" = END ] || { echo "Exam continues."; exit 0; }
  fi
  echo $(now) > $S/stopped; echo grading > $S/state
  issue "
  RHCSA practice exam over. server1 is grading your work, please wait...
"
  if [ "$1" = timeup ]; then wall "RHCSA practice exam: TIME IS UP. server1 reboots in 10 seconds and is graded." 2>/dev/null; sleep 10
  else wall "RHCSA practice exam ended. server1 reboots now and is graded." 2>/dev/null; sleep 2; fi
  systemctl reboot
  ;;
tick)   # run every minute by rhcsa-exam.timer (and shortly after every boot)
  case "$(state)" in
    grading)
      # wait until server1 has finished booting and its network is up, like a grader that connects once the system is up
      for i in $(seq 1 120); do systemctl is-active -q multi-user.target && break; sleep 5; done
      nm-online -s -q -t 180 2>/dev/null || true
      for i in $(seq 1 24); do [ -n "$(nmcli -t -f DEVICE,STATE dev 2>/dev/null | grep -v -e ':connected$' -e ':unmanaged$' -e ':unavailable$' -e '^lo:')" ] || break; sleep 5; done
      sleep 30
      bash $G > $S/report.raw 2>&1
      sed 's/\x1b\[[0-9;]*m//g' $S/report.raw > $S/report.txt
      P=$(sed -n 's/^Score: \([0-9]*\) .*/\1/p' $S/report.txt); CODE=$(grep -o 'RHCSA-PE1-[0-9A-F]*-[0-9A-F]*' $S/report.txt)
      P=${P:-0}; echo $((P*15)) > $S/score; echo "$CODE" > $S/code; echo graded > $S/state
      [ $((P*15)) -ge 210 ] && V=PASS || V="NOT YET"
      if [ "$(cat $S/mode)" = drill ]; then HEAD="RHCSA practice drill graded. Paste the code on the exam page to score your 5 drill tasks."
      else HEAD="RHCSA practice exam graded:  $((P*15)) / 300  ($V, pass mark 210)"; fi
      issue "
  $HEAD
  Result code: $CODE
  Log in and run: rhcsa-exam result     Score report: $SITE
"
      systemctl disable --now rhcsa-exam.timer >/dev/null 2>&1
      ;;
    running)
      L=$(( $(cat $S/end) - $(now) ))
      for w in 1800 600 300 60; do
        if [ "$L" -le $w ] && [ "$L" -gt 0 ] && ! grep -qx $w $S/warned; then echo $w >> $S/warned
          wall "RHCSA practice exam: $(( (L+59)/60 )) minutes left." 2>/dev/null; fi
      done
      [ "$L" -le 0 ] && exec "$0" timeup
      ;;
  esac
  ;;
result)
  [ "$(state)" = graded ] || { "$0" status; exit 1; }
  SC=$(cat $S/score); [ "$SC" -ge 210 ] && V="${GR}PASS${N}" || V="${RD}NOT YET${N}"
  echo; echo "${B}RHCSA practice exam result${N}"
  if [ "$(cat $S/mode)" = drill ]; then echo "  Drill graded. The exam page scores just your 5 drill tasks from the code below."
  else echo "  Score: ${B}$SC / 300${N}   $V   (pass mark 210)"; fi
  echo "  Time used: $(hms $(( $(cat $S/stopped) - $(cat $S/start) )))"
  echo; echo "  Result code: ${Y}$(cat $S/code)${N}"
  echo "  Paste it at $SITE for your score report, task review and study plan."
  if [ "$2" = --details ]; then echo; grep -E '^(PASS|FAIL)' $S/report.txt; else echo "  (Task-by-task details: rhcsa-exam result --details)"; fi
  echo
  ;;
reset)
  need_root reset; rm -rf $S; rm -f /etc/issue.d/rhcsa-exam.issue /etc/motd.d/rhcsa-exam; systemctl disable --now rhcsa-exam.timer >/dev/null 2>&1
  echo "Attempt cleared. Note: this does not undo your changes to server1. For a true fresh start, restore the exam-start snapshot."
  ;;
*) sed -n '2,11p' "$0" | sed 's/^# \{0,1\}//';;
esac
