#!/bin/bash
set -e

# DeployDB Agent Installation Script
# Usage: curl -sSL https://get.deploydb.com/bootstrap?token=YOUR_TOKEN | bash
#    or: curl -sSL https://get.deploydb.com | bash -s -- --token=YOUR_TOKEN

# Fetch latest version from GitHub releases
GITHUB_REPO="deploydb/deploydb-agent"
VERSION=$(curl -fsSL "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" 2>/dev/null | grep -o '"tag_name": *"[^"]*"' | cut -d'"' -f4 | sed 's/^v//')
if [ -z "$VERSION" ]; then
  VERSION="0.3.0"  # Fallback version
fi
BINARY_BASE_URL="https://github.com/${GITHUB_REPO}/releases/download/v${VERSION}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Token can be embedded from query param or passed as argument
TOKEN=""
PG_HOST="localhost"
PG_PORT="5432"
PG_USER="postgres"
PG_DATABASE="postgres"

# Parse arguments (can override embedded token)
while [[ $# -gt 0 ]]; do
  case $1 in
    --token=*) TOKEN="${1#*=}"; shift ;;
    --pg-host=*) PG_HOST="${1#*=}"; shift ;;
    --pg-port=*) PG_PORT="${1#*=}"; shift ;;
    --pg-user=*) PG_USER="${1#*=}"; shift ;;
    --pg-database=*) PG_DATABASE="${1#*=}"; shift ;;
    --help|-h)
      echo "DeployDB Agent Installer"
      echo ""
      echo "Usage: curl -sSL https://get.deploydb.com/bootstrap?token=TOKEN | bash"
      echo "   or: curl -sSL https://get.deploydb.com | bash -s -- --token=TOKEN"
      echo ""
      echo "Options:"
      echo "  --token=TOKEN          Agent authentication token (can also be passed via URL)"
      echo "  --pg-host=HOST         PostgreSQL host (default: localhost)"
      echo "  --pg-port=PORT         PostgreSQL port (default: 5432)"
      echo "  --pg-user=USER         PostgreSQL user (default: postgres)"
      echo "  --pg-database=DB       PostgreSQL database (default: postgres)"
      echo "  --help, -h             Show this help message"
      exit 0
      ;;
    *)
      echo -e "${RED}Error: Unknown option: $1${NC}"
      echo "Use --help for usage information"
      exit 1
      ;;
  esac
done

# Require token
if [ -z "$TOKEN" ]; then
  echo -e "${RED}Error: Token is required${NC}"
  echo "Usage: curl -sSL https://get.deploydb.com/bootstrap?token=YOUR_TOKEN | bash"
  exit 1
fi

# Detect token mode from control plane
echo -e "${YELLOW}→${NC} Checking token..."
TOKEN_INFO_URL="https://deploydb.com/api/v1/token/info?token=${TOKEN}"
TOKEN_RESPONSE=$(curl -sSL "$TOKEN_INFO_URL")

if [ $? -ne 0 ]; then
  echo -e "${RED}Error: Failed to verify token with control plane${NC}"
  echo "Please check your internet connection and try again."
  exit 1
fi

# Parse JSON response to get mode
TOKEN_MODE=$(echo "$TOKEN_RESPONSE" | grep -o '"mode":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN_MODE" ]; then
  echo -e "${RED}Error: Invalid token or token has expired${NC}"
  echo "Please generate a new token from the DeployDB dashboard."
  exit 1
fi

echo -e "${GREEN}✓${NC} Token verified (mode: ${TOKEN_MODE})"

# Detect OS
detect_os() {
  case "$(uname -s)" in
    Linux*) echo "linux" ;;
    Darwin*) echo "darwin" ;;
    *)
      echo -e "${RED}Error: Unsupported operating system: $(uname -s)${NC}"
      echo "DeployDB Agent supports Linux and macOS only."
      exit 1
      ;;
  esac
}

# Detect architecture
detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64) echo "amd64" ;;
    arm64|aarch64) echo "arm64" ;;
    *)
      echo -e "${RED}Error: Unsupported architecture: $(uname -m)${NC}"
      echo "DeployDB Agent supports amd64 and arm64 only."
      exit 1
      ;;
  esac
}

OS=$(detect_os)
ARCH=$(detect_arch)

echo -e "${CYAN}"
echo "  ____             _             ____  ____  "
echo " |  _ \  ___ _ __ | | ___  _   _|  _ \| __ ) "
echo " | | | |/ _ \ '_ \| |/ _ \| | | | | | |  _ \ "
echo " | |_| |  __/ |_) | | (_) | |_| | |_| | |_) |"
echo " |____/ \___| .__/|_|\___/ \__, |____/|____/ "
echo "            |_|            |___/             "
echo -e "${NC}"
echo -e "${GREEN}Installing DeployDB Agent v${VERSION}${NC}"
echo -e "Platform: ${OS}/${ARCH}"
echo ""

# Download binary
BINARY_URL="${BINARY_BASE_URL}/deploydb-agent-${OS}-${ARCH}"
INSTALL_DIR="/usr/local/bin"
TMP_FILE="/tmp/deploydb-agent"

echo -e "${YELLOW}→${NC} Downloading DeployDB agent..."
if ! curl -fsSL -o "$TMP_FILE" "$BINARY_URL"; then
  echo -e "${RED}Error: Failed to download agent from ${BINARY_URL}${NC}"
  echo "Please check your internet connection and try again."
  exit 1
fi

chmod +x "$TMP_FILE"

echo -e "${YELLOW}→${NC} Installing to ${INSTALL_DIR}..."
if [ "$EUID" -ne 0 ]; then
  sudo mv "$TMP_FILE" "$INSTALL_DIR/deploydb-agent"
else
  mv "$TMP_FILE" "$INSTALL_DIR/deploydb-agent"
fi

# Create configuration
if [ "$OS" = "darwin" ]; then
  CONFIG_DIR="$HOME/Library/Application Support/DeployDB"
  CONFIG_FILE="$CONFIG_DIR/config.yaml"
  mkdir -p "$CONFIG_DIR"
  USE_SUDO=""
else
  CONFIG_DIR="/etc/deploydb"
  CONFIG_FILE="$CONFIG_DIR/config.yaml"
  if [ "$EUID" -ne 0 ]; then
    sudo mkdir -p "$CONFIG_DIR"
    USE_SUDO="sudo"
  else
    mkdir -p "$CONFIG_DIR"
    USE_SUDO=""
  fi
fi

echo -e "${YELLOW}→${NC} Creating configuration at ${CONFIG_FILE}..."
$USE_SUDO tee "$CONFIG_FILE" > /dev/null <<EOF
# DeployDB Agent Configuration
control_plane_url: "wss://deploydb.com/cable"
token: "$TOKEN"

postgres:
  host: "$PG_HOST"
  port: $PG_PORT
  user: "$PG_USER"
  database: "$PG_DATABASE"

metrics_interval: 30s
EOF

# Execute appropriate command based on token mode
if [ "$TOKEN_MODE" = "bootstrap" ]; then
  echo -e "${YELLOW}→${NC} Running bootstrap (will install PostgreSQL)..."
  echo ""

  # Bootstrap mode: install PostgreSQL and configure agent
  CONTROL_PLANE_URL="https://deploydb.com"
  if [ "$EUID" -ne 0 ]; then
    sudo /usr/local/bin/deploydb-agent bootstrap --token="$TOKEN" --url="$CONTROL_PLANE_URL"
  else
    /usr/local/bin/deploydb-agent bootstrap --token="$TOKEN" --url="$CONTROL_PLANE_URL"
  fi

  if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Bootstrap failed${NC}"
    echo "Check the output above for details."
    exit 1
  fi

  echo ""
  echo -e "${GREEN}Bootstrap completed!${NC}"
  echo ""

  # Setup systemd/launchd service for ongoing monitoring
  if [ "$OS" = "linux" ]; then
    echo -e "${YELLOW}→${NC} Setting up systemd service for monitoring..."

    SERVICE_FILE="/etc/systemd/system/deploydb-agent.service"
    $USE_SUDO tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=DeployDB Agent
After=network.target postgresql.service

[Service]
Type=simple
ExecStart=/usr/local/bin/deploydb-agent run --config=/etc/deploydb/config.yaml
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    $USE_SUDO systemctl daemon-reload
    $USE_SUDO systemctl enable deploydb-agent
    $USE_SUDO systemctl start deploydb-agent

    echo -e "${GREEN}✓${NC} systemd service installed and started"

  elif [ "$OS" = "darwin" ]; then
    echo -e "${YELLOW}→${NC} Setting up launchd service for monitoring..."

    PLIST_DIR="$HOME/Library/LaunchAgents"
    PLIST_FILE="$PLIST_DIR/com.deploydb.agent.plist"
    mkdir -p "$PLIST_DIR"

    cat > "$PLIST_FILE" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.deploydb.agent</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/bin/deploydb-agent</string>
    <string>run</string>
    <string>--config=${CONFIG_FILE}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${HOME}/Library/Logs/deploydb-agent.log</string>
  <key>StandardErrorPath</key>
  <string>${HOME}/Library/Logs/deploydb-agent.error.log</string>
</dict>
</plist>
EOF

    launchctl unload "$PLIST_FILE" 2>/dev/null || true
    launchctl load "$PLIST_FILE"

    echo -e "${GREEN}✓${NC} launchd service installed and started"
  fi

elif [ "$TOKEN_MODE" = "setup" ]; then
  # Setup mode: configure agent for existing PostgreSQL installation
  echo -e "${YELLOW}→${NC} Setup mode: connecting to existing PostgreSQL..."

  # Setup service based on OS
  if [ "$OS" = "linux" ]; then
    echo -e "${YELLOW}→${NC} Setting up systemd service..."

    SERVICE_FILE="/etc/systemd/system/deploydb-agent.service"
    $USE_SUDO tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=DeployDB Agent
After=network.target postgresql.service

[Service]
Type=simple
ExecStart=/usr/local/bin/deploydb-agent run --config=/etc/deploydb/config.yaml
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    $USE_SUDO systemctl daemon-reload
    $USE_SUDO systemctl enable deploydb-agent
    $USE_SUDO systemctl start deploydb-agent

    echo -e "${GREEN}✓${NC} systemd service installed and started"

  elif [ "$OS" = "darwin" ]; then
    echo -e "${YELLOW}→${NC} Setting up launchd service..."

    PLIST_DIR="$HOME/Library/LaunchAgents"
    PLIST_FILE="$PLIST_DIR/com.deploydb.agent.plist"
    mkdir -p "$PLIST_DIR"

    cat > "$PLIST_FILE" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.deploydb.agent</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/bin/deploydb-agent</string>
    <string>run</string>
    <string>--config=${CONFIG_FILE}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${HOME}/Library/Logs/deploydb-agent.log</string>
  <key>StandardErrorPath</key>
  <string>${HOME}/Library/Logs/deploydb-agent.error.log</string>
</dict>
</plist>
EOF

    launchctl unload "$PLIST_FILE" 2>/dev/null || true
    launchctl load "$PLIST_FILE"

    echo -e "${GREEN}✓${NC} launchd service installed and started"
  fi

else
  echo -e "${RED}Error: Unknown token mode: ${TOKEN_MODE}${NC}"
  echo "Please contact support."
  exit 1
fi

echo ""
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✓ DeployDB Agent installed successfully!${NC}"
echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "The agent is now running and connecting to DeployDB."
echo -e "Return to the web interface to continue setup."
echo ""
if [ "$OS" = "linux" ]; then
  echo -e "Useful commands:"
  echo -e "  ${CYAN}sudo systemctl status deploydb-agent${NC}  - Check agent status"
  echo -e "  ${CYAN}sudo journalctl -u deploydb-agent -f${NC}  - View agent logs"
  echo -e "  ${CYAN}sudo systemctl restart deploydb-agent${NC} - Restart agent"
elif [ "$OS" = "darwin" ]; then
  echo -e "Useful commands:"
  echo -e "  ${CYAN}launchctl list | grep deploydb${NC}        - Check agent status"
  echo -e "  ${CYAN}tail -f ~/Library/Logs/deploydb-agent.log${NC} - View agent logs"
  echo -e "  ${CYAN}launchctl kickstart -k gui/\$(id -u)/com.deploydb.agent${NC} - Restart agent"
fi
echo ""
