#!/usr/bin/env bash
set -Eeuo pipefail

REPO="/home/shire3d/ARMOR"
LOG="$HOME/shire-mini-autostart.log"

exec >>"$LOG" 2>&1

echo
echo "===== $(date --iso-8601=seconds) SHIRE MINI AUTOSTART ====="

[ "$(hostname)" = "Work" ] || {
  echo "FAIL: Wrong host."
  exit 1
}

export DISPLAY=:0
export XAUTHORITY=/home/ray/.Xauthority

for _ in $(seq 1 60); do
  xdpyinfo >/dev/null 2>&1 && break
  sleep 1
done

xdpyinfo >/dev/null 2>&1 || {
  echo "FAIL: Desktop display did not become available."
  exit 1
}

OUTPUT="$(
  xrandr --current |
  awk '/ connected primary/ {print $1; exit}'
)"

[ -n "$OUTPUT" ] || {
  echo "FAIL: Primary display output was not found."
  exit 1
}

MODE="$(
  xrandr --current |
  awk '/\*/ {print $1; exit}'
)"

if [ "$MODE" != "1920x1080" ]; then
  echo "Changing display from $MODE to 1920x1080."
  xrandr --output "$OUTPUT" --mode 1920x1080
  sleep 2
fi

MODE="$(
  xrandr --current |
  awk '/\*/ {print $1; exit}'
)"

[ "$MODE" = "1920x1080" ] || {
  echo "FAIL: Display mode is $MODE."
  exit 1
}

if pgrep -f \
  '^/home/shire3d/ARMOR/venv/bin/python(3)? /home/shire3d/ARMOR/main.py$' \
  >/dev/null
then
  echo "INFO: SHiRE is already running."
  exit 0
fi

echo "Launching SHiRE at $MODE."
exec "$REPO/scripts/start_armor_mini.sh"
