#!/bin/bash
set -e

# InstaTunnel CLI Installation Script
INSTALL_DIR="/usr/local/bin"
REPO_URL="https://instatunnel.my/releases"
GITHUB_URL="https://github.com/instatunnel/cli/releases/latest/download"

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

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

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

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

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

# Detect OS and architecture
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case $ARCH in
    x86_64) ARCH="amd64" ;;
    arm64|aarch64) ARCH="arm64" ;;
    i386|i686) ARCH="386" ;;
    *) print_error "Unsupported architecture: $ARCH"; exit 1 ;;
esac

case $OS in
    linux) PLATFORM="linux-$ARCH" ;;
    darwin) PLATFORM="darwin-$ARCH" ;;
    freebsd) PLATFORM="freebsd-$ARCH" ;;
    openbsd) PLATFORM="openbsd-$ARCH" ;;
    msys*|mingw*|cygwin*) print_error "Windows users should use: choco install instatunnel"; exit 1 ;;
    *) print_error "Unsupported OS: $OS"; exit 1 ;;
esac

BINARY_NAME="instatunnel-$PLATFORM"
if [ "$OS" = "windows" ]; then
    BINARY_NAME="$BINARY_NAME.exe"
fi

print_status "Installing InstaTunnel CLI for $OS/$ARCH..."

# Try primary URL first, fallback to GitHub
BINARY_URL="$REPO_URL/$BINARY_NAME"
FALLBACK_URL="$GITHUB_URL/$BINARY_NAME"

# Create temp directory
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

cd "$TEMP_DIR"

# Download binary with fallback
print_status "Downloading binary..."
if ! curl -fsSL "$BINARY_URL" -o "instatunnel" 2>/dev/null; then
    print_warning "Primary download failed, trying GitHub releases..."
    if ! curl -fsSL "$FALLBACK_URL" -o "instatunnel"; then
        print_error "Failed to download binary from both sources"
        exit 1
    fi
fi

# Verify binary
if [ ! -f "instatunnel" ] || [ ! -s "instatunnel" ]; then
    print_error "Downloaded binary is invalid"
    exit 1
fi

# Make executable
chmod +x "instatunnel"

# Check if we need sudo for installation
if [ -w "$INSTALL_DIR" ]; then
    mv "instatunnel" "$INSTALL_DIR/"
    # Also create 'it' alias
    cp "$INSTALL_DIR/instatunnel" "$INSTALL_DIR/it"
    print_status "Installed to $INSTALL_DIR/"
else
    print_status "Installing to $INSTALL_DIR/ (requires sudo)..."
    sudo mv "instatunnel" "$INSTALL_DIR/"
    # Also create 'it' alias
    sudo cp "$INSTALL_DIR/instatunnel" "$INSTALL_DIR/it"
fi

print_success "InstaTunnel CLI installed successfully!"
echo ""
print_status "🚀 Quick Start:"
echo "   instatunnel 3000    # Expose port 3000 instantly (no setup needed!)"
echo "   it 3000             # Short alias for the same command"
echo ""
print_status "💡 More examples:"
echo "   instatunnel         # Auto-detect common ports (3000, 8000, 8080)"
echo "   instatunnel 8080 --name myapp"
echo "   instatunnel --help  # See all options"
echo ""
print_status "📚 Documentation: https://docs.instatunnel.my"

# Test installation
if command -v instatunnel >/dev/null 2>&1; then
    VERSION=$(instatunnel --version 2>/dev/null || echo "unknown")
    print_success "Installation verified! Version: $VERSION"
else
    print_warning "Installation complete but 'instatunnel' command not found in PATH"
    print_warning "You may need to restart your terminal or add $INSTALL_DIR to your PATH"
fi
