
#!/bin/sh

set -eu

GPuctl_LIB="/usr/local/lib/scripts"

. "$GPuctl_LIB/common.sh"
. "$GPuctl_LIB/status.sh"
. "$GPuctl_LIB/gpu.sh"
. "$GPuctl_LIB/llama.sh"
. "$GPuctl_LIB/comfy.sh"


show_usage() {
    cat <<'EOF'
Usage:

  gpuctl status
  gpuctl gpu
  gpuctl update
  gpuctl sleep
  gpuctl wake

  gpuctl start llama [model.gguf] [extra args...]
  gpuctl start comfy [extra args...]

  gpuctl comfy models list [type]
  gpuctl comfy models queue
  gpuctl comfy models add <URL> <type>
  gpuctl comfy models rm <filename> [type]

  gpuctl stop <service>
  gpuctl restart <service>
  gpuctl logs <service>

Services: llama, comfy, model-worker, webdav, dashboard,
          ssh-main, ssh-companion, gpu-test
EOF
}


case "${1:-}" in

    status)
        show_status
        ;;

    gpu)
        show_gpu
        ;;

    update)
        if [ "$#" -ne 1 ]; then
            echo "Usage: gpuctl update" >&2
            exit 1
        fi

        update_ssh
        ;;

    sleep)
        if [ "$#" -ne 1 ]; then
            echo "Usage: gpuctl sleep" >&2
            exit 1
        fi

        sleep_mode
        ;;

    wake)
        if [ "$#" -ne 1 ]; then
            echo "Usage: gpuctl wake" >&2
            exit 1
        fi

        wake_mode
        ;;

    start)
        case "${2:-}" in

            llama)
                shift 2
                start_llama "$@"
                ;;

            comfy)
                shift 2
                start_comfy "$@"
                ;;

            *)
                show_usage
                exit 1
                ;;
        esac
        ;;

    comfy)
        shift
        comfy_command "$@"
        ;;

    llama)
        shift
        llama_command "$@"
        ;;

    stop)
        if [ "$#" -ne 2 ]; then
            echo "Usage: gpuctl stop <service>" >&2
            exit 1
        fi

        stop_service "$2"
        ;;

    restart)
        if [ "$#" -ne 2 ]; then
            echo "Usage: gpuctl restart <service>" >&2
            exit 1
        fi

        restart_service "$2"
        ;;

    logs)
        if [ "$#" -ne 2 ]; then
            echo "Usage: gpuctl logs <service>" >&2
            exit 1
        fi

        logs_service "$2"
        ;;

    *)
        show_usage
        exit 1
        ;;

esac