#!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-secret [--check] <yaml_key_path>"
    echo ""
    echo "Read a value from ./secrets.yaml using a YAML key path."
    echo ""
    echo "Examples:"
    echo "  wild-secret 'database.password'      # Get database password"
    echo "  wild-secret 'api.keys.github'        # Get GitHub API key"
    echo "  wild-secret 'credentials[0].token'   # Get first credential token"
    echo "  wild-secret --check 'api.keys.github' # Exit 1 if key doesn't exist"
    echo ""
    echo "Options:"
    echo "  --check     Exit 1 if key doesn't exist (no output)"
    echo "  -h, --help  Show this help message"
}

# Parse arguments
CHECK_MODE=false
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        --check)
            CHECK_MODE=true
            shift
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            if [ -z "${KEY_PATH}" ]; then
                KEY_PATH="$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

# 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"

if [ ! -f "${SECRETS_FILE}" ]; then
    if [ "${CHECK_MODE}" = true ]; then
        exit 1
    fi
    echo "Error: secrets file not found at ${SECRETS_FILE}" >&2
    echo ""
    exit 0
fi

# Use yq to extract the value from the YAML file
result=$(yq eval ".${KEY_PATH}" "${SECRETS_FILE}" 2>/dev/null || echo "null")

# Check if result is null (key not found)
if [ "${result}" = "null" ]; then
    if [ "${CHECK_MODE}" = true ]; then
        exit 1
    fi
    echo "Error: Key path '${KEY_PATH}' not found in ${SECRETS_FILE}" >&2
    echo ""
    exit 0
fi

# In check mode, exit 0 if key exists (don't output value)
if [ "${CHECK_MODE}" = true ]; then
    exit 0
fi

echo "${result}"