#!/usr/bin/env bash
# SLangroom-EXec Format Encoder
# This script is used to encode the format of the slangroom-exec command
# into a string that can be used in the slangroom-exec command

print_help() {
    printf "\033[1mUsage:\033[0m"
    printf "  $0 [options]\n"
    printf "\033[1mOptions:\033[0m\n"
    printf "  -c conf               conf filename to read\n"
    printf "  -s slangroom-contract slangroom-contract filename to read\n"
    printf "  -d data               data filename to read\n"
    printf "  -k keys               keys filename to read\n"
    printf "  -e extra              extra filename to read\n"
    printf "  -x context            context filename to read\n"
    printf "  -F filename           lookup files based on a prefix\n"
    printf "  -h                    Print this help message\n"
    printf "\nEncode the parameters into a base64 string.\n"
    exit 1
}

# Function to encode to base64
encode_base64() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        cat "$1" 2>/dev/null | base64
    else
        cat "$1" 2>/dev/null | base64 -w 0
    fi
}

encode_json_base64() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        jq -c . "$1" 2>/dev/null | base64
    else
        jq -c . "$1" 2>/dev/null | base64 -w 0
    fi
}

# check that jq and getopt are installed

if ! command -v jq &> /dev/null; then
    printf "jq is not installed. Please install jq to use this script."
    exit 1
fi

if ! command -v getopt &> /dev/null; then
    printf "getopt is not installed. Please install getopt to use this script."
    exit 1
fi

# Default values for options
conf=""
slangroom_contract=""
data=""
keys=""
extra=""
context=""

while getopts "c:s:d:k:e:x:F:h" opt; do
    case ${opt} in
        c)
            conf=$(encode_base64 "${OPTARG}");;
        s)
            slangroom_contract=$(encode_base64 "${OPTARG}");;
        d)
            data=$(encode_json_base64 "${OPTARG}");;
        k)
            keys=$(encode_json_base64 "${OPTARG}");;
        e)
            extra=$(encode_json_base64 "${OPTARG}");;
        x)
            context=$(encode_base64 "${OPTARG}");;
        F)
            conf=$(encode_base64 "${OPTARG}.conf")
            slangroom_contract=$(encode_base64 "${OPTARG}.slang")
            data=$(encode_json_base64 "${OPTARG}.data.json")
            keys=$(encode_json_base64 "${OPTARG}.keys.json")
            extra=$(encode_json_base64 "${OPTARG}.extra.json")
            context=$(encode_base64 "${OPTARG}.context");;
        h)
            print_help ;;
        \?)
            printf "Invalid option: -${OPTARG}" >&2
            exit 1 ;;
        :)
            printf "Option -${OPTARG} requires an argument." >&2
            exit 1 ;;
    esac
done
shift $((OPTIND -1))


# if slangroom-contract is empty, read it from stdin
if [ -z "$slangroom_contract" ]; then
    slangroom_contract=$(encode_base64 -)
fi

# Print the encoded string
printf "${conf}\n${slangroom_contract}\n${data}\n${keys}\n${extra}\n${context}"

