#!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-compile-template [options]"
    echo ""
    echo "Compile a gomplate template from stdin using \$WC_HOME/config.yaml as context."
    echo ""
    echo "Examples:"
    echo "  echo 'Hello {{.config.cluster.name}}' | wild-compile-template"
    echo "  cat template.yml | wild-compile-template"
    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
            ;;
        *)
            echo "Too many arguments"
            usage
            exit 1
            ;;
    esac
done

# Check if WC_HOME is set
if [ -z "${WC_HOME:-}" ]; then
    echo "Error: WC_HOME environment variable not set" >&2
    exit 1
fi

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

if [ ! -f "${CONFIG_FILE}" ]; then
    echo "Error: config.yaml not found at ${CONFIG_FILE}" >&2
    exit 1
fi

# Build gomplate command with config context
gomplate_cmd="gomplate -c .=${CONFIG_FILE}"

# Add secrets context if secrets.yaml exists (enables .secrets shorthand)
if [ -f "${SECRETS_FILE}" ]; then
    gomplate_cmd="${gomplate_cmd} -c secrets=${SECRETS_FILE}"
fi

# Execute gomplate with stdin
${gomplate_cmd}