#!/usr/bin/bash
set -euo pipefail

if [[ "$(id -u)" -ne 0 ]]; then
  echo "irongargoyle-first-run must be run as root." >&2
  exit 1
fi

VENV_DIR="/opt/irongargoyle/.venv"
WHEELHOUSE_DIR="/usr/share/irongargoyle/wheelhouse"
WHEELS_DIR="/usr/share/irongargoyle/wheels"
APP_WHEEL_GLOB="$WHEELS_DIR/irongargoyle-"'*.whl'
CONFIG_PATH="/etc/irongargoyle/config.yaml"

install -d -m 0755 /opt/irongargoyle
install -d -m 0755 /etc/irongargoyle
install -d -m 0755 /var/lib/irongargoyle
install -d -m 0755 /var/lib/irongargoyle/backups
install -d -m 0755 /var/lib/irongargoyle/quarantine
install -d -m 0755 /var/log/irongargoyle

if [[ ! -d "$WHEELHOUSE_DIR" ]]; then
  echo "Missing packaged wheelhouse: $WHEELHOUSE_DIR" >&2
  exit 1
fi
if [[ ! -d "$WHEELS_DIR" ]]; then
  echo "Missing packaged wheels directory: $WHEELS_DIR" >&2
  exit 1
fi

shopt -s nullglob
APP_WHEELS=($APP_WHEEL_GLOB)
shopt -u nullglob
if [[ ${#APP_WHEELS[@]} -eq 0 ]]; then
  echo "Missing packaged IronGargoyle wheel in $WHEELS_DIR" >&2
  exit 1
fi

python3.11 -m venv "$VENV_DIR"
if ! "$VENV_DIR/bin/python" -m pip --version >/dev/null 2>&1; then
  echo "pip is not available in $VENV_DIR. Install python3.11-venv/python3.11-pip and retry." >&2
  exit 1
fi
"$VENV_DIR/bin/python" -m pip install --upgrade --no-index --find-links "$WHEELHOUSE_DIR" "${APP_WHEELS[0]}"

systemctl daemon-reload
"$VENV_DIR/bin/irongargoyle" install configure-webui --config "$CONFIG_PATH"
systemctl enable irongargoyle-agent.service irongargoyle-console.service
systemctl restart irongargoyle-agent.service irongargoyle-console.service

echo "Managed IronGargoyle runtime refreshed at $VENV_DIR"
