#!/usr/bin/env bash
# ARMOR OS autostart wrapper.
# Runs after desktop login. Does not change system login settings.
# Does not run Blender, open a file manager, export, render, or generate STLs.
# ENG-LAPTOP-0001E-C: retained local diagnostic logging.

set -euo pipefail

LOG="$HOME/ARMOR_autostart.log"
ARMOR_PROCESS_PATTERN='^(\./|/home/shire3d/ARMOR/)?venv/bin/python(3)?[[:space:]]+(/home/shire3d/ARMOR/)?main\.py([[:space:]].*)?$'

log() {
    printf '%s\n' "$*" >> "$LOG"
}

{
    echo
    echo "=================================================="
    echo "$(date)"
    echo "AUTOSTART WRAPPER STARTED"
    echo "HOST=$(hostname)"
    echo "DISPLAY=${DISPLAY:-UNSET}"
    echo "XDG_SESSION_TYPE=${XDG_SESSION_TYPE:-UNSET}"
    echo "PWD=$(pwd)"
    echo "=================================================="
} >> "$LOG"

sleep 5

cd /home/shire3d/ARMOR

HOST="$(hostname)"
if [ "$HOST" != "armoros" ]; then
    log "FAIL: Wrong host. Expected armoros. Current: $HOST"
    exit 1
fi

if [ -z "${DISPLAY:-}" ]; then
    log "FAIL: DISPLAY is not set. Desktop session is not ready."
    exit 1
fi

if [ "${XDG_SESSION_TYPE:-}" != "x11" ]; then
    log "FAIL: Local session is not X11. Current: ${XDG_SESSION_TYPE:-UNSET}"
    exit 1
fi

if [ ! -x ./scripts/start_armor_laptop.sh ]; then
    log "FAIL: ARMOR laptop launcher missing or not executable."
    exit 1
fi

if pgrep -f "$ARMOR_PROCESS_PATTERN" >/dev/null 2>&1; then
    log "INFO: ARMOR OS is already running. Duplicate launch blocked."
    exit 0
fi

log "Reached approved launcher handoff."

exec ./scripts/start_armor_laptop.sh >> "$LOG" 2>&1
