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

APP_ROOT="/opt/gar-bot"
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
GAR_BOT_USER="${GAR_BOT_USER:-${SUDO_USER:-$(id -un)}}"
GAR_BOT_GROUP="${GAR_BOT_GROUP:-$(id -gn "$GAR_BOT_USER")}"

sudo apt update
sudo apt install -y python3-venv python3-pip pigpio rsync curl

sudo mkdir -p "$APP_ROOT"
sudo rsync -a --delete "$SRC_DIR/" "$APP_ROOT/rp5_ai_agent/"
sudo chown -R "$GAR_BOT_USER:$GAR_BOT_GROUP" "$APP_ROOT"

python3 -m venv "$APP_ROOT/venv"
"$APP_ROOT/venv/bin/pip" install --upgrade pip
"$APP_ROOT/venv/bin/pip" install -r "$APP_ROOT/rp5_ai_agent/requirements.txt"

tmp_service="$(mktemp)"
sed \
  -e "s/^User=.*/User=$GAR_BOT_USER/" \
  -e "s/^Group=.*/Group=$GAR_BOT_GROUP/" \
  "$APP_ROOT/rp5_ai_agent/systemd/gar-bot-agent.service" > "$tmp_service"
sudo cp "$tmp_service" /etc/systemd/system/gar-bot-agent.service
rm -f "$tmp_service"
sudo systemctl daemon-reload
sudo systemctl enable pigpiod
sudo systemctl enable gar-bot-agent

echo "Installed GAR-BOT agent for $GAR_BOT_USER:$GAR_BOT_GROUP."
echo "Start with: sudo systemctl start gar-bot-agent"
echo "Check with: sudo systemctl status gar-bot-agent"
