#!/bin/bash

# Extract and Clean Secrets Script
# This script extracts secrets and removes metadata fields that shouldn't be applied

set -euo pipefail

# Default configuration
KUBECONFIG_FILE=""
OUTPUT_DIR="./cleaned-secrets"

# sed in-place: Darwin (macOS) requires sed -i '', Linux uses sed -i
if [[ "$(uname -s)" == "Darwin" ]]; then
    SED_INPLACE=(sed -i "")
else
    SED_INPLACE=(sed -i)
fi

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

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

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

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

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

# Show help message
show_help() {
    cat << EOF
Extract and Clean Secrets Script

This script performs the following operations:
1. Extract configserversecret from hubble-system namespace to YAML file
2. Extract msgbroker-secret from hubble-system namespace to YAML file
3. Clean both YAML files by removing metadata fields

Usage: $0 [OPTIONS]

OPTIONS:
    --kubeconfig FILE    Path to kubeconfig file (optional, uses default if not provided)
    --output-dir DIR     Output directory for cleaned files (default: ./cleaned-secrets)
    --help               Show this help message

EXAMPLES:
    $0 --kubeconfig /path/to/kubeconfig
    $0 --output-dir /tmp/secrets
EOF
}

# Parse command-line arguments
parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --kubeconfig)
                KUBECONFIG_FILE="$2"
                shift 2
                ;;
            --output-dir)
                OUTPUT_DIR="$2"
                shift 2
                ;;
            --help)
                show_help
                exit 0
                ;;
            *)
                log_error "Unknown option: $1"
                show_help
                exit 1
                ;;
        esac
    done
}

# Validate parameters
validate_parameters() {
    if [[ -n "$KUBECONFIG_FILE" && ! -f "$KUBECONFIG_FILE" ]]; then
        log_error "kubeconfig file does not exist: $KUBECONFIG_FILE"
        exit 1
    fi
}

# Check if kubectl is available
check_kubectl() {
    if ! command -v kubectl &> /dev/null; then
        log_error "kubectl command not found. Please install kubectl."
        exit 1
    fi
}

# Test cluster connectivity
test_cluster_connection() {
    log_info "Testing cluster connectivity..."
    
    local kubectl_cmd="kubectl"
    if [[ -n "$KUBECONFIG_FILE" ]]; then
        kubectl_cmd="kubectl --kubeconfig=$KUBECONFIG_FILE"
    fi
    
    if ! eval "$kubectl_cmd cluster-info" &>/dev/null; then
        log_error "Failed to connect to cluster. Please check your kubeconfig and cluster status."
        exit 1
    fi
    log_success "Cluster connection successful"
}

# Create output directory
create_output_directory() {
    log_info "Creating output directory: $OUTPUT_DIR"
    
    if [[ ! -d "$OUTPUT_DIR" ]]; then
        mkdir -p "$OUTPUT_DIR"
        log_success "Created output directory: $OUTPUT_DIR"
    else
        log_info "Output directory already exists: $OUTPUT_DIR"
    fi
}

# Extract secret to YAML file
extract_secret() {
    local secret_name="$1"
    local namespace="$2"
    local output_file="$3"
    
    log_info "Extracting $secret_name from $namespace namespace..."
    
    local kubectl_cmd="kubectl"
    if [[ -n "$KUBECONFIG_FILE" ]]; then
        kubectl_cmd="kubectl --kubeconfig=$KUBECONFIG_FILE"
    fi
    
    if ! eval "$kubectl_cmd get secret $secret_name -n $namespace -o yaml" > "$output_file" 2>/dev/null; then
        log_error "Failed to extract $secret_name from $namespace namespace"
        exit 1
    fi
    
    log_success "$secret_name extracted to $(basename "$output_file")"
}

# Clean YAML file by removing metadata fields
clean_yaml_file() {
    local yaml_file="$1"
    
    log_info "Cleaning $(basename "$yaml_file")..."
    
    # Remove metadata fields that shouldn't be applied
    "${SED_INPLACE[@]}" "/resourceVersion:/d" "$yaml_file"
    "${SED_INPLACE[@]}" "/selfLink/d" "$yaml_file"
    "${SED_INPLACE[@]}" "/uid:/d" "$yaml_file"
    "${SED_INPLACE[@]}" "/creationTimestamp:/d" "$yaml_file"
    "${SED_INPLACE[@]}" "/last-applied-configuration:/d" "$yaml_file"
    "${SED_INPLACE[@]}" "/{\"apiVersion\":/d" "$yaml_file"
    
    log_success "Cleaned $(basename "$yaml_file")"
}

# Extract and clean configserversecret
extract_and_clean_configserver_secret() {
    local output_file="$OUTPUT_DIR/configserversecret.yaml"
    
    extract_secret "configserversecret" "hubble-system" "$output_file"
    clean_yaml_file "$output_file"
}

# Extract and clean msgbroker-secret
extract_and_clean_msgbroker_secret() {
    local output_file="$OUTPUT_DIR/msgbroker-secret.yaml"
    
    extract_secret "msgbroker-secret" "hubble-system" "$output_file"
    clean_yaml_file "$output_file"
}

# Main function
main() {
    parse_arguments "$@"
    validate_parameters
    check_kubectl
    test_cluster_connection
    create_output_directory
    
    log_info "Starting secret extraction and cleaning process..."
    
    # Step 1: Extract and clean configserversecret
    extract_and_clean_configserver_secret
    
    # Step 2: Extract and clean msgbroker-secret
    extract_and_clean_msgbroker_secret
    
    log_success "Secret extraction and cleaning process completed successfully!"
    log_info "All cleaned files are available in: $OUTPUT_DIR"
    
    # List extracted files
    log_info "Cleaned files:"
    ls -la "$OUTPUT_DIR"
}

# Run main function with all arguments
main "$@"
