#!/bin/bash

# exit immediately on error
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

# Base URL for downloads
BASE_URL="https://download.operator.cubbit.eu/download/"

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

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

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

# Function to detect OS and architecture
detect_platform() {
    local os=""
    local arch=""

    # Detect OS
    case "$(uname -s)" in
        Linux*)
            os="linux"
            ;;
        Darwin*)
            os="darwin"
            ;;
        *)
            print_error "Unsupported operating system: $(uname -s)"
            exit 1
            ;;
    esac

    # Detect architecture
    case "$(uname -m)" in
        x86_64|amd64)
            arch="amd64"
            ;;
        arm64|aarch64)
            arch="arm64"
            ;;
        *)
            print_error "Unsupported architecture: $(uname -m)"
            exit 1
            ;;
    esac

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

# Function to find the best installation directory
find_install_dir() {
    local install_dir=""

    # Check if custom install directory is provided via environment variable
    if [[ -n "$INSTALL_DIR" ]]; then
        if [[ -d "$INSTALL_DIR" ]] && [[ -w "$INSTALL_DIR" ]]; then
            install_dir="$INSTALL_DIR"
            print_status "Using custom installation directory: $INSTALL_DIR" >&2
        else
            print_error "Custom INSTALL_DIR '$INSTALL_DIR' doesn't exist or isn't writable"
            exit 1
        fi
    # Check if user has write permission to /usr/local/bin (preferred)
    elif [[ -d "/usr/local/bin" ]] && [[ -w "/usr/local/bin" ]]; then
        install_dir="/usr/local/bin"
    # Check if ~/.local/bin exists or can be created
    elif [[ -d "$HOME/.local/bin" ]] || mkdir -p "$HOME/.local/bin" > /dev/null; then
        install_dir="$HOME/.local/bin"
        # Add to PATH if not already there
        if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
            print_warning "Adding $HOME/.local/bin to PATH for this session" >&2
            export PATH="$HOME/.local/bin:$PATH"
            print_warning "To make this permanent, add 'export PATH=\"\$HOME/.local/bin:\$PATH\"' to your shell profile (~/.bashrc, ~/.zshrc, etc.)" >&2
        fi
    else
        print_error "Cannot find a suitable directory to install kubectl-cubbit"
        print_error "Please ensure you have write permissions to /usr/local/bin or ~/.local/bin"
        exit 1
    fi

    echo "$install_dir"
}

# Function to check if plugin is already installed
check_existing_plugin() {
    if command -v kubectl-cubbit >/dev/null 2>&1; then
        local existing_path
        existing_path=$(command -v kubectl-cubbit)
        print_warning "kubectl-cubbit is already installed at: $existing_path"

        # Check if we can read from stdin (not in a pipe)
        if [[ -t 0 ]] && [[ -z "$FORCE_OVERWRITE" ]]; then
            read -p "Do you want to overwrite it? (y/N): " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                print_status "Installation cancelled by user"
                exit 0
            fi
            print_status "Proceeding with overwrite..."
        elif [[ "$FORCE_OVERWRITE" == "true" ]]; then
            print_status "Force overwrite enabled, proceeding with installation..."
        else
            print_status "Running in non-interactive mode, automatically skipping overwrite of existing installation..."
            print_warning "To force overwrite, set FORCE_OVERWRITE=true in your environment"
            exit 0
        fi
        return 0
    else
        print_status "kubectl-cubbit not found in PATH, proceeding with installation..."
        return 0
    fi
}

# Function to download and install the plugin
install_plugin() {
    local platform="$1"
    local install_dir="$2"
    local download_url="${BASE_URL}/kubectl-cubbit-${platform}"
    local temp_file="/tmp/kubectl-cubbit-${platform}"
    local final_path="${install_dir}/kubectl-cubbit"

    print_status "Downloading kubectl-cubbit for $platform..."
    print_status "URL: $download_url"

    # Download the file
    if command -v curl >/dev/null 2>&1; then
        curl -L -o "$temp_file" "$download_url"
    elif command -v wget >/dev/null 2>&1; then
        wget -O "$temp_file" "$download_url"
    else
        print_error "Neither curl nor wget is available. Please install one of them."
        exit 1
    fi

    # Check if download was successful
    if [[ ! -f "$temp_file" ]]; then
        print_error "Failed to download kubectl-cubbit"
        exit 1
    fi

    # Check if the downloaded file is not empty and is a binary
    if [[ ! -s "$temp_file" ]]; then
        print_error "Downloaded file is empty"
        rm -f "$temp_file"
        exit 1
    fi

    # Add execution permission
    chmod +x "$temp_file"

    # Move to final destination
    print_status "Installing kubectl-cubbit to $final_path..."
    mv "$temp_file" "$final_path"

    print_success "kubectl-cubbit installed successfully!"
}

# Function to verify installation
verify_installation() {
    print_status "Verifying installation..."

    if ! command -v kubectl-cubbit >/dev/null 2>&1; then
        print_error "kubectl-cubbit not found in PATH after installation"
        print_error "You may need to restart your shell or add the installation directory to your PATH"
        exit 1
    fi

    print_status "Running 'kubectl cubbit version' to verify installation..."
    echo
    kubectl cubbit version
    echo
    print_success "Installation verified successfully!"
}

# Main execution
main() {
    print_status "Starting kubectl-cubbit installation..."

    # Check for existing installation
    check_existing_plugin

    # Detect platform and architecture
    platform=$(detect_platform)
    print_status "Detected platform: $platform"

    # Find installation directory
    install_dir=$(find_install_dir)
    print_status "Installation directory: $install_dir"
    if [[ ":$PATH:" != *":$install_dir:"* ]]; then
        export PATH="$install_dir:$PATH"
    fi

    # Install the plugin
    install_plugin "$platform" "$install_dir"

    # Verify installation
    verify_installation

    print_success "kubectl-cubbit installation completed successfully!"
    print_status "You can now use 'kubectl cubbit' commands."
}

# Check if kubectl is installed
if ! command -v kubectl >/dev/null 2>&1; then
    print_error "kubectl is not installed or not in PATH"
    print_error "Please install kubectl first: https://kubernetes.io/docs/tasks/tools/"
    exit 1
fi

# Run main function
main
---
