#!/bin/bash
# Run this on the DigitalOcean server (as root) to:
# 1. Create log directory
# 2. Install the API systemd service for /var/www/boundary-fastapiandnextjs
# 3. Enable and start the service so logs go to /var/log/plagis/

set -e
APP_ROOT="${APP_ROOT:-/var/www/boundary-fastapiandnextjs}"
SERVICE_NAME="plagis-aumentum-api"
LOG_DIR="/var/log/plagis"

echo "Using app root: $APP_ROOT"
echo ""

# 1. Create log directory
echo "1. Creating log directory $LOG_DIR ..."
mkdir -p "$LOG_DIR"
chmod 755 "$LOG_DIR"
echo "   Done."

# 2. Install service file (use the varwww variant)
SERVICE_FILE="$APP_ROOT/scripts/plagis-aumentum-api-varwww.service"
if [ ! -f "$SERVICE_FILE" ]; then
  echo "   ERROR: $SERVICE_FILE not found. Run this script from the server where the repo is deployed."
  exit 1
fi
echo "2. Installing systemd unit ..."
cp "$SERVICE_FILE" /etc/systemd/system/plagis-aumentum-api.service
systemctl daemon-reload
echo "   Done."

# 3. Ensure venv exists
if [ ! -x "$APP_ROOT/venv/bin/python3" ]; then
  echo "   WARNING: $APP_ROOT/venv/bin/python3 not found."
  echo "   Create venv and install deps:"
  echo "     cd $APP_ROOT && python3 -m venv venv && venv/bin/pip install -r requirements.txt"
  echo ""
  read -p "   Continue anyway? (y/N) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 1
  fi
fi

# 4. Enable and start
echo "3. Enabling and starting $SERVICE_NAME ..."
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"
systemctl status "$SERVICE_NAME" --no-pager || true
echo ""
echo "Logs:"
echo "  tail -f $LOG_DIR/api.log $LOG_DIR/api-error.log"
echo "  journalctl -u $SERVICE_NAME -f"
echo ""
