#!/bin/bash
# TATER Compliance Agent — Linux Installer
# Supports Ubuntu 20.04+, Debian 10+, RHEL 8+, CentOS 8+, Fedora 34+
# Architecture: amd64 (x86_64) or arm64 (aarch64)
#
# Usage:
#   sudo bash install.sh
#
# Environment variables (optional — can also be configured interactively):
#   TATER_API_BASE    - TATER API base URL (e.g. https://api.tatersecurity.com/api)
#   TATER_API_KEY     - TATER API key
#   TATER_TENANT_ID   - Azure AD tenant ID
#   TATER_ORG_ID      - TATER organization ID
#   TATER_VERSION     - Agent version to install (default: auto-detect from bundled binary)
#
# Non-interactive install example:
#   sudo TATER_API_BASE="https://api.tatersecurity.com/api" \
#        TATER_API_KEY="your-api-key" \
#        TATER_TENANT_ID="your-tenant-id" \
#        TATER_ORG_ID="org-xxxxxxxx" \
#        bash install.sh

set -euo pipefail

INSTALL_DIR="/usr/local/bin"
DATA_DIR="/var/lib/tater"
CONTROLS_DIR="$DATA_DIR/Controls/Linux"
LOG_DIR="$DATA_DIR/Logs"
SERVICE_NAME="tater-agent"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
CONFIG_FILE="$DATA_DIR/config.json"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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

info()    { echo -e "${CYAN}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[OK]${NC} $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC} $*"; }
error()   { echo -e "${RED}[ERROR]${NC} $*" >&2; exit 1; }

echo ""
echo -e "${CYAN}============================================${NC}"
echo -e "${CYAN}  TATER Compliance Agent — Linux Installer${NC}"
echo -e "${CYAN}============================================${NC}"
echo ""

# Check root
if [ "$EUID" -ne 0 ]; then
    error "This installer must be run as root. Use: sudo bash install.sh"
fi

# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
    x86_64)  BINARY_NAME="tater-agent-linux-amd64" ;;
    aarch64) BINARY_NAME="tater-agent-linux-arm64" ;;
    *)       error "Unsupported architecture: $ARCH (supported: x86_64, aarch64)" ;;
esac
info "Architecture: $ARCH -> $BINARY_NAME"

# Find binary — check script directory first, then current directory
BINARY_PATH=""
for search_dir in "$SCRIPT_DIR" "$(pwd)"; do
    if [ -f "$search_dir/$BINARY_NAME" ]; then
        BINARY_PATH="$search_dir/$BINARY_NAME"
        break
    fi
done

if [ -z "$BINARY_PATH" ]; then
    # Try to download from TATER
    if [ -n "${TATER_API_BASE:-}" ]; then
        BASE_URL="${TATER_API_BASE%/api}"
        info "Binary not found locally — downloading from $BASE_URL/Agent/$BINARY_NAME ..."
        if command -v curl >/dev/null 2>&1; then
            curl -fsSL -o "/tmp/$BINARY_NAME" "$BASE_URL/Agent/$BINARY_NAME" || error "Download failed"
            BINARY_PATH="/tmp/$BINARY_NAME"
        elif command -v wget >/dev/null 2>&1; then
            wget -q -O "/tmp/$BINARY_NAME" "$BASE_URL/Agent/$BINARY_NAME" || error "Download failed"
            BINARY_PATH="/tmp/$BINARY_NAME"
        else
            error "Binary $BINARY_NAME not found and curl/wget not available for download."
        fi
    else
        error "Binary $BINARY_NAME not found in $SCRIPT_DIR or $(pwd). Place the binary next to install.sh or set TATER_API_BASE."
    fi
fi

info "Binary: $BINARY_PATH"

# Create directories
info "Creating directories..."
mkdir -p "$DATA_DIR" "$CONTROLS_DIR" "$LOG_DIR"
chmod 750 "$DATA_DIR"
success "Directories created"

# Copy Linux control scripts if available
if [ -d "$SCRIPT_DIR/../Controls/Linux" ]; then
    cp "$SCRIPT_DIR/../Controls/Linux/"*.sh "$CONTROLS_DIR/" 2>/dev/null || true
    chmod +x "$CONTROLS_DIR/"*.sh 2>/dev/null || true
    script_count=$(ls "$CONTROLS_DIR/"*.sh 2>/dev/null | wc -l)
    success "Copied $script_count Linux control scripts to $CONTROLS_DIR"
elif [ -d "$SCRIPT_DIR/controls" ]; then
    cp "$SCRIPT_DIR/controls/"*.sh "$CONTROLS_DIR/" 2>/dev/null || true
    chmod +x "$CONTROLS_DIR/"*.sh 2>/dev/null || true
fi

# Install binary
info "Installing binary to $INSTALL_DIR/$SERVICE_NAME ..."
cp "$BINARY_PATH" "$INSTALL_DIR/$SERVICE_NAME"
chmod 755 "$INSTALL_DIR/$SERVICE_NAME"
success "Binary installed"

# Collect configuration
echo ""
info "Configuration"
echo ""

if [ -z "${TATER_API_BASE:-}" ]; then
    read -r -p "  TATER API Base URL [https://api.tatersecurity.com/api]: " TATER_API_BASE
    TATER_API_BASE="${TATER_API_BASE:-https://api.tatersecurity.com/api}"
fi

if [ -z "${TATER_API_KEY:-}" ]; then
    read -r -s -p "  TATER API Key: " TATER_API_KEY
    echo ""
fi

if [ -z "${TATER_TENANT_ID:-}" ]; then
    read -r -p "  Azure AD Tenant ID: " TATER_TENANT_ID
fi

if [ -z "${TATER_ORG_ID:-}" ]; then
    read -r -p "  TATER Organization ID (optional, press Enter to skip): " TATER_ORG_ID
fi

# Write config
info "Writing configuration to $CONFIG_FILE ..."
cat > "$CONFIG_FILE" <<EOF
{
  "apiBase": "${TATER_API_BASE}",
  "apiKey": "${TATER_API_KEY}",
  "tenantId": "${TATER_TENANT_ID}",
  "organizationId": "${TATER_ORG_ID:-}",
  "controlsPath": "${CONTROLS_DIR}",
  "logPath": "${LOG_DIR}",
  "scanIntervalHours": 24,
  "dashboardUrl": "https://app.tatersecurity.com"
}
EOF
chmod 600 "$CONFIG_FILE"
success "Configuration written"

# Install systemd service
info "Installing systemd service..."
if [ -f "$SCRIPT_DIR/tater-agent.service" ]; then
    cp "$SCRIPT_DIR/tater-agent.service" "$SERVICE_FILE"
else
    cat > "$SERVICE_FILE" <<'UNIT'
[Unit]
Description=TATER Compliance Agent
After=network.target
StartLimitIntervalSec=300
StartLimitBurst=5

[Service]
Type=simple
ExecStart=/usr/local/bin/tater-agent
Restart=always
RestartSec=30
WorkingDirectory=/var/lib/tater
User=root
StandardOutput=journal
StandardError=journal
SyslogIdentifier=tater-agent

[Install]
WantedBy=multi-user.target
UNIT
fi
chmod 644 "$SERVICE_FILE"

systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

# Verify service started
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
    success "Service started successfully"
else
    warn "Service may not have started — check: journalctl -u $SERVICE_NAME -n 20"
fi

echo ""
echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN}  Installation Complete!${NC}"
echo -e "${GREEN}============================================${NC}"
echo ""
echo "  Service:    $SERVICE_NAME"
echo "  Status:     systemctl status $SERVICE_NAME"
echo "  Logs:       journalctl -u $SERVICE_NAME -f"
echo "  Config:     $CONFIG_FILE"
echo "  Controls:   $CONTROLS_DIR"
echo ""
echo "  The agent will run its first compliance scan now."
echo "  Results will appear in TATER within a few minutes."
echo ""
