#!/bin/sh
# Older images can have Python's package record without Python's executable.
set -eu
usage() {
    echo 'Usage: graphics-setup [--install|--check|--activate-kernel] [--vendor auto|intel|amd|nvidia]'
    echo 'Run without sudo. With no options, report detected graphics devices.'
    echo 'Missing desktop tools are repaired before installation; package installation asks for confirmation.'
}
validate() {
    mode=
    vendor=auto
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --install|--check|--activate-kernel)
                [ -z "$mode" ] || return 64
                mode=$1 ;;
            --vendor)
                [ "$#" -ge 2 ] || return 64
                shift
                vendor=$1 ;;
            --vendor=*) vendor=${1#--vendor=} ;;
            *) return 64 ;;
        esac
        shift
    done
    case $vendor in auto|intel|amd|nvidia) ;; *) return 64 ;; esac
    if [ "$vendor" != auto ]; then
        case $mode in --check|--activate-kernel) return 64 ;; esac
    fi
}
if [ "$#" -eq 1 ]; then
    case "$1" in -h|--help) usage; exit 0 ;; esac
fi
validate "$@" || { usage >&2; exit 64; }
[ "$(id -u)" -ne 0 ] || { echo 'Run graphics-setup without sudo.' >&2; exit 64; }
python_ready() {
    [ -x /usr/bin/python3 ] && /usr/bin/python3 -c 'import argparse, pathlib, subprocess' >/dev/null 2>&1
}
if ! python_ready; then
    # Read-only/activation modes must never initiate package repairs.
    if [ "$mode" != --install ]; then
        echo 'Python is missing or incomplete. Run desktop-setup, then graphics-setup again.' >&2
        exit 1
    fi
    echo 'Restoring missing desktop tools before graphics installation.'
    /usr/bin/desktop-setup
    python_ready || { echo 'Python is still unavailable; graphics setup stopped.' >&2; exit 1; }
fi
exec /usr/bin/python3 /usr/libexec/graphics-utils/setup.py "$@"
