#!/bin/bash

# Help message
if [[ -z "$1" || "$1" == "-h" || "$1" == "--help" || "$1" == "/?" ]]; then
    echo
    echo Automated capsule update script
    echo ----------------------
    echo
    echo "arg0 -> BIOS cabinet package (.cab) file path to install as the new BIOS image."
    echo "arg1 -> (optional) Set this to -R to automatically trigger REBOOT after installing the package"
    echo         NOTE: depending on the system, this may require ROOT permissions!
    echo "arg2 -> (only with "-R") Set this to a number: this is the number of seconds platform waits before rebooting"
    echo
    echo Examples:
    echo
    echo   update.sh seco_AmstonLake_E89_bios_9AADA203_1-06-11_20260113_Evaluation-only.cab
    echo     Install the cabinet package, but do not trigger the BIOS update yet. It will be triggered on next reboot.
    echo
    echo   update.sh seco_AmstonLake_E89_bios_9AADA203_1-06-11_20260113_Evaluation-only.cab -R 5
    echo     Install the driver. The platform is rebooted after 5 seconds, triggering the BIOS update.
    echo
    exit 0
fi

if [[ "$EUID" -ne 0 ]]; then
  echo "Error: This script must be run as root (use sudo)." >&2
  exit 1
fi

CONF_FILE="/etc/fwupd/fwupd.conf"
FLAG_NAME="DisableCapsuleUpdateOnDisk"

if [[ ! -f "$CONF_FILE" ]]; then
    echo "Config file $CONF_FILE does not exist."
    exit 1
fi

# Parse the config, ignoring commented lines, check if flag is true (case-insensitive)
flag_value=$(grep -i "^\s*${FLAG_NAME}\s*=" "$CONF_FILE" | grep -vi "^\s*#" | head -n1 | cut -d'=' -f2 | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')

if [[ "$flag_value" != "true" ]]; then
    echo "$FLAG_NAME is not set to true in $CONF_FILE"
    echo Please, set it in order to move on:
    echo
    echo 'echo -e "\n[uefi_capsule]\nDisableCapsuleUpdateOnDisk=true" | sudo tee -a /etc/fwupd/fwupd.conf'
    echo
    echo NOTE: reboot is required in order for this setting to take effect!!!
    echo
    echo Please, try again after performing the suggested action.
    exit 1
fi

if ! fwupdmgr install $1 --no-reboot-check; then
  echo "fwupdmgr failed."
  exit 1
fi

# Check for -R flag as second argument
if [[ "$2" != "-R" ]]; then
    echo "Optional flag -R not present. BIOS update is triggered on next reboot."
    exit 0
fi

# Check for countdown seconds
if [[ -z "$3" || ! "$3" =~ ^[0-9]+$ ]]; then
    echo "Error: Countdown time must be a positive integer."
    exit 1
fi

COUNTDOWN="$3"

echo
echo "Platform is rebooting in $COUNTDOWN seconds..."
echo

for ((i=COUNTDOWN; i>0; i--)); do
    echo "Rebooting in $i..."
    sleep 1
done

# Reboot the system (this may require sudo/root)
reboot