#!/usr/bin/env nu

# Generate Random Secrets for Provisioning Platform
# Creates a .env file with secure random secrets

def main [
    --output: string = ".env"   # Output file path
    --force                     # Overwrite existing file
] {
    print $"(ansi green_bold)Generating Secrets for Provisioning Platform(ansi reset)"
    print ""

    # Check if file exists
    if ($output | path exists) and not $force {
        print $"(ansi red_bold)Error:(ansi reset) ($output) already exists"
        print "Use --force to overwrite"
        return 1
    }

    # Read template
    if not (".env.example" | path exists) {
        print $"(ansi red_bold)Error:(ansi reset) .env.example not found"
        return 1
    }

    mut content = (open .env.example)

    # Generate secrets
    let secrets = {
        "CHANGE_ME_RANDOM_SECRET_HERE": (generate_secret 32),
        "CHANGE_ME_GITEA_SECRET_KEY": (generate_secret 32),
        "CHANGE_ME_ADMIN_PASSWORD": (generate_password 16),
        "CHANGE_ME_POSTGRES_PASSWORD": (generate_password 24),
        "CHANGE_ME_API_SERVER_JWT_SECRET": (generate_secret 32),
        "CHANGE_ME_HARBOR_ADMIN_PASSWORD": (generate_password 16),
        "CHANGE_ME_HARBOR_DB_PASSWORD": (generate_password 24),
        "CHANGE_ME_HARBOR_CORE_SECRET": (generate_secret 32),
        "CHANGE_ME_HARBOR_JOBSERVICE_SECRET": (generate_secret 32),
        "CHANGE_ME_GRAFANA_PASSWORD": (generate_password 16)
    }

    # Replace placeholders
    for secret in ($secrets | transpose key value) {
        $content = ($content | str replace -a $secret.key $secret.value)
    }

    # Save file
    $content | save -f $output

    print $"(ansi green)✓ Generated ($output) with secure secrets(ansi reset)"
    print ""
    print $"(ansi cyan_bold)Generated Secrets:(ansi reset)"

    for secret in ($secrets | transpose key value) {
        let name = ($secret.key | str replace "CHANGE_ME_" "" | str replace "_" " " | str downcase | str title-case)
        print $"  ($name): ($secret.value | str substring 0..8)..."
    }

    print ""
    print $"(ansi yellow)Keep this file secure! Add to .gitignore:(ansi reset)"
    print $"  echo '($output)' >> .gitignore"
}

# Generate random secret (base64)
def generate_secret [length: int] {
    openssl rand -base64 $length | str trim
}

# Generate random password (alphanumeric)
def generate_password [length: int] {
    openssl rand -base64 48 | str replace -ra '[^a-zA-Z0-9]' '' | str substring 0..$length
}
