#!/bin/bash

# Override DB Password Script
# This script overrides the dbPassword field in configserversecret.yaml with a base64 encoded value

set -euo pipefail

# Default configuration
YAML_FILE="./cleaned-secrets/configserversecret.yaml"
NEW_PASSWORD=""
BACKUP_SUFFIX=".backup"

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

This script overrides the dbPassword field in configserversecret.yaml with a base64 encoded value.

Usage: $0 [OPTIONS]

OPTIONS:
    --password PASSWORD    New password to set (REQUIRED)
    --file FILE           Path to configserversecret.yaml file (default: ./cleaned-secrets/configserversecret.yaml)
    --help                Show this help message

EXAMPLES:
    $0 --password mynewpassword
    $0 --password mynewpassword --file /path/to/configserversecret.yaml
EOF
}

# Parse command-line arguments
parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --password)
                NEW_PASSWORD="$2"
                shift 2
                ;;
            --file)
                YAML_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 [[ -z "$NEW_PASSWORD" ]]; then
        log_error "Password (--password) is required."
        show_help
        exit 1
    fi

    if [[ ! -f "$YAML_FILE" ]]; then
        log_error "YAML file does not exist: $YAML_FILE"
        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
}

# Create backup of original file
create_backup() {
    local backup_file="${YAML_FILE}${BACKUP_SUFFIX}"
    
    log_info "Creating backup of original file: $backup_file"
    
    if cp "$YAML_FILE" "$backup_file"; then
        log_success "Backup created: $backup_file"
    else
        log_error "Failed to create backup"
        exit 1
    fi
}

# Override dbPassword in YAML file
override_db_password() {
    log_info "Overriding dbPassword in $(basename "$YAML_FILE")..."
    
    # Base64 encode the new password
    local encoded_password
    encoded_password=$(echo -n "$NEW_PASSWORD" | base64)
    
    if [[ $? -ne 0 ]]; then
        log_error "Failed to base64 encode password"
        exit 1
    fi
    
    log_info "Base64 encoded password: $encoded_password"
    
    # Create temporary file for the modified content
    local temp_file=$(mktemp)
    
    # Use sed to replace the dbPassword value
    if sed "s/dbPassword: .*/dbPassword: $encoded_password/" "$YAML_FILE" > "$temp_file"; then
        # Replace original file with modified content
        if mv "$temp_file" "$YAML_FILE"; then
            log_success "Successfully overridden dbPassword in $(basename "$YAML_FILE")"
        else
            log_error "Failed to update YAML file"
            rm -f "$temp_file"
            exit 1
        fi
    else
        log_error "Failed to modify YAML file"
        rm -f "$temp_file"
        exit 1
    fi
}

# Verify the change
verify_change() {
    log_info "Verifying the change..."
    
    # Check if dbPassword field exists and has the new value
    local current_encoded
    current_encoded=$(grep "dbPassword:" "$YAML_FILE" | awk '{print $2}')
    
    if [[ -n "$current_encoded" ]]; then
        # Decode to verify it matches our input
        local decoded_password
        decoded_password=$(echo "$current_encoded" | base64 -d 2>/dev/null)
        
        if [[ "$decoded_password" == "$NEW_PASSWORD" ]]; then
            log_success "Verification successful: dbPassword has been updated correctly"
            log_info "Original password: [hidden]"
            log_info "New password: [hidden]"
            log_info "Base64 encoded value: $current_encoded"
        else
            log_error "Verification failed: Password does not match expected value"
            exit 1
        fi
    else
        log_error "Verification failed: dbPassword field not found in YAML file"
        exit 1
    fi
}

# Main function
main() {
    parse_arguments "$@"
    validate_parameters
    check_base64
    
    log_info "Starting dbPassword override process..."
    log_info "Target file: $YAML_FILE"
    log_info "New password: [hidden]"
    
    # Create backup before making changes
    create_backup
    
    # Override the password
    override_db_password
    
    # Verify the change
    verify_change
    
    log_success "dbPassword override process completed successfully!"
    log_info "Original file backed up as: ${YAML_FILE}${BACKUP_SUFFIX}"
    log_info "Modified file: $YAML_FILE"
}

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