#!/bin/bash
# Swynx Installer
# Usage: curl -fsSL https://licences.swynx.io/install.sh | bash
#
# Options:
#   --uninstall    Remove Swynx and its service
#   --no-service   Install without systemd service
#   --port PORT    Dashboard port (default: 9000)

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Defaults
INSTALL_DIR="/usr/local/bin"
DATA_DIR="/var/lib/swynx"
SERVICE_NAME="swynx-dashboard"
PORT=9000
SETUP_SERVICE=true
UNINSTALL=false
BASE_URL="https://licences.swynx.io/releases/latest"

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --uninstall)
      UNINSTALL=true
      shift
      ;;
    --no-service)
      SETUP_SERVICE=false
      shift
      ;;
    --port)
      PORT="$2"
      shift 2
      ;;
    *)
      shift
      ;;
  esac
done

# Fetch version info
get_version() {
  if command -v curl &> /dev/null; then
    VERSION=$(curl -fsSL "https://licences.swynx.io/api/version" 2>/dev/null | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
  elif command -v wget &> /dev/null; then
    VERSION=$(wget -qO- "https://licences.swynx.io/api/version" 2>/dev/null | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
  fi
  VERSION=${VERSION:-"latest"}
}

print_banner() {
  echo -e "${BLUE}"
  echo "                        ↑↑↑↑↑↑↑↑↑↑↑↑                        "
  echo "                  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑                  "
  echo "              ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑              "
  echo "           ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑            "
  echo "         ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑          "
  echo "       ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑        "
  echo "      ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑       "
  echo "    ↑↑↑↑↑↑↑↑↑↑↑↑↑↑     ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑     ↑↑↑↑↑↑↑↑↑↑↑↑    "
  echo "   ↑↑↑↑↑↑↑↑↑↑↑↑          ↑↑↑↑↑↑↑↑↑↑↑↑         ↑↑↑↑↑↑↑↑↑↑↑   "
  echo "  ↑↑↑↑↑↑↑↑↑↑↑↑           ↑↑↑↑↑↑↑↑↑↑↑↑          ↑↑↑↑↑↑↑↑↑↑↑  "
  echo "  ↑↑↑↑↑↑↑↑↑↑↑↑           ↑↑↑↑↑↑↑↑↑↑↑↑          ↑↑↑↑↑↑↑↑↑↑↑↑ "
  echo "  ↑↑↑↑↑↑↑↑↑↑↑↑↑          ↑↑↑↑↑↑↑↑↑↑↑↑         ↑↑↑↑↑↑↑↑↑↑↑↑↑ "
  echo "  ↑↑↑↑↑↑↑↑↑↑↑↑↑         ↑↑↑↑↑↑↑↑↑↑↑↑↑↑        ↑↑↑↑↑↑↑↑↑↑↑↑↑ "
  echo "  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑       ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑      ↑↑↑↑↑↑↑↑↑↑↑↑↑↑ "
  echo "  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑   ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ "
  echo "   ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  "
  echo "    ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑   "
  echo "      ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑     "
  echo "         ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑         "
  echo -e "${NC}"
  echo ""
  echo "  ____  _____ _____ ____     _             _ _ _   "
  echo " |  _ \| ____| ____|  _ \   / \  _   _  __| (_) |_ "
  echo " | |_) |  _| |  _| | |_) | / _ \| | | |/ _\` | | __|"
  echo " |  __/| |___| |___|  _ < / ___ \ |_| | (_| | | |_ "
  echo " |_|   |_____|_____|_| \_/_/   \_\__,_|\__,_|_|\__|"
  echo ""
  echo " Performance | Emissions | Exposure | Risk"
  echo ""
  if [ -n "$VERSION" ] && [ "$VERSION" != "latest" ]; then
    echo -e "                    ${GREEN}Installing v${VERSION}${NC}"
    echo ""
  fi
}

detect_platform() {
  OS=$(uname -s | tr '[:upper:]' '[:lower:]')
  ARCH=$(uname -m)

  case "$OS" in
    linux)
      PLATFORM="linux"
      ;;
    darwin)
      PLATFORM="macos"
      ;;
    mingw*|msys*|cygwin*)
      echo -e "${RED}Error: Windows detected. Please download the Windows package manually.${NC}"
      exit 1
      ;;
    *)
      echo -e "${RED}Error: Unsupported operating system: $OS${NC}"
      exit 1
      ;;
  esac

  case "$ARCH" in
    x86_64|amd64)
      ARCH="x64"
      ;;
    arm64|aarch64)
      ARCH="arm64"
      ;;
    *)
      echo -e "${RED}Error: Unsupported architecture: $ARCH${NC}"
      exit 1
      ;;
  esac

  BINARY_NAME="swynx-${PLATFORM}-${ARCH}"
  DOWNLOAD_URL="${BASE_URL}/${BINARY_NAME}.tar.gz"

  echo -e "${GREEN}Detected: ${PLATFORM}-${ARCH}${NC}"
}

check_root() {
  if [ "$EUID" -ne 0 ]; then
    echo -e "${YELLOW}Note: Running without root. Will install to ~/bin instead.${NC}"
    INSTALL_DIR="$HOME/bin"
    DATA_DIR="$HOME/.swynx"
    SETUP_SERVICE=false
    mkdir -p "$INSTALL_DIR"
  fi
}

uninstall() {
  echo -e "${YELLOW}Uninstalling Swynx...${NC}"

  # Stop and disable service
  if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    echo "Stopping service..."
    systemctl stop "$SERVICE_NAME"
  fi

  if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
    echo "Disabling service..."
    systemctl disable "$SERVICE_NAME"
  fi

  # Remove service file
  if [ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]; then
    rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
    systemctl daemon-reload
    echo "Removed systemd service"
  fi

  # Remove binary
  if [ -f "${INSTALL_DIR}/swynx" ]; then
    rm -f "${INSTALL_DIR}/swynx"
    echo "Removed binary"
  fi

  echo -e "${GREEN}Swynx uninstalled.${NC}"
  echo -e "${YELLOW}Note: Data in ${DATA_DIR} was preserved. Remove manually if needed.${NC}"
  exit 0
}

download_and_install() {
  echo -e "${BLUE}Downloading Swynx...${NC}"

  TEMP_DIR=$(mktemp -d)
  trap "rm -rf $TEMP_DIR" EXIT

  # Download
  if command -v curl &> /dev/null; then
    curl -fsSL "$DOWNLOAD_URL" -o "$TEMP_DIR/swynx.tar.gz"
  elif command -v wget &> /dev/null; then
    wget -q "$DOWNLOAD_URL" -O "$TEMP_DIR/swynx.tar.gz"
  else
    echo -e "${RED}Error: curl or wget required${NC}"
    exit 1
  fi

  # Extract
  echo "Extracting..."
  tar -xzf "$TEMP_DIR/swynx.tar.gz" -C "$TEMP_DIR"

  # Find the binary (handle different archive structures)
  BINARY_PATH=$(find "$TEMP_DIR" -name "swynx*" -type f -executable 2>/dev/null | head -1)
  if [ -z "$BINARY_PATH" ]; then
    BINARY_PATH=$(find "$TEMP_DIR" -name "swynx-${PLATFORM}-${ARCH}" -type f | head -1)
  fi

  if [ -z "$BINARY_PATH" ]; then
    echo -e "${RED}Error: Could not find binary in archive${NC}"
    exit 1
  fi

  # Install binary
  echo "Installing to ${INSTALL_DIR}..."
  cp "$BINARY_PATH" "${INSTALL_DIR}/swynx"
  chmod +x "${INSTALL_DIR}/swynx"

  # Copy public folder if present - REPLACE any existing to ensure fresh UI
  PUBLIC_PATH=$(find "$TEMP_DIR" -type d -name "public" | head -1)
  if [ -n "$PUBLIC_PATH" ]; then
    # Remove old public folders to ensure clean update
    rm -rf "${DATA_DIR}/public" 2>/dev/null
    rm -rf "$HOME/.swynx/public" 2>/dev/null

    mkdir -p "${DATA_DIR}"
    cp -r "$PUBLIC_PATH" "${DATA_DIR}/public"
    echo "Dashboard files installed to ${DATA_DIR}/public"

    # Also copy to ~/.swynx/public for when running manually
    mkdir -p "$HOME/.swynx"
    cp -r "$PUBLIC_PATH" "$HOME/.swynx/public"
  else
    echo -e "${YELLOW}Warning: Dashboard files not found in archive${NC}"
  fi

  echo -e "${GREEN}Binary installed to ${INSTALL_DIR}/swynx${NC}"
}

setup_systemd_service() {
  if [ "$PLATFORM" != "linux" ]; then
    echo -e "${YELLOW}Note: Auto-start service is only available on Linux.${NC}"
    echo "To start the dashboard manually: swynx dashboard --port $PORT"
    return
  fi

  if ! command -v systemctl &> /dev/null; then
    echo -e "${YELLOW}Note: systemd not found. Skipping service setup.${NC}"
    echo "To start the dashboard manually: swynx dashboard --port $PORT"
    return
  fi

  echo -e "${BLUE}Setting up systemd service...${NC}"

  # Create service file
  cat > "/etc/systemd/system/${SERVICE_NAME}.service" << EOF
[Unit]
Description=Swynx Dashboard
Documentation=https://licences.swynx.io/docs
After=network.target

[Service]
Type=simple
Environment=PEER_AUDIT_DATA_DIR=${DATA_DIR}
ExecStart=${INSTALL_DIR}/swynx dashboard --port ${PORT}
Restart=on-failure
RestartSec=5
WorkingDirectory=${DATA_DIR}

# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=${DATA_DIR}
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

  # Create data directory
  mkdir -p "${DATA_DIR}"

  # Reload systemd and enable service
  systemctl daemon-reload
  systemctl enable "$SERVICE_NAME"
  systemctl start "$SERVICE_NAME"

  echo -e "${GREEN}Service installed and started!${NC}"
}

print_success() {
  # Get local IP for convenience
  LOCAL_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "localhost")

  echo ""
  echo -e "${GREEN}============================================${NC}"
  echo -e "${GREEN}  Swynx installed successfully!${NC}"
  echo -e "${GREEN}============================================${NC}"
  echo ""

  if [ "$SETUP_SERVICE" = true ] && [ "$PLATFORM" = "linux" ]; then
    echo -e "  Dashboard URL: ${BLUE}http://${LOCAL_IP}:${PORT}/${NC}"
    echo ""
    echo "  Service commands:"
    echo "    systemctl status $SERVICE_NAME   # Check status"
    echo "    systemctl restart $SERVICE_NAME  # Restart"
    echo "    systemctl stop $SERVICE_NAME     # Stop"
    echo "    journalctl -u $SERVICE_NAME -f   # View logs"
  else
    echo "  Start the dashboard:"
    echo "    swynx dashboard --port $PORT"
    echo ""
    echo -e "  Then open: ${BLUE}http://localhost:${PORT}/${NC}"
  fi

  echo ""
  echo "  Next steps:"
  echo "    1. Open the dashboard in your browser"
  echo "    2. Enter your license key to activate"
  echo "    3. Add your first project and run a scan"
  echo ""
}

# Main
get_version
print_banner

if [ "$UNINSTALL" = true ]; then
  check_root
  uninstall
fi

detect_platform
check_root
download_and_install

if [ "$SETUP_SERVICE" = true ]; then
  setup_systemd_service
fi

print_success
