#!/usr/bin/env bash
# install-service.sh
# Generates and installs a systemd user-level service for the Battery Tracker app.
# No root required — uses ~/.config/systemd/user/.
#
# Usage:  bash sbin/install-service.sh

set -euo pipefail

# Resolve the app root directory from the script's own location
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VENV_WAITRESS="$APP_DIR/.venv/bin/waitress-serve"
SERVICE_DIR="$HOME/.config/systemd/user"
SERVICE_FILE="$SERVICE_DIR/battery-tracker.service"

echo "=== Battery Tracker — systemd user service installer ==="
echo "App directory: $APP_DIR"
echo

# Sanity checks
if [[ ! -f "$VENV_WAITRESS" ]]; then
  echo "ERROR: waitress-serve not found at $VENV_WAITRESS"
  echo "Run:  python3 -m venv .venv && .venv/bin/pip install -r requirements.txt"
  exit 1
fi

if [[ ! -f "$APP_DIR/app.py" ]]; then
  echo "ERROR: app.py not found in $APP_DIR"
  exit 1
fi

# Prompt for port and host
read -rp "Listen host [default: 127.0.0.1]: " HOST
HOST="${HOST:-127.0.0.1}"

read -rp "Listen port [default: 5000]: " PORT
PORT="${PORT:-5000}"

echo
echo "Home Assistant integration (optional — press Enter to skip):"
read -rp "  HOMEASSISTANT_URL (e.g. http://homeassistant.local:8123): " HA_URL
read -rp "  HOMEASSISTANT_API_KEY (long-lived access token): " HA_KEY
read -rp "  HOMEASSISTANT_POLL_INTERVAL seconds [default: 300]: " HA_INTERVAL
HA_INTERVAL="${HA_INTERVAL:-300}"

echo
echo "Generating service file → $SERVICE_FILE"

mkdir -p "$SERVICE_DIR"

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=Battery Tracker Flask App
After=network.target

[Service]
Type=simple
WorkingDirectory=$APP_DIR
ExecStart=$VENV_WAITRESS --host=$HOST --port=$PORT app:app
Environment=PYTHONPATH=$APP_DIR
$([ -n "$HA_URL" ] && echo "Environment=HOMEASSISTANT_URL=$HA_URL")
$([ -n "$HA_KEY" ] && echo "Environment=HOMEASSISTANT_API_KEY=$HA_KEY")
$([ -n "$HA_URL" ] && echo "Environment=HOMEASSISTANT_POLL_INTERVAL=$HA_INTERVAL")
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
EOF

echo "Service file written."
echo

# Reload and enable
systemctl --user daemon-reload
systemctl --user enable battery-tracker

echo
echo "=== Done ==="
echo
echo "Start the service:   systemctl --user start battery-tracker"
echo "Check status:        systemctl --user status battery-tracker"
echo "View logs:           journalctl --user -u battery-tracker -f"
echo "Stop the service:    systemctl --user stop battery-tracker"
echo
echo "To uninstall:"
echo "  systemctl --user disable --now battery-tracker"
echo "  rm $SERVICE_FILE"
echo "  systemctl --user daemon-reload"
