#!/bin/bash
set -e

# simpliCD Install Script
# https://github.com/nigelbasa/simplicd

VERSION="${VERSION:-latest}"
INSTALL_DIR="/usr/local/bin"
CONFIG_DIR="/etc/simplicd"
DATA_DIR="/var/lib/simplicd"
REPO="nigelbasa/simplicd"

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

info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

success() {
    echo -e "${GREEN}[OK]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
    exit 1
}

# Check if running as root
check_root() {
    if [ "$EUID" -ne 0 ]; then
        error "Please run as root or with sudo"
    fi
}

# Detect architecture
detect_arch() {
    ARCH=$(uname -m)
    case $ARCH in
        x86_64)
            ARCH="amd64"
            ;;
        aarch64)
            ARCH="arm64"
            ;;
        armv7l)
            ARCH="armv7"
            ;;
        *)
            error "Unsupported architecture: $ARCH"
            ;;
    esac
    info "Detected architecture: $ARCH"
}

# Detect OS
detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$ID
        info "Detected OS: $OS"
    else
        error "Cannot detect OS"
    fi
}

# Get latest version from GitHub
get_latest_version() {
    if [ "$VERSION" = "latest" ]; then
        VERSION=$(curl -s "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
        if [ -z "$VERSION" ]; then
            VERSION="v1.0.0"
            warn "Could not fetch latest version, using $VERSION"
        fi
    fi
    info "Installing version: $VERSION"
}

# Download and install binary with SHA256 verification against the release's
# checksums.txt. Refuses to install if the checksum doesn't match — protects
# against tampered mirrors / interrupted downloads.
install_binary() {
    info "Downloading simpliCD..."

    DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${VERSION}/simplicd-linux-${ARCH}"
    CHECKSUMS_URL="https://github.com/${REPO}/releases/download/${VERSION}/checksums.txt"

    curl -fsSL "$DOWNLOAD_URL" -o /tmp/simplicd || error "Failed to download binary from $DOWNLOAD_URL"

    info "Verifying SHA256..."
    if curl -fsSL "$CHECKSUMS_URL" -o /tmp/simplicd.checksums 2>/dev/null; then
        EXPECTED=$(grep "simplicd-linux-${ARCH}$" /tmp/simplicd.checksums | awk '{print $1}')
        if [ -z "$EXPECTED" ]; then
            warn "No checksum entry for simplicd-linux-${ARCH} — skipping verification"
        else
            ACTUAL=$(sha256sum /tmp/simplicd | awk '{print $1}')
            if [ "$EXPECTED" != "$ACTUAL" ]; then
                rm -f /tmp/simplicd /tmp/simplicd.checksums
                error "SHA256 mismatch (expected ${EXPECTED:0:16}…, got ${ACTUAL:0:16}…). Aborting."
            fi
            success "SHA256 verified"
        fi
        rm -f /tmp/simplicd.checksums
    else
        warn "checksums.txt not published for this release — skipping verification"
    fi

    chmod +x /tmp/simplicd
    mv /tmp/simplicd "$INSTALL_DIR/simplicd"
    success "Installed to $INSTALL_DIR/simplicd"
}

# Create directories
create_directories() {
    info "Creating directories..."
    
    mkdir -p "$CONFIG_DIR"
    mkdir -p "$DATA_DIR"/{pids,logs,stats}
    
    chmod 755 "$CONFIG_DIR"
    chmod 755 "$DATA_DIR"
    
    success "Created directories"
}

# Install systemd service
install_service() {
    info "Installing systemd service..."
    
    cat > /lib/systemd/system/simplicd.service << 'EOF'
[Unit]
Description=simpliCD - Simple Continuous Deployment
Documentation=https://github.com/nigelbasa/simplicd
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/simplicd serve
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
EnvironmentFile=-/etc/simplicd/env

# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/var/lib/simplicd /etc/simplicd

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    success "Installed systemd service"
}

# Create example config if not exists
create_config() {
    if [ ! -f "$CONFIG_DIR/config.yaml" ]; then
        info "Creating example config..."
        cat > "$CONFIG_DIR/config.yaml" << 'EOF'
# simpliCD Configuration
# See: https://github.com/nigelbasa/simplicd

server:
  port: 9090
  data_dir: /var/lib/simplicd
  log_level: info

projects: []
  # Example project:
  # - name: my-app
  #   repo: git@github.com:user/my-app.git
  #   branch: main
  #   path: /var/www/my-app
  #   build:
  #     - npm ci
  #     - npm run build
  #   start: npm start
  #   health_check:
  #     url: http://localhost:3000/health
  #     timeout: 30s
EOF
        success "Created $CONFIG_DIR/config.yaml"
    else
        warn "Config already exists at $CONFIG_DIR/config.yaml"
    fi
}

# Print success message
print_success() {
    echo ""
    echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}  simpliCD installed successfully!${NC}"
    echo -e "${GREEN}════════════════════════════════════════════════════════════${NC}"
    echo ""
    echo "  Commands:"
    echo "    simplicd init          - Interactive setup"
    echo "    simplicd add           - Add a project"
    echo "    simplicd deploy <name> - Deploy a project"
    echo "    simplicd list          - List all projects"
    echo "    simplicd serve         - Start the server"
    echo ""
    echo "  Service:"
    echo "    sudo systemctl start simplicd   - Start service"
    echo "    sudo systemctl enable simplicd  - Enable on boot"
    echo "    sudo systemctl status simplicd  - Check status"
    echo ""
    echo "  Config: $CONFIG_DIR/config.yaml"
    echo "  Docs:   https://github.com/nigelbasa/simplicd"
    echo ""
}

# Main
main() {
    echo ""
    echo -e "${BLUE}╔═══════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║     simpliCD Installer                ║${NC}"
    echo -e "${BLUE}║     Simple Continuous Deployment      ║${NC}"
    echo -e "${BLUE}╚═══════════════════════════════════════╝${NC}"
    echo ""
    
    check_root
    detect_arch
    detect_os
    get_latest_version
    install_binary
    create_directories
    install_service
    create_config
    print_success
}

main "$@"
