#!/bin/bash
#
# rskiller installer script
# This script detects the platform and installs the appropriate binary
#

set -e

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

# Default values
INSTALL_DIR="/usr/local/bin"
REPO="NakaSato/rskiller"
GITHUB_API="https://api.github.com/repos/${REPO}"
GITHUB_DOWNLOAD="https://github.com/${REPO}/releases/latest/download"

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

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

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

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

# Detect platform and architecture
detect_platform() {
    local os arch
    
    case "$(uname -s)" in
        Darwin*)
            os="macos"
            ;;
        Linux*)
            os="linux"
            ;;
        *)
            error "Unsupported operating system: $(uname -s)"
            ;;
    esac
    
    case "$(uname -m)" in
        x86_64|amd64)
            arch="x64"
            ;;
        arm64|aarch64)
            arch="arm64"
            ;;
        *)
            error "Unsupported architecture: $(uname -m)"
            ;;
    esac
    
    echo "${os}-${arch}"
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Download and install binary
install_binary() {
    local platform="$1"
    local filename="rskiller-${platform}.tar.gz"
    local url="${GITHUB_DOWNLOAD}/${filename}"
    local temp_dir
    
    info "Detected platform: ${platform}"
    info "Download URL: ${url}"
    
    # Create temporary directory
    temp_dir=$(mktemp -d)
    trap "rm -rf ${temp_dir}" EXIT
    
    # Download binary
    info "Downloading rskiller..."
    if command_exists curl; then
        curl -L -o "${temp_dir}/${filename}" "${url}" || error "Failed to download binary"
    elif command_exists wget; then
        wget -O "${temp_dir}/${filename}" "${url}" || error "Failed to download binary"
    else
        error "Neither curl nor wget is available. Please install one of them."
    fi
    
    # Extract binary
    info "Extracting binary..."
    tar -xzf "${temp_dir}/${filename}" -C "${temp_dir}" || error "Failed to extract binary"
    
    # Install binary
    info "Installing to ${INSTALL_DIR}..."
    
    # Check if we need sudo
    if [ -w "${INSTALL_DIR}" ]; then
        mv "${temp_dir}/rskiller" "${INSTALL_DIR}/" || error "Failed to install binary"
    else
        warn "Installation directory requires elevated privileges"
        sudo mv "${temp_dir}/rskiller" "${INSTALL_DIR}/" || error "Failed to install binary with sudo"
    fi
    
    # Make executable
    chmod +x "${INSTALL_DIR}/rskiller" || sudo chmod +x "${INSTALL_DIR}/rskiller"
    
    success "rskiller installed successfully!"
}

# Verify installation
verify_installation() {
    if command_exists rskiller; then
        local version
        version=$(rskiller --version 2>/dev/null || echo "unknown")
        success "Installation verified: ${version}"
        info "You can now run 'rskiller' from anywhere in your terminal"
    else
        warn "Binary installed but not found in PATH"
        info "You may need to restart your terminal or run:"
        info "  export PATH=\"${INSTALL_DIR}:\$PATH\""
    fi
}

# Check for existing installation
check_existing() {
    if command_exists rskiller; then
        local current_version
        current_version=$(rskiller --version 2>/dev/null || echo "unknown")
        warn "rskiller is already installed: ${current_version}"
        
        read -p "Do you want to update/reinstall? [y/N] " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            info "Installation cancelled"
            exit 0
        fi
    fi
}

# Main installation function
main() {
    echo "🦀 rskiller installer"
    echo "====================="
    echo
    
    # Parse command line arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --install-dir)
                INSTALL_DIR="$2"
                shift 2
                ;;
            --help|-h)
                echo "Usage: $0 [--install-dir DIR]"
                echo "  --install-dir DIR  Install directory (default: /usr/local/bin)"
                exit 0
                ;;
            *)
                error "Unknown option: $1"
                ;;
        esac
    done
    
    # Validate requirements
    if ! command_exists tar; then
        error "tar is required but not installed"
    fi
    
    # Check for existing installation
    check_existing
    
    # Detect platform and install
    local platform
    platform=$(detect_platform)
    install_binary "${platform}"
    
    # Verify installation
    verify_installation
    
    echo
    success "🎉 Installation complete!"
    info "Run 'rskiller --help' to get started"
}

# Run main function
main "$@"