#!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-secret-set <yaml_key_path> <value>"
    echo ""
    echo "Set a value in \$WC_HOME/secrets.yaml using a YAML key path."
    echo ""
    echo "Examples:"
    echo "  wild-secret-set 'database.password' 'secret123'       # Set database password"
    echo "  wild-secret-set 'api.keys.github' 'ghp_token123'     # Set GitHub API key"
    echo "  wild-secret-set 'cloudflare.token' 'cf_token456'     # Set Cloudflare token"
    echo ""
    echo "Options:"
    echo "  -h, --help  Show this help message"
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            if [ -z "${KEY_PATH}" ]; then
                KEY_PATH="$1"
            elif [ -z "${VALUE}" ]; then
                VALUE="$1"
            else
                echo "Too many arguments"
                usage
                exit 1
            fi
            shift
            ;;
    esac
done

if [ -z "${KEY_PATH}" ]; then
    echo "Error: YAML key path is required"
    usage
    exit 1
fi

if [ -z "${VALUE}" ]; then
    VALUE=$(openssl rand -base64 32)
    echo "No value provided. Generated random value: ${VALUE}"
fi

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    print "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

SECRETS_FILE="${WC_HOME}/secrets.yaml"

# Create secrets file if it doesn't exist
if [ ! -f "${SECRETS_FILE}" ]; then
    echo "Creating new secrets file at ${SECRETS_FILE}"
    echo "{}" > "${SECRETS_FILE}"
    chmod 600 "${SECRETS_FILE}"  # Make secrets file readable only by owner
fi

# Use yq to set the value in the YAML file
yq eval ".${KEY_PATH} = \"${VALUE}\"" -i "${SECRETS_FILE}"

echo "Set ${KEY_PATH} = [REDACTED]"