#!/bin/bash

# Extract DB Password Script
# This script extracts and decodes the dbPassword from configserversecret in hubble-system namespace

set -euo pipefail

# Default configuration (hardcoded)
KUBECONFIG_FILE=""
SECRET_NAME="configserversecret"
NAMESPACE="hubble-system"
PASSWORD_KEY="dbPassword"

# 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 DB Password Script

This script extracts and decodes the dbPassword from configserversecret in hubble-system namespace.

Usage: $0 [OPTIONS]

OPTIONS:
    --kubeconfig FILE    Path to kubeconfig file (optional, uses default if not provided)
    --help               Show this help message

EXAMPLES:
    $0 --kubeconfig /path/to/kubeconfig
    $0
EOF
}

# Parse command-line arguments
parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --kubeconfig)
                KUBECONFIG_FILE="$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
}

# Check if base64 is available
check_base64() {
    if ! command -v base64 &> /dev/null; then
        log_error "base64 command not found. Please install base64."
        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"
}

# Extract and decode the password
extract_password() {
    log_info "Extracting $PASSWORD_KEY from secret $SECRET_NAME in namespace $NAMESPACE..."
    
    local kubectl_cmd="kubectl"
    if [[ -n "$KUBECONFIG_FILE" ]]; then
        kubectl_cmd="kubectl --kubeconfig=$KUBECONFIG_FILE"
    fi
    
    # Check if secret exists
    if ! eval "$kubectl_cmd get secret $SECRET_NAME -n $NAMESPACE" &>/dev/null; then
        log_error "Secret '$SECRET_NAME' not found in namespace '$NAMESPACE'"
        exit 1
    fi
    
    # Extract the base64 encoded password
    local encoded_password
    encoded_password=$(eval "$kubectl_cmd get secret $SECRET_NAME -n $NAMESPACE -o jsonpath='{.data.$PASSWORD_KEY}'" 2>/dev/null)
    
    if [[ -z "$encoded_password" ]]; then
        log_error "Key '$PASSWORD_KEY' not found in secret '$SECRET_NAME'"
        log_info "Available keys in the secret:"
        eval "$kubectl_cmd get secret $SECRET_NAME -n $NAMESPACE -o jsonpath='{.data}'" | jq -r 'keys[]' 2>/dev/null || eval "$kubectl_cmd get secret $SECRET_NAME -n $NAMESPACE -o yaml" | grep -E '^  [a-zA-Z]:' | sed 's/^  //' | cut -d: -f1
        exit 1
    fi
    
    # Decode the password
    local decoded_password
    decoded_password=$(echo "$encoded_password" | base64 -d 2>/dev/null)
    
    if [[ $? -ne 0 ]]; then
        log_error "Failed to decode base64 password"
        exit 1
    fi
    
    log_success "Password extracted and decoded successfully"
    
    # Output the password
    echo "=========================================="
    echo "Secret: $SECRET_NAME"
    echo "Namespace: $NAMESPACE"
    echo "Key: $PASSWORD_KEY"
    echo "Decoded Password: $decoded_password"
    echo "=========================================="
    
    # Output the password to stdout for parent script to capture
    echo "$decoded_password"
}

# Main function
main() {
    parse_arguments "$@"
    validate_parameters
    check_kubectl
    check_base64
    test_cluster_connection
    extract_password
}

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