#!/usr/bin/env bash
# ARMOR OS laptop launcher
# Safe launcher for X11 laptop command station mode.
# Launches the ARMOR OS laptop command station only.

set -euo pipefail

cd /home/shire3d/ARMOR

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

if [ -z "${DISPLAY:-}" ]; then
  echo "FAIL: DISPLAY is not set. Start this from an X11-capable terminal."
  exit 1
fi

if [ ! -x ./venv/bin/python ]; then
  echo "FAIL: ARMOR venv missing at ./venv/bin/python"
  exit 1
fi


export QT_QPA_PLATFORM=xcb
export ARMOR_DISPLAY_PROFILE=laptop
export QT_AUTO_SCREEN_SCALE_FACTOR=0
export QT_SCALE_FACTOR="${QT_SCALE_FACTOR:-1.35}"

echo "========================================"
echo " ARMOR OS LAPTOP COMMAND STATION"
echo " Host: $HOST"
echo " Repo: $(pwd)"
echo " Display: ${DISPLAY}"
echo " Profile: ${ARMOR_DISPLAY_PROFILE}"
echo " Scale: ${QT_SCALE_FACTOR}"
echo "========================================"

BOOT_VIDEO="/home/shire3d/ARMOR/assets/shire_boot.mp4"

echo "Playing ARMOR startup animation..."

ffplay \
  -loglevel error \
  -nostats \
  -autoexit \
  -fs \
  -noborder \
  -an \
  "$BOOT_VIDEO" \
  </dev/null \
  >/dev/null 2>&1 || true

echo "Launching ARMOR OS..."

./venv/bin/python main.py &
ARMOR_PID=$!

WINDOW=""

for _ in $(seq 1 60); do
  if ! kill -0 "$ARMOR_PID" 2>/dev/null; then
    wait "$ARMOR_PID"
    exit $?
  fi

  WINDOW="$(
    wmctrl -lGpx 2>/dev/null |
    awk -v pid="$ARMOR_PID" '
      $3 == pid {
        area = $6 * $7
        if (area > largest) {
          largest = area
          window = $1
        }
      }
      END {
        print window
      }
    '
  )"

  [ -n "$WINDOW" ] && break
  sleep 0.25
done

if [ -n "$WINDOW" ]; then
  SCREEN="$(
    xrandr --current |
    awk '/\*/ {print $1; exit}'
  )"

  WIDTH="${SCREEN%x*}"
  HEIGHT="${SCREEN#*x}"

  wmctrl -ir "$WINDOW" \
    -b remove,hidden,shaded,fullscreen,maximized_vert,maximized_horz ||
    true

  sleep 0.25

  wmctrl -ir "$WINDOW" \
    -e "0,0,0,$WIDTH,$HEIGHT" ||
    true

  wmctrl -ir "$WINDOW" \
    -b add,maximized_vert,maximized_horz ||
    true

  wmctrl -ir "$WINDOW" \
    -b add,fullscreen ||
    true

  wmctrl -ia "$WINDOW" || true

  echo "ARMOR fullscreen enforced on window $WINDOW."
else
  echo "WARNING: ARMOR window was not found for fullscreen enforcement."
fi

wait "$ARMOR_PID"
