#!/bin/bash

# Fail out if anything fails.
set -e

SYMCRYPT_REPO='https://github.com/microsoft/SymCrypt.git'
SYMCRYPT_DIR='./SymCrypt'

CURRENT_DIR=$(pwd)
RELEASE_TAG=

function show_help() {
    echo "Usage: $0 [--release-tag <tag>]"
    echo
    echo "Options:"
    echo "  --release-tag <tag>  The release tag to use for the build, e.g.: v103.5.1"
    echo "  --debug              Enable debug output, which is just 'set -x'"
    echo "  --help               Display this help message"
    echo
    echo "Generates a sourceable script file that sets git-related environment variables for the SymCrypt build."
    echo "The script file will be named 'symcrypt-build-environment-variables-<release-tag>.sh"
}

while [[ "$#" -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -t|--tag|--release-tag)
            RELEASE_TAG="$2"
            shift
            ;;
        -d|--debug)
            set -x
            ;;
        *)
            echo "Unknown parameter passed: $1"
            exit 1
            ;;
    esac
    shift
done

if [ -z "${RELEASE_TAG}" ]; then
    echo "release tag is required" >> /dev/stderr
    show_help
    exit 1
fi

echo "generating env file for release tag: '${RELEASE_TAG}'"

# Create a temporary directory to clone the git repo
TEMP_DIR=$(mktemp -d)
if [[ ! "$TEMP_DIR" || ! -d "$TEMP_DIR" ]]; then
    echo "Could not create temp dir to clone git repo" >> /dev/stderr
    exit 1
fi

# Clone into the temp directory
pushd "${TEMP_DIR}" > /dev/null
echo "Cloning SymCrypt repo '${SYMCRYPT_REPO}' into temp directory '${TEMP_DIR}"
git clone "${SYMCRYPT_REPO}"

# The version script uses the current git branch, which want to main but at the commit for the release tag.
echo "Getting to the commit for release tag '${RELEASE_TAG}'"
cd "${SYMCRYPT_DIR}"
TAG_COMMIT=$(git rev-parse --verify "${RELEASE_TAG}")
if [[ ! "$TAG_COMMIT" ]]; then
    echo "Could not find commit for release tag '${RELEASE_TAG}'"
    exit 1
fi
echo "Tag commit is '${TAG_COMMIT}'"
git reset --hard "${TAG_COMMIT}"

# Call the version script to get the properly formmatted git info
ENV_SCRIPT_FILE_NAME="symcrypt-build-environment-variables-${RELEASE_TAG}.sh"
echo "#!/bin/bash" > "${CURRENT_DIR}/${ENV_SCRIPT_FILE_NAME}"
echo "# Generated by 'generate-env-file.sh'" >> "${CURRENT_DIR}/${ENV_SCRIPT_FILE_NAME}"
echo "Running version script"
python3 scripts/version.py --no-print-version-number --commit-info >> "${CURRENT_DIR}/${ENV_SCRIPT_FILE_NAME}"
echo "Generated '${ENV_SCRIPT_FILE_NAME}'"

# Clean up the temp directory
popd > /dev/null
rm -rf "${TEMP_DIR}"
