#!/bin/bash

# Sets a wake-up alarm to power off and then wake the system after a
# specified interval in seconds (> 29 seconds).
# Requires root privileges

FORCE_MODE=0
MIN_INTERVAL=29
INTERVAL=""

usage() {
    echo "Usage: $0 [-f] <interval>"
    echo "  -f: Force setting the alarm without confirmation"
    echo "  <interval>: Time interval (must be greater than ${MIN_INTERVAL} seconds)"
}

is_number() {
    if ! [[ "$1" =~ ^[0-9]+$ ]]; then
        return 1 #
    else
        return 0 #
    fi
}

while getopts "f" opt; do
  case ${opt} in
    f )
      FORCE_MODE=1
      ;;
    \? )
      usage
      exit 1
      ;;
  esac
done
shift $((OPTIND -1))

# Check for interval argument
if [ -z "$1" ]; then
    usage
    exit 1
else
    INTERVAL="$1"
fi

if ! is_number "$INTERVAL"; then
    echo "Error: Interval must be a numeric value."
    exit 1
fi

if [ ${INTERVAL} -le ${MIN_INTERVAL} ]; then
    echo "Error: The interval must be greater than ${MIN_INTERVAL} seconds."
    exit 1
fi

if [ $FORCE_MODE -ne 1 ]; then
    read -p "Are you sure you want to power off and wake up the system in $INTERVAL seconds? (y/N) " CONFIRM
    case $CONFIRM in
        [Yy]* ) echo "The system will shut down and power on in ${INTERVAL} seconds. Please wait.";;
        * ) echo "System reboot cancelled."; exit;;
    esac
fi

# set the wake alarm
echo $(date '+%s' -d "+ ${INTERVAL} seconds") > /sys/class/rtc/rtc0/wakealarm && sleep 1

if [ $? -eq 0 ]; then
    logger "Forcing hard system reboot"
else
    logger "Failed to set wake alarm"
    exit 1
fi

# enable magic SysRqs and power off
echo 1 > /proc/sys/kernel/sysrq
echo o > /proc/sysrq-trigger

# we should never get here
logger "Hard system reboot failed"
