#!/bin/bash

# CloudXM Plugin Upload to Hostinger Server
# Usage: ./upload-to-hostinger.sh <plugin_name> <version> <public_dir> <server_url>
#
# Environment Variables Required:
# - CLOUDXM_AUTH_TOKEN: Authentication token for the server
# - PLUGIN_DEPLOYMENT_URL: Base URL of the plugin server (e.g., https://plugins.cloudxm.com.br)

set -e

# Configuration
PLUGIN_NAME=$1
VERSION=$2
PUBLIC_DIR=$3
SERVER_URL=$4

# Determine deployment path based on environment
if [ -n "$CI_COMMIT_TAG" ]; then
    DEPLOY_PATH="stable"
    echo "Using stable deployment path"
else
    DEPLOY_PATH="dev"
    echo "Using dev deployment path"
fi

# Default values
SERVER_URL=${SERVER_URL:-"https://plugin.cloudxm.com.br"}
SERVER_URL="$SERVER_URL/$DEPLOY_PATH"
AUTH_TOKEN=${CLOUDXM_AUTH_TOKEN}

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

# Logging functions
log() {
    echo -e "${GREEN}✓ $1${NC}"
}

warn() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

error() {
    echo -e "${RED}❌ $1${NC}"
}

# Validate inputs
if [ -z "$PLUGIN_NAME" ] || [ -z "$VERSION" ] || [ -z "$PUBLIC_DIR" ]; then
    error "Usage: $0 <plugin_name> <version> <public_dir> [server_url]"
    exit 1
fi

if [ -z "$AUTH_TOKEN" ]; then
    error "CLOUDXM_AUTH_TOKEN environment variable is required"
    exit 1
fi

if [ -z "$SERVER_URL" ]; then
    error "PLUGIN_DEPLOYMENT_URL environment variable or server_url parameter is required"
    exit 1
fi

# Ensure server URL doesn't end with /
SERVER_URL=${SERVER_URL%/}

log "Starting upload of $PLUGIN_NAME v$VERSION to $SERVER_URL"

# Check if public directory exists
if [ ! -d "$PUBLIC_DIR" ]; then
    error "Public directory $PUBLIC_DIR does not exist"
    exit 1
fi

# Function to upload file via curl
upload_file() {
    local file_path=$1
    local filename=$2
    local upload_url="$SERVER_URL/plugins/upload"

    log "Uploading $filename..."

    if [ ! -f "$file_path" ]; then
        warn "File $file_path does not exist, skipping..."
        return 1
    fi

    # Upload using curl with authentication
    local response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "X-CloudXM-Auth: $AUTH_TOKEN" \
        -F "plugin=@$file_path" \
        -F "plugin_name=$PLUGIN_NAME" \
        -F "version=$VERSION" \
        "$upload_url")

    local http_code=$(echo "$response" | tail -n1)
    local response_body=$(echo "$response" | sed '$d')  # Remove last line (safer than head -n -1)

    if [ "$http_code" -eq 200 ]; then
        log "Successfully uploaded $filename"
        return 0
    else
        error "Failed to upload $filename (HTTP $http_code): $response_body"
        return 1
    fi
}

# Upload ZIP file (server will generate latest.json dynamically)
# Construct expected ZIP filename from plugin name and version
zip_filename="$PLUGIN_NAME-v$VERSION.zip"
zip_file="$PUBLIC_DIR/$zip_filename"

if [ ! -f "$zip_file" ]; then
    error "Expected ZIP file not found: $zip_file"
    error "Available files in $PUBLIC_DIR:"
    ls -la "$PUBLIC_DIR"/*.zip 2>/dev/null || echo "No ZIP files found"
    exit 1
fi

if upload_file "$zip_file" "$zip_filename"; then
    log "Plugin ZIP uploaded successfully"
else
    error "Failed to upload plugin ZIP"
    exit 1
fi

# Notify server that plugin was uploaded (server will auto-discover and update catalog)
log "Notifying server of plugin upload..."

notify_url="$SERVER_URL/plugins/uploaded"

notify_data="{
    \"plugin_name\": \"$PLUGIN_NAME\",
    \"version\": \"$VERSION\",
    \"filename\": \"$zip_filename\"
}"

notify_response=$(curl -s -w "\n%{http_code}" \
    -X POST \
    -H "Content-Type: application/json" \
    -H "X-CloudXM-Auth: $AUTH_TOKEN" \
    -d "$notify_data" \
    "$notify_url")

notify_http_code=$(echo "$notify_response" | tail -n1)
notify_response_body=$(echo "$notify_response" | sed '$d')

if [ "$notify_http_code" -eq 200 ]; then
    log "Plugin registration successful"
else
    error "Failed to register plugin (HTTP $notify_http_code): $notify_response_body"
    exit 1
fi

# Verify deployment
log "Verifying deployment..."
verify_response=$(curl -s -w "\n%{http_code}" "$SERVER_URL/plugins")
verify_http_code=$(echo "$verify_response" | tail -n1)
verify_response_body=$(echo "$verify_response" | sed '$d')  # Remove last line (safer than head -n -1)

if [ "$verify_http_code" -eq 200 ]; then
    # Check if our plugin is in the catalog
    if echo "$verify_response_body" | grep -q "$PLUGIN_NAME"; then
        log "✅ Deployment verified successfully!"
        log "🌐 Plugin available at: $SERVER_URL/$PLUGIN_NAME/"
        log "📦 Download URL: $SERVER_URL/$PLUGIN_NAME/$zip_filename"
        log "📄 Info URL: $SERVER_URL/$PLUGIN_NAME/latest.json"
    else
        warn "Plugin catalog updated but plugin not found in verification"
    fi
else
    warn "Could not verify deployment (HTTP $verify_http_code)"
fi

log "🎉 Plugin $PLUGIN_NAME v$VERSION uploaded successfully to $SERVER_URL"