#!/bin/bash -e

set -euo pipefail

# ============================================================================
# Constants - D-Bus Interfaces and Objects
# ============================================================================
readonly INTERFACE_ROOT="xyz.openbmc_project"
readonly STATE_INTERFACE="${INTERFACE_ROOT}.State"
readonly CONTROL_INTERFACE="${INTERFACE_ROOT}.Control"

readonly OBJECT_ROOT="/xyz/openbmc_project"
readonly STATE_OBJECT="${OBJECT_ROOT}/state"
readonly CONTROL_OBJECT="${OBJECT_ROOT}/control"

# ============================================================================
# Constants - Systemd Targets and Directories
# ============================================================================
readonly BMC_SYSTEMD_RUN_DIR="/run/systemd/system/"
readonly HOST_TIMEOUT_TARGET="obmc-host-timeout@0.target"
readonly HOST_CRASH_TARGET="obmc-host-crash@0.target"

# ============================================================================
# Constants - BMC Reboot Guard
# ============================================================================
readonly BMC_REBOOT_GUARD_FILE="reboot-guard.conf"
readonly BMC_REBOOT_GUARD_UNITS=("reboot" "poweroff" "halt")

# ============================================================================
# Constants - Default Values
# ============================================================================
readonly DEFAULT_WAIT_TIMEOUT=30

# ============================================================================
# Usage and Help
# ============================================================================
readonly OPTS="bmcstate,bootprogress,chassiskill,chassisoff,chassison,chassisstate,hoststate,\
osstate,power,poweroff,poweron,state,status,hostrebootoff,hostrebooton,recoveryoff,recoveryon,\
bmcrebootoff, bmcrebooton, listbootblock listlogs showlog deletelogs, stopofftargets"

readonly USAGE="Usage: obmcutil [-h] [--wait] [--verbose] [--id=<INSTANCE_ID>]
{$OPTS}"

## NOTE: By declaring these globally instead of passing them through the
## intermediary functions, which may not be "best practice", the readability
## and cleanliness of the code should at least be increased.

# ============================================================================
# Global Variables
# ============================================================================
# The command passed in to be executed (e.g. poweron/off, status, etc.)
# This will be be used in some instances of error reporting
G_ORIG_CMD=
# The state an interface should be in after executing the requested command.
G_REQUESTED_STATE=
# The query to run during a poweron/off or chassison/off to check that
# the requested state (G_REQUESTED_STATE) of the interface has been reached.
G_QUERY=
# Wait the set period of time for state transitions to be successful before
# continuing on with the program or reporting an error if timeout reached.
G_WAIT=
# Print the journal to the console
G_VERBOSE=
# Instance id, default 0
G_INSTANCE_ID="0"
# Force a command even if system state is not correct
G_FORCE=

# ============================================================================
# Service Cache - Avoid repeated mapper lookups
# ============================================================================
declare -A G_SERVICE_CACHE

# ============================================================================
# Helper Functions
# ============================================================================

# Get service for an object with caching to avoid repeated mapper calls
function get_service()
{
    local object="$1"

    # Check cache first
    if [ -n "${G_SERVICE_CACHE[$object]:-}" ]; then
        echo "${G_SERVICE_CACHE[$object]}"
        return 0
    fi

    # Call mapper and cache result
    local service
    service=$(mapper get-service "$object")
    G_SERVICE_CACHE[$object]="$service"
    echo "$service"
}

function print_help()
{
    echo "$USAGE"
    echo ""
    echo "positional arguments:"
    echo "  {$OPTS}"
    echo ""
    echo "Examples:"
    echo ""
    echo "obmcutil hostrebootoff Disable auto reboot of Host from Quiesce state"
    echo "obmcutil hostrebootoffonetime Disable auto reboot of Host from"
    echo "                              Quiesce state for a single boot"
    echo "obmcutil hostrebooton   Enable auto reboot of Host from Quiesce state"
    echo ""
    echo "obmcutil bmcrebootoff   Disable reboot of BMC"
    echo "obmcutil bmcrebooton    Enable reboot of BMC"
    echo ""
    echo "obmcutil recoveryoff    Disable handling boot watchdog timeout and host crash"
    echo "                        Also, disable BMC and Host auto reboots"
    echo ""
    echo "obmcutil recoveryon     Enable handling boot watchdog timeout and host crash"
    echo "                        Also, enable BMC and Host auto reboots"
    echo ""
    echo "obmcutil recoverystatus Display the status of handling boot watchdog timeout and host crash"
    echo "                        and also the status of BMC and Host auto reboots setting"
    echo ""
    echo "obmcutil listbootblock  Check for and list any errors blocking the boot"
    echo "                        of the system"
    echo ""
    echo "obmcutil listlogs       List all phosphor-logging entries on the"
    echo "                        system"
    echo ""
    echo "obmcutil showlog <log>  Display details of input log. Format of <log>"
    echo "                        should match listlogs output"
    echo ""
    echo "obmcutil deletelogs     Delete all phosphor-logging entries from"
    echo "                        system"
    echo "obmcutil stopofftargets Manually stop all obmc targets in power off"
    echo "                        path"
    echo ""
    echo "optional arguments (must precede the positional options above):"
    echo "  -h, --help          show this help message and exit"
    echo "  -w, --wait          block until state transition succeeds or fails"
    echo "  -v, --verbose       print the journal to stdout if --wait is supplied"
    echo "  -i, -id             instance id, default 0"
    echo "  -f, --force         force issuing the command ignoring preconditions (use with caution)"
    exit 0
}

function run_timeout()
{
    local timeout="$1"; shift
    local cmd="$*"
    local verbose_child=

    if [ -n "$G_VERBOSE" ]; then
        journalctl -f &
        verbose_child=$!
    fi

    $cmd

    # Run a background query for the transition to the expected state
    # This will be killed if the transition doesn't succeed within
    # a timeout period.
    (
        while ! grep -q "$G_REQUESTED_STATE" <<< "$(handle_cmd "$G_QUERY")" ; do
            sleep 1
        done
    ) &
    wait_child=$!

    # Could be bad if process is killed before 'timeout' occurs if
    # transition doesn't succeed.
    trap -- "" SIGTERM

    # Workaround for lack of 'timeout' command.
    (
        sleep "$timeout"
        kill $wait_child
    ) > /dev/null 2>&1 &

    if ! wait $wait_child; then
        echo "Unable to confirm '$G_ORIG_CMD' success" \
            "within timeout period (${timeout}s)"
    fi

    if [ -n "$verbose_child" ]; then
        kill $verbose_child
    fi
}

function run_cmd()
{
    local cmd="$*";

    if [ -n "$G_WAIT" ]; then
        run_timeout "$G_WAIT" "$cmd"
    else
        $cmd
    fi
}

function set_property()
{
    run_cmd busctl set-property "$@"
}

function get_property()
{
    G_WAIT=""
    run_cmd busctl get-property "$@"
}

# Generic function to query and display state properties
function state_query()
{
    local state
    state=$(get_property "$@" | cut -d '"' -f2)
    printf "%-20s: %s\n" "$4" "$state"
}

# Helper to query state for a given object type
function query_state()
{
    local object_type="$1"
    local interface="$2"
    local property="$3"
    local instance="${4:-$G_INSTANCE_ID}"

    local object="${STATE_OBJECT}/${object_type}${instance}"
    local service
    service=$(get_service "$object")
    state_query "$service" "$object" "$interface" "$property"
}

# Helper to set a state transition property
function set_state_transition()
{
    local object_type="$1"
    local interface="$2"
    local property="$3"
    local value="$4"
    local instance="${5:-$G_INSTANCE_ID}"

    local object="${STATE_OBJECT}/${object_type}${instance}"
    local service
    service=$(get_service "$object")
    set_property "$service" "$object" "$interface" "$property" "s" "$value"
}

# Helper to set a control property
function set_control_property()
{
    local object_path="$1"
    local interface="$2"
    local property="$3"
    local type="$4"
    local value="$5"

    local service
    service=$(get_service "$object_path")
    set_property "$service" "$object_path" "$interface" "$property" "$type" "$value"
}

function print_usage_err()
{
    echo "ERROR: $1" >&2
    echo "$USAGE"
    exit 1
}

function mask_systemd_target()
{
    local target="$*"
    systemctl mask "$target" || {
        echo "ERROR: Failed to mask systemd target: $target" >&2
        return 1
    }
}

function unmask_systemd_target()
{
    local target="$*"
    systemctl unmask "$target" || {
        echo "ERROR: Failed to unmask systemd target: $target" >&2
        return 1
    }
}

function get_systemd_target_state()
{
    local target="$*"
    local enabled_state
    enabled_state=$(systemctl is-enabled "$target" 2>/dev/null) || enabled_state="unknown"
    echo "$enabled_state"
}

function disable_bmc_reboot()
{
    local unit
    for unit in "${BMC_REBOOT_GUARD_UNITS[@]}"; do
        mkdir -p "${BMC_SYSTEMD_RUN_DIR}${unit}.target.d"
        echo -e "[Unit]\nRefuseManualStart=yes" >> "${BMC_SYSTEMD_RUN_DIR}${unit}.target.d/${BMC_REBOOT_GUARD_FILE}"
    done
}

function enable_bmc_reboot()
{
    local unit
    for unit in "${BMC_REBOOT_GUARD_UNITS[@]}"; do
        rm -rf "${BMC_SYSTEMD_RUN_DIR}${unit}.target.d"
    done
}

function get_bmc_reboot_status()
{
    local unit
    for unit in "${BMC_REBOOT_GUARD_UNITS[@]}"; do
        if [ -e "${BMC_SYSTEMD_RUN_DIR}${unit}.target.d/${BMC_REBOOT_GUARD_FILE}" ]; then
            echo "off"
            return 0
        fi
    done
    echo "on"
    return 0
}

function get_host_reboot_status()
{
    local OBJECT=$CONTROL_OBJECT/host$G_INSTANCE_ID/auto_reboot
    local SERVICE
    SERVICE=$(get_service "$OBJECT")
    local INTERFACE=$CONTROL_INTERFACE.Boot.RebootPolicy
    local PROPERTY=AutoReboot
    local output
    output="$(get_property "$SERVICE" "$OBJECT" $INTERFACE $PROPERTY)"
    echo "${output//b /}"
}

# will write blocking errors to stdout
function check_boot_block_errors()
{
    local blockArray=()
    local subtree assocs entry berror

    # Look for any objects under logging that implement the
    # xyz.openbmc_project.Logging.ErrorBlocksTransition
    subtree="$(busctl call xyz.openbmc_project.ObjectMapper \
               /xyz/openbmc_project/object_mapper \
               xyz.openbmc_project.ObjectMapper \
               GetSubTree sias "/xyz/openbmc_project/logging/" 0 1 \
               xyz.openbmc_project.Logging.ErrorBlocksTransition)"

    subtree="${subtree//\"/}"

    for entry in $subtree; do
        if [[ ${entry} == xyz/openbmc_project/logging/block* ]]; then
            blockArray+=( "$entry" )
        fi
    done

    # now find associated error log for each boot block error
    for berror in "${blockArray[@]}"; do
        assocs="$(busctl call xyz.openbmc_project.Logging "$berror" \
                  org.freedesktop.DBus.Properties Get \
                  ss xyz.openbmc_project.Association.Definitions Associations)"

        assocs="${assocs//\"/}"

        for entry in $assocs; do
            if [[ ${entry} == xyz/openbmc_project/logging/entry* ]]; then
                echo "Blocking Error: $entry"
            fi
        done
    done
}

# check if system is in transitioning state for chassis or host and
# reject request if it is (if force option not set)
function check_chassis_host_states()
{
    # If user has --force enabled, no check
    if [ -n "$G_FORCE" ]; then
        return 0
    fi

    local OBJECT=$STATE_OBJECT/chassis$G_INSTANCE_ID
    local SERVICE
    SERVICE=$(get_service "$OBJECT")
    local INTERFACE=$STATE_INTERFACE.Chassis
    local PROPERTY=CurrentPowerState
    local state
    state=$(get_property "$SERVICE" "$OBJECT" "$INTERFACE $PROPERTY" | cut -d '"' -f2)
    if [[ ${state} =~ "xyz.openbmc_project.State.Chassis.PowerState.Transitioning"* ]]; then
        echo "Chassis is $state, request rejected, use --force to override"
        exit 1
    fi

    OBJECT=$STATE_OBJECT/host$G_INSTANCE_ID
    SERVICE=$(get_service "$OBJECT")
    INTERFACE=$STATE_INTERFACE.Host
    PROPERTY=CurrentHostState
    state=$(get_property "$SERVICE" "$OBJECT" "$INTERFACE $PROPERTY" | cut -d '"' -f2)
    if [[ ${state} =~ "xyz.openbmc_project.State.Host.HostState.Transitioning"* ]]; then
        echo "Host is $state, request rejected, use --force to override"
        exit 1
    fi
}

# helper function to check for boot block errors and notify user
function check_and_warn_boot_block()
{
    blockingErrors=$(check_boot_block_errors)
    if [ -n "$blockingErrors" ]; then
        echo !!!!!!!!!!
        echo "WARNING! System has blocking errors that will prevent boot"
        echo "$blockingErrors"
        echo !!!!!!!!!!
    fi
}

# list all phosphor-logging entries
function list_logs()
{
    # Look for any objects under logging that implement the
    # xyz.openbmc_project.Logging.Entry
    busctl -j call xyz.openbmc_project.ObjectMapper \
        /xyz/openbmc_project/object_mapper \
        xyz.openbmc_project.ObjectMapper \
        GetSubTreePaths sias "/xyz/openbmc_project/logging/" 0 1 \
        xyz.openbmc_project.Logging.Entry
}

# display input log details
function show_log()
{
    busctl -j call xyz.openbmc_project.Logging \
        "$1" \
        org.freedesktop.DBus.Properties \
        GetAll s xyz.openbmc_project.Logging.Entry
}

# delete all phosphor-logging entries
function delete_logs()
{
    busctl call xyz.openbmc_project.Logging \
        /xyz/openbmc_project/logging \
        xyz.openbmc_project.Collection.DeleteAll DeleteAll
}

# stop all targets associated with powering off a system
function stop_off_targets()
{
    systemctl stop \
        obmc-chassis-powered-off@0.target \
        obmc-host-stop-pre@0.target \
        obmc-host-stopped@0.target \
        obmc-host-stopping@0.target \
        obmc-power-off@0.target \
        obmc-power-stop-pre@0.target \
        obmc-power-stop@0.target
}

function handle_cmd()
{
    case "$1" in
        chassisoff)
            check_chassis_host_states
            local INTERFACE=$STATE_INTERFACE.Chassis
            G_REQUESTED_STATE=$INTERFACE.PowerState.Off
            G_QUERY="chassisstate"
            set_state_transition "chassis" "$INTERFACE" "RequestedPowerTransition" "$INTERFACE.Transition.Off"
            ;;
        chassison)
            check_chassis_host_states
            check_and_warn_boot_block
            local INTERFACE=$STATE_INTERFACE.Chassis
            G_REQUESTED_STATE=$INTERFACE.PowerState.On
            G_QUERY="chassisstate"
            set_state_transition "chassis" "$INTERFACE" "RequestedPowerTransition" "$INTERFACE.Transition.On"
            ;;
        poweroff)
            check_chassis_host_states
            local INTERFACE=$STATE_INTERFACE.Host
            G_REQUESTED_STATE=$INTERFACE.HostState.Off
            G_QUERY="hoststate"
            set_state_transition "host" "$INTERFACE" "RequestedHostTransition" "$INTERFACE.Transition.Off"
            ;;
        poweron)
            check_chassis_host_states
            check_and_warn_boot_block
            local INTERFACE=$STATE_INTERFACE.Host
            G_REQUESTED_STATE=$INTERFACE.HostState.Running
            G_QUERY="hoststate"
            set_state_transition "host" "$INTERFACE" "RequestedHostTransition" "$INTERFACE.Transition.On"
            ;;
        bmcstate)
            query_state "bmc" "$STATE_INTERFACE.BMC" "CurrentBMCState" "0"
            ;;
        chassisstate)
            query_state "chassis" "$STATE_INTERFACE.Chassis" "CurrentPowerState"
            ;;
        hoststate)
            query_state "host" "$STATE_INTERFACE.Host" "CurrentHostState"
            ;;
        osstate)
            query_state "host" "$STATE_INTERFACE.OperatingSystem.Status" "OperatingSystemState"
            ;;
        state|status)
            for query in bmcstate chassisstate hoststate bootprogress osstate
            do
                handle_cmd $query
            done
            check_and_warn_boot_block
            ;;
        bootprogress)
            query_state "host" "$STATE_INTERFACE.Boot.Progress" "BootProgress"
            ;;
        power)
            local OBJECT=/org/openbmc/control/power0
            local SERVICE
            SERVICE=$(get_service "$OBJECT")
            local INTERFACE=org.openbmc.control.Power
            local property STATE
            for property in pgood state pgood_timeout; do
                # get_property can potentially return several
                # different formats of values, so we do the parsing outside
                # of get_property depending on the query. These queries
                # return 'i VALUE' formatted strings.
                STATE=$(get_property "$SERVICE" "$OBJECT" "$INTERFACE" "$property")
                STATE="${STATE#i }"
                STATE="${STATE#i	}"
                printf "%s = %s\n" "$property" "$STATE"
            done
            ;;
        chassiskill)
            /usr/libexec/chassiskill
            ;;
        hostrebootoff)
            set_control_property "$CONTROL_OBJECT/host$G_INSTANCE_ID/auto_reboot" \
                "$CONTROL_INTERFACE.Boot.RebootPolicy" "AutoReboot" "b" "false"
            ;;
        hostrebootoffonetime)
            set_control_property "$CONTROL_OBJECT/host$G_INSTANCE_ID/auto_reboot/one_time" \
                "$CONTROL_INTERFACE.Boot.RebootPolicy" "AutoReboot" "b" "false"
            ;;
        hostrebooton)
            set_control_property "$CONTROL_OBJECT/host$G_INSTANCE_ID/auto_reboot" \
                "$CONTROL_INTERFACE.Boot.RebootPolicy" "AutoReboot" "b" "true"
            ;;
        bmcrebootoff)
            disable_bmc_reboot
            ;;
        bmcrebooton)
            enable_bmc_reboot
            ;;
        recoveryoff)
            handle_cmd hostrebootoff
            handle_cmd bmcrebootoff
            mask_systemd_target $HOST_TIMEOUT_TARGET
            mask_systemd_target $HOST_CRASH_TARGET
            ;;
        recoveryon)
            handle_cmd hostrebooton
            handle_cmd bmcrebooton
            unmask_systemd_target $HOST_TIMEOUT_TARGET
            unmask_systemd_target $HOST_CRASH_TARGET
            ;;
        recoverystatus)
            host_reboot_state=$(get_host_reboot_status)
            if [[ $host_reboot_state == "true" ]]; then
                host_reboot_status=1
            else
                host_reboot_status=0
            fi

            bmc_reboot_state=$(get_bmc_reboot_status)
            if [[ $bmc_reboot_state == "on" ]]; then
                bmc_reboot_status=1
            else
                bmc_reboot_status=0
            fi

            host_timeout_target_state=$(get_systemd_target_state $HOST_TIMEOUT_TARGET)
            if [[ $host_timeout_target_state == "masked" ]]; then
                host_timeout_status=0
            else
                host_timeout_status=1
            fi

            host_crash_target_state=$(get_systemd_target_state $HOST_CRASH_TARGET)
            if [[ $host_crash_target_state == "masked" ]]; then
                host_crash_status=0
            else
                host_crash_status=1
            fi

            if (( host_reboot_status && bmc_reboot_status && host_timeout_status && host_crash_status )); then
                echo "recovery: On"
            elif (( !host_reboot_status && !bmc_reboot_status && !host_timeout_status && !host_crash_status )); then
                echo "recovery: Off"
            else
                echo "recovery: Undefined"
            fi

            declare -A status
            status[0]="Off"
            status[1]="On"

            printf "  %-11s: %s\n" "hostReboot" "${status[$host_reboot_status]}"
            printf "  %-11s: %s\n" "bmcReboot" "${status[$bmc_reboot_status]}"
            printf "  %-11s: %s\n" "hostTimeout" "${status[$host_timeout_status]}"
            printf "  %-11s: %s\n" "hostCrash" "${status[$host_crash_status]}"
            ;;
        listbootblock)
            blockingErrors=$(check_boot_block_errors)
            if [ -z "$blockingErrors" ]; then
                echo "No blocking errors present"
            else
                echo "$blockingErrors"
            fi
            ;;
        listlogs)
            list_logs
            ;;
        showlog)
            if [ -z "${2:-}" ]; then
                print_usage_err "showlog requires a log path argument"
            fi
            show_log "$2"
            ;;
        deletelogs)
            delete_logs
            ;;
        stopofftargets)
            stop_off_targets
            ;;
        *)
            print_usage_err "Invalid command '$1'"
            ;;
    esac
}

# Validate at least one argument is provided
if [ $# -eq 0 ]; then
    print_usage_err "No command specified"
fi

shiftcnt=0
for arg in "$@"; do
    case $arg in
        -w|--wait)
            G_WAIT=$DEFAULT_WAIT_TIMEOUT
            shiftcnt=$((shiftcnt+1))
            continue
            ;;
        -h|--help)
            print_help
            ;;
        -v|--verbose)
            G_VERBOSE=y
            shiftcnt=$((shiftcnt+1))
            ;;
        -i=*|--id=*)
            G_INSTANCE_ID="${arg#*=}"
            # Validate instance ID is a number
            if ! [[ "$G_INSTANCE_ID" =~ ^[0-9]+$ ]]; then
                print_usage_err "Instance ID must be a number: $G_INSTANCE_ID"
            fi
            shiftcnt=$((shiftcnt+1))
            ;;
        -f|--force)
            G_FORCE=y
            shiftcnt=$((shiftcnt+1))
            ;;
        -*)
            print_usage_err "Unknown option: $arg"
            ;;
        *)
            G_ORIG_CMD=$arg
            # shift out the optional parameters
            shift $shiftcnt
            # pass all arguments to handle_cmd in case command takes additional
            # parameters
            handle_cmd "$@"
            break
            ;;
    esac
done

# If we got here without executing a command, only options were provided
if [ -z "$G_ORIG_CMD" ]; then
    print_usage_err "No command specified"
fi
