#!/bin/bash
#
# © 2026 IACA Electronique — All rights reserved.
#
# Usage: patch.sh ASSETS_BASE_URL
#
# Exit codes:
#   0  — Success
#   1  — Script not run as root
#   2  — Missing ASSETS_BASE_URL argument
#  10  — Unable to load OS version file
#  11  — OS not compatible with this patch
#  12  — Patch already installed
#  13  — Unable to remount filesystem as read-write
#  14  — Failed to download new watchdog daemon
#  15  — Failed to backup existing watchdog daemon
#  16  — Failed to replace watchdog daemon script
#  17  — Failed to set watchdog daemon executable
#  18  — Failed to write patch fingerprint to version file

# ****************************************** PARAMETERS *******************************************

PATCH_ID="p262501"
COMPATIBLE_OS=("ot-rev8" "ot-rev9")

ASSETS_BASE_URL=${1}
WORKING_DIR=$(mktemp -d)
DATE_SUFFIX=$(date +%Y%m%d_%H%M%S)

WD_DAEMON="watchdog-daemon.sh"
WD_DAEMON_FULLPATH="/root/optimum/watchdog-daemon.sh"

VERSION_FILE="/etc/iaca/version"
CURRENT_OS_VERSION=

# ******************************************* FUNCTIONS *******************************************

function load() {
    local version_file="$VERSION_FILE"
    if ! CURRENT_OS_VERSION=$(cat "$version_file"); then
        return 1
    fi
}

# Checks whether the device OS matches one of the entries in COMPATIBLE_OS.
# Returns: 0 = compatible, 1 = incompatible OS.
function check_that_os_is_compatible() {
    local current_version=${CURRENT_OS_VERSION}

    for os in "${COMPATIBLE_OS[@]}"; do
        if [[ "$current_version" == *"$os"* ]]; then
            return 0
        fi
    done

    return 1
}

function add_patch_fingerprint() {
    sed -i "1s/$/ ${PATCH_ID}/" "$VERSION_FILE"
}

function check_that_patch_is_not_already_installed(){
    if [[ "$CURRENT_OS_VERSION" == *"$PATCH_ID"* ]]; then
      return 1
    else
      return 0
    fi
}

function download() {
    local filename="${1}"
    local output="${WORKING_DIR}/${filename}"
    local url="${ASSETS_BASE_URL}/${filename}"

    curl -fsSL "$url" -o "$output"
}

function unlock_fs(){
  if ! sudo mount -o remount,rw /; then
    return 1
  fi
}

function log() {
    echo -e "\e[3;38;5;250m${1}\e[0m"
}

function success() {
    echo -e "\e[1;32m${1}\e[0m"
}

function usage() {
    echo "$0 ASSETS_BASE_URL"
}

function error() {
    echo -e "\e[31mERROR: ${1}\e[0m"
}

# ********************************************* MAIN **********************************************

if [ "$EUID" -ne 0 ]; then
    error "Please run as root."
    exit 1
fi

if [ -z "${ASSETS_BASE_URL}" ]; then
    error "Bad usage."
    usage
    exit 2
fi

load || { error "Unable to load script."; exit 10; }

check_that_os_is_compatible || { error "OS is not compatible with this patch (current = '$CURRENT_OS_VERSION')."; exit 11; }
check_that_patch_is_not_already_installed || { error "Patch already installed."; exit 12; }

unlock_fs || { error "Unable to unlock filesystem."; exit 13; }
log "Filesystem unlocked."

download "${WD_DAEMON}" || { error "Unable to download ${WD_DAEMON}"; exit 14; }
log "New watchdog daemon downloaded."

cp "${WD_DAEMON_FULLPATH}" "${WD_DAEMON_FULLPATH}.${DATE_SUFFIX}.old" || { error "Unable to backup old watchdog daemon script (${WD_DAEMON_FULLPATH})."; exit 15; }
log "Old watchdog daemon backuped."

mv "${WORKING_DIR}/${WD_DAEMON}" "${WD_DAEMON_FULLPATH}" || { error "Unable to replace watchdog daemon script (${WD_DAEMON_FULLPATH})."; exit 16; }
log "New watchdog daemon installed."

chmod +x "${WD_DAEMON_FULLPATH}" || { error "Unable to set watchdog daemon executable."; exit 17; }

rm -rf "${WORKING_DIR}" || { echo "Warning: Unable to clear working directory."; }
log "Working directory cleaned."

add_patch_fingerprint || { error "Unable to add fingerprint patch in version file."; exit 18; }

success "Patch applied. Please reboot the board."

exit 0