#!/usr/bin/env bash
# ReadySet Shallow Cache — Systemd Deployment Script
# Generated by RDST. Do not edit {placeholder} values manually.
set -euo pipefail

SERVICE_NAME="readyset-cache-{target_name}"
DB_ENGINE="{db_engine}"
DB_HOST="{db_host}"
DB_PORT="{db_port}"
DB_USER="{db_user}"
DB_NAME="{db_name}"
READYSET_PORT="{readyset_port}"
READYSET_IMAGE="{readyset_image}"
CONFIG_DIR="/etc/readyset"
CONFIG_FILE="${CONFIG_DIR}/${SERVICE_NAME}.toml"
BINARY_PATH="/usr/local/bin/readyset"

# ---------------------------------------------------------------------------
# Subcommand handling
# ---------------------------------------------------------------------------
case "${1:-}" in
  stop)
    echo "Stopping ${SERVICE_NAME}..."
    sudo systemctl stop "$SERVICE_NAME"
    echo "Stopped."
    exit 0
    ;;
  logs)
    sudo journalctl -u "$SERVICE_NAME" -f
    exit 0
    ;;
  status)
    sudo systemctl status "$SERVICE_NAME" --no-pager
    exit 0
    ;;
  restart)
    echo "Restarting ${SERVICE_NAME}..."
    sudo systemctl restart "$SERVICE_NAME"
    echo "Restarted."
    exit 0
    ;;
  uninstall)
    echo "Uninstalling ${SERVICE_NAME}..."
    sudo systemctl stop "$SERVICE_NAME" 2>/dev/null || true
    sudo systemctl disable "$SERVICE_NAME" 2>/dev/null || true
    sudo rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
    sudo rm -f "$CONFIG_FILE"
    sudo systemctl daemon-reload
    echo "Uninstalled."
    exit 0
    ;;
esac

# ---------------------------------------------------------------------------
# Prerequisite checks
# ---------------------------------------------------------------------------
if ! command -v systemctl >/dev/null 2>&1; then
  echo "Error: systemd is not available on this system."
  echo "Use Docker mode instead: rdst cache deploy --target <name> --mode docker"
  exit 1
fi

# ---------------------------------------------------------------------------
# Check if already installed
# ---------------------------------------------------------------------------
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
  echo "ReadySet service '${SERVICE_NAME}' is already running."
  sudo systemctl status "$SERVICE_NAME" --no-pager
  echo ""
  echo "Commands:"
  echo "  $0 logs       View logs"
  echo "  $0 status     Check status"
  echo "  $0 restart    Restart"
  echo "  $0 stop       Stop"
  echo "  $0 uninstall  Remove service"
  exit 0
fi

# ---------------------------------------------------------------------------
# Password prompt
# ---------------------------------------------------------------------------
read -s -p "Enter database password for user '${DB_USER}': " DB_PASSWORD
echo ""

if [ -z "$DB_PASSWORD" ]; then
  echo "Error: Password cannot be empty."
  exit 1
fi

# ---------------------------------------------------------------------------
# Build connection URL
# ---------------------------------------------------------------------------
if [ "$DB_ENGINE" = "mysql" ]; then
  DB_URL="mysql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}"
  DB_TYPE="mysql"
else
  DB_URL="postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}"
  DB_TYPE="postgresql"
fi

# ---------------------------------------------------------------------------
# Download ReadySet binary (if not present)
# ---------------------------------------------------------------------------
if [ ! -f "$BINARY_PATH" ]; then
  echo "Downloading ReadySet binary..."

  # Try Docker image extraction approach (works for any arch)
  if command -v docker >/dev/null 2>&1; then
    echo "Extracting binary from Docker image: ${READYSET_IMAGE}"
    TEMP_CONTAINER="rdst-extract-$$"
    docker create --name "$TEMP_CONTAINER" "$READYSET_IMAGE" >/dev/null 2>&1
    sudo docker cp "${TEMP_CONTAINER}:/usr/local/bin/readyset" "$BINARY_PATH" 2>/dev/null || \
    sudo docker cp "${TEMP_CONTAINER}:/usr/bin/readyset" "$BINARY_PATH" 2>/dev/null || \
    { echo "Error: Could not extract ReadySet binary from image."; docker rm "$TEMP_CONTAINER" >/dev/null 2>&1; exit 1; }
    docker rm "$TEMP_CONTAINER" >/dev/null 2>&1
    sudo chmod 755 "$BINARY_PATH"
    echo "Binary installed to ${BINARY_PATH}"
  else
    echo "Error: Docker is required to extract the ReadySet binary."
    echo "Install Docker or download the binary manually to ${BINARY_PATH}"
    exit 1
  fi
else
  echo "ReadySet binary already present: ${BINARY_PATH}"
fi

# ---------------------------------------------------------------------------
# Write config
# ---------------------------------------------------------------------------
echo "Writing config to ${CONFIG_FILE}..."
sudo mkdir -p "$CONFIG_DIR"
sudo tee "$CONFIG_FILE" > /dev/null <<EOF
# ReadySet configuration for target: {target_name}
database_type = "${DB_TYPE}"
upstream_db_url = "${DB_URL}"
listen_port = ${READYSET_PORT}
EOF

# ---------------------------------------------------------------------------
# Create systemd unit
# ---------------------------------------------------------------------------
echo "Creating systemd service: ${SERVICE_NAME}..."
sudo tee "/etc/systemd/system/${SERVICE_NAME}.service" > /dev/null <<EOF
[Unit]
Description=ReadySet Cache (${SERVICE_NAME})
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=${BINARY_PATH}
Restart=on-failure
RestartSec=5
Environment=UPSTREAM_DB_URL=${DB_URL}
Environment=DATABASE_TYPE=${DB_TYPE}
Environment=LISTEN_ADDRESS=0.0.0.0:${READYSET_PORT}
Environment=DEPLOYMENT_MODE=standalone
Environment=QUERY_CACHING=explicit
Environment=CACHE_MODE=shallow

[Install]
WantedBy=multi-user.target
EOF

# ---------------------------------------------------------------------------
# Enable and start
# ---------------------------------------------------------------------------
echo "Starting ${SERVICE_NAME}..."
sudo systemctl daemon-reload
sudo systemctl enable "$SERVICE_NAME"
sudo systemctl start "$SERVICE_NAME"

# Wait briefly and verify
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
  echo ""
  echo "ReadySet deployed as systemd service!"
  echo ""
  echo "  Service: ${SERVICE_NAME}"
  echo "  Port:    ${READYSET_PORT}"
  echo "  Engine:  ${DB_TYPE}"
  echo "  Config:  ${CONFIG_FILE}"
  echo ""
  echo "Commands:"
  echo "  $0 logs       View logs"
  echo "  $0 status     Check status"
  echo "  $0 restart    Restart"
  echo "  $0 stop       Stop"
  echo "  $0 uninstall  Remove service"
else
  echo ""
  echo "Warning: Service failed to start. Check logs:"
  echo "  sudo journalctl -u ${SERVICE_NAME} -n 50 --no-pager"
  exit 1
fi
