#!/usr/bin/bash
set -euo pipefail

SERVICE_NAME="com.cyan.SkillFishGovernor"
OBJECT_PATH="/com/cyan/SkillFishGovernor"
INTERFACE="com.cyan.SkillFishGovernor.PerformanceMode"

usage() {
    cat <<'EOF'
Usage: cyan-skillfish-performance-mode [OPTIONS] [COMMAND...]

Options:
    --on                  Enable performance mode
    --fixed-frequency <MHz>
                          Enable performance mode with fixed frequency
    --range <min> <max>   Set frequency range (MHz, use 0 for no limit)
    --off                 Disable performance mode
    --status              Show performance mode status
    -h, --help            Show this help message

Steam launch example:
  Add to Steam launch options: cyan-skillfish-performance-mode %command%

Command wrapper mode:
  cyan-skillfish-performance-mode some-game
  cyan-skillfish-performance-mode --fixed-frequency 1200 some-game
  cyan-skillfish-performance-mode --range 500 1500 some-game
  - Enables performance mode before running the command
  - Disables performance mode when the command exits
EOF
}

has_cmd() {
    command -v "$1" >/dev/null 2>&1
}

call_enable() {
    if has_cmd busctl; then
        busctl --system call "$SERVICE_NAME" "$OBJECT_PATH" "$INTERFACE" Enable >/dev/null 2>&1
        return $?
    fi

    if has_cmd dbus-send; then
        dbus-send --system \
            --dest="$SERVICE_NAME" \
            "$OBJECT_PATH" \
            "$INTERFACE.Enable" >/dev/null 2>&1
        return $?
    fi

    echo "Error: neither busctl nor dbus-send is installed." >&2
    return 1
}

call_disable() {
    if has_cmd busctl; then
        busctl --system call "$SERVICE_NAME" "$OBJECT_PATH" "$INTERFACE" Disable >/dev/null 2>&1
        return $?
    fi

    if has_cmd dbus-send; then
        dbus-send --system \
            --dest="$SERVICE_NAME" \
            "$OBJECT_PATH" \
            "$INTERFACE.Disable" >/dev/null 2>&1
        return $?
    fi

    echo "Error: neither busctl nor dbus-send is installed." >&2
    return 1
}

call_set_fixed_frequency() {
    local frequency="$1"

    if has_cmd busctl; then
        busctl --system call "$SERVICE_NAME" "$OBJECT_PATH" "$INTERFACE" SetFixedFrequency u "$frequency" >/dev/null 2>&1
        return $?
    fi

    if has_cmd dbus-send; then
        dbus-send --system \
            --dest="$SERVICE_NAME" \
            "$OBJECT_PATH" \
            "$INTERFACE.SetFixedFrequency" \
            uint32:"$frequency" >/dev/null 2>&1
        return $?
    fi

    echo "Error: neither busctl nor dbus-send is installed." >&2
    return 1
}

call_set_range() {
    local min="$1"
    local max="$2"
    local error_output

    if has_cmd busctl; then
        error_output=$(busctl --system call "$SERVICE_NAME" "$OBJECT_PATH" "$INTERFACE" SetRange uu "$min" "$max" 2>&1)
        if [ $? -eq 0 ]; then
            return 0
        else
            echo "$error_output" >&2
            return 1
        fi
    fi

    if has_cmd dbus-send; then
        error_output=$(dbus-send --system \
            --dest="$SERVICE_NAME" \
            "$OBJECT_PATH" \
            "$INTERFACE.SetRange" \
            uint32:"$min" uint32:"$max" 2>&1)
        if [ $? -eq 0 ]; then
            return 0
        else
            echo "$error_output" >&2
            return 1
        fi
    fi

    echo "Error: neither busctl nor dbus-send is installed." >&2
    return 1
}

call_status() {
    if has_cmd busctl; then
        busctl --system get-property "$SERVICE_NAME" "$OBJECT_PATH" "$INTERFACE" Enabled
        return $?
    fi

    if has_cmd dbus-send; then
        dbus-send --system \
            --print-reply \
            --dest="$SERVICE_NAME" \
            "$OBJECT_PATH" \
            org.freedesktop.DBus.Properties.Get \
            string:"$INTERFACE" \
            string:"Enabled"
        return $?
    fi

    echo "Error: neither busctl nor dbus-send is installed." >&2
    return 1
}

cleanup() {
    call_disable || true
}

# No arguments: show usage
if [ "$#" -eq 0 ]; then
    usage
    exit 1
fi

# Handle explicit options
case "$1" in
    --on)
        if call_enable; then
            echo "Performance mode enabled"
            exit 0
        else
            echo "Error: failed to enable performance mode. Is the service running?" >&2
            echo "Try: sudo systemctl status cyan-skillfish-governor-smu" >&2
            exit 1
        fi
        ;;
    --fixed-frequency)
        if [ "$#" -lt 2 ]; then
            echo "Error: --fixed-frequency requires a numeric MHz argument." >&2
            usage
            exit 1
        fi

        if [[ ! "$2" =~ ^[0-9]+$ ]]; then
            echo "Error: fixed frequency must be a positive integer (MHz)." >&2
            exit 1
        fi

        if call_set_fixed_frequency "$2"; then
            echo "Performance mode enabled with fixed frequency ${2} MHz"

            if [ "$#" -gt 2 ]; then
                shift 2
                if [ "${1:-}" = "--" ]; then
                    shift
                fi

                if [ "$#" -eq 0 ]; then
                    echo "Error: no command provided after --fixed-frequency" >&2
                    exit 1
                fi

                trap cleanup EXIT INT TERM
                exec "$@"
            fi

            exit 0
        else
            echo "Error: failed to set fixed frequency. Is the service running?" >&2
            echo "Try: sudo systemctl status cyan-skillfish-governor-smu" >&2
            exit 1
        fi
        ;;
    --range)
        if [ "$#" -lt 3 ]; then
            echo "Error: --range requires two numeric arguments (min max in MHz)." >&2
            usage
            exit 1
        fi

        if [[ ! "$2" =~ ^[0-9]+$ ]] || [[ ! "$3" =~ ^[0-9]+$ ]]; then
            echo "Error: frequency range values must be non-negative integers (MHz)." >&2
            exit 1
        fi

        if call_set_range "$2" "$3"; then
            echo "Frequency range set: min=$2 MHz, max=$3 MHz"

            if [ "$#" -gt 3 ]; then
                shift 3
                if [ "${1:-}" = "--" ]; then
                    shift
                fi

                if [ "$#" -eq 0 ]; then
                    echo "Error: no command provided after --range" >&2
                    exit 1
                fi

                trap cleanup EXIT INT TERM
                exec "$@"
            fi

            exit 0
        else
            exit 1
        fi
        ;;
    --off)
        if call_disable; then
            echo "Performance mode disabled"
            exit 0
        else
            echo "Error: failed to disable performance mode. Is the service running?" >&2
            echo "Try: sudo systemctl status cyan-skillfish-governor-smu" >&2
            exit 1
        fi
        ;;
    --status)
        call_status
        exit $?
        ;;
    -h|--help|help)
        usage
        exit 0
        ;;
    *)
        # Treat as command wrapper mode: enable, run command, disable on exit
        call_enable || {
            echo "Warning: failed to enable performance mode." >&2
        }
        trap cleanup EXIT INT TERM
        exec "$@"
        ;;
esac
