#!/bin/bash
#
# ArmoredGate Installer
# https://get.armoredgate.com
#
# Usage:
#   curl -fsSL https://get.armoredgate.com/install.sh | bash
#   curl -fsSL https://get.armoredgate.com/install.sh | bash -s -- --version 1.0.0
#

set -euo pipefail

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

# Defaults
VERSION="${VERSION:-latest}"
INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"
BASE_URL="https://get.armoredgate.com/releases"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --version)
            VERSION="$2"
            shift 2
            ;;
        --dir)
            INSTALL_DIR="$2"
            shift 2
            ;;
        --help)
            echo "ArmoredGate Installer"
            echo ""
            echo "Usage: curl -fsSL https://get.armoredgate.com/install.sh | bash -s -- [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --version VERSION   Install specific version (default: latest)"
            echo "  --dir PATH          Install to directory (default: /usr/local/bin)"
            echo "  --help              Show this help message"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            exit 1
            ;;
    esac
done

# Logging
log() { echo -e "${BLUE}[ArmoredGate]${NC} $1"; }
success() { echo -e "${GREEN}[✓]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
error() { echo -e "${RED}[✗]${NC} $1"; exit 1; }

# Detect OS and architecture
detect_platform() {
    local os arch

    case "$(uname -s)" in
        Linux*)  os="linux" ;;
        Darwin*) os="darwin" ;;
        MINGW*|CYGWIN*|MSYS*) error "Windows is not supported. Please use WSL2." ;;
        *)       error "Unsupported operating system: $(uname -s)" ;;
    esac

    case "$(uname -m)" in
        x86_64|amd64)  arch="amd64" ;;
        arm64|aarch64) arch="arm64" ;;
        *)             error "Unsupported architecture: $(uname -m)" ;;
    esac

    echo "${os}-${arch}"
}

# Check requirements
check_requirements() {
    log "Checking requirements..."
    
    # Check for curl or wget
    if command -v curl &>/dev/null; then
        DOWNLOADER="curl"
    elif command -v wget &>/dev/null; then
        DOWNLOADER="wget"
    else
        error "curl or wget is required but not installed"
    fi

    # Check for root/sudo if installing to system directory
    if [[ "$INSTALL_DIR" == /usr* ]] && [[ $EUID -ne 0 ]]; then
        if command -v sudo &>/dev/null; then
            SUDO="sudo"
        else
            error "Root privileges required to install to $INSTALL_DIR"
        fi
    else
        SUDO=""
    fi

    # Linux-specific checks
    if [[ "$(uname -s)" == "Linux" ]]; then
        # Check for systemd
        if ! command -v systemctl &>/dev/null; then
            warn "systemd not found - some features may be limited"
        fi
        
        # Check for systemd-nspawn
        if ! command -v systemd-nspawn &>/dev/null; then
            warn "systemd-nspawn not found - container features require systemd-container package"
            log "Install with: apt install systemd-container (Debian/Ubuntu)"
            log "          or: dnf install systemd-container (RHEL/Rocky)"
        fi
    fi

    success "Requirements satisfied"
}

# Download file
download() {
    local url="$1"
    local dest="$2"
    
    if [[ "$DOWNLOADER" == "curl" ]]; then
        curl -fsSL "$url" -o "$dest"
    else
        wget -q "$url" -O "$dest"
    fi
}

# Install ArmoredGate
install() {
    local platform
    platform=$(detect_platform)
    
    log "Detected platform: $platform"
    log "Installing ArmoredGate ${VERSION}..."
    
    # Create temp directory
    local tmpdir
    tmpdir=$(mktemp -d)
    trap "rm -rf $tmpdir" EXIT
    
    # Download
    local archive_url="${BASE_URL}/${VERSION}/armoredgate-${platform}.tar.gz"
    local archive_path="${tmpdir}/armoredgate.tar.gz"
    
    log "Downloading from ${archive_url}..."
    if ! download "$archive_url" "$archive_path"; then
        error "Failed to download ArmoredGate. Check your network connection."
    fi
    
    # Extract
    log "Extracting..."
    tar -xzf "$archive_path" -C "$tmpdir"
    
    # Install binary
    log "Installing to ${INSTALL_DIR}..."
    $SUDO mkdir -p "$INSTALL_DIR"
    $SUDO mv "${tmpdir}/armoredgate" "${INSTALL_DIR}/armoredgate"
    $SUDO chmod +x "${INSTALL_DIR}/armoredgate"
    
    # Verify installation
    if ! "${INSTALL_DIR}/armoredgate" --version &>/dev/null; then
        error "Installation verification failed"
    fi
    
    success "ArmoredGate installed successfully!"
}

# Post-install
post_install() {
    local version
    version=$("${INSTALL_DIR}/armoredgate" --version 2>/dev/null || echo "unknown")
    
    echo ""
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}  ArmoredGate installed successfully!${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo "  Version:  ${version}"
    echo "  Location: ${INSTALL_DIR}/armoredgate"
    echo ""
    echo "  Get started:"
    echo "    armoredgate init          # Initialize a new project"
    echo "    armoredgate pull nginx    # Pull a container image"
    echo "    armoredgate run nginx     # Run a container"
    echo ""
    echo "  Documentation: https://docs.armoredgate.com"
    echo "  Support:       https://armoredgate.com/contact"
    echo ""
}

# Main
main() {
    echo ""
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}  ArmoredGate Installer${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    
    check_requirements
    install
    post_install
}

main
