#!/usr/bin/env bash
# Checked with ShellCheck (https://www.shellcheck.net/)

#/ Generate API client module for the current project.
#/
#/ Generates client code from Kurento API definition files (.kmd).



# Configure shell
# ===============

SELF_DIR="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null && pwd -P)"
source "$SELF_DIR/bash.conf.sh" || exit 1

log "==================== BEGIN ===================="
trap_add 'log "==================== END ===================="' EXIT

# Trace all commands (to stderr).
set -o xtrace



# Check dependencies
# ==================

command -v jq >/dev/null || {
    log "ERROR: 'jq' is not installed; please install it"
    exit 1
}



# Parse call arguments
# ====================

CFG_RELEASE="false"
CFG_GIT_SSH_KEY_PATH=""

while [[ $# -gt 0 ]]; do
    case "${1-}" in
        --release)
            CFG_RELEASE="true"
            ;;
        --git-ssh-key)
            if [[ -n "${2-}" ]]; then
                CFG_GIT_SSH_KEY_PATH="$(realpath "$2")"
                shift
            else
                log "ERROR: --git-ssh-key expects <Path>"
                exit 1
            fi
            ;;
        *)
            log "ERROR: Unknown argument '${1-}'"
            exit 1
            ;;
    esac
    shift
done



# Validate config
# ===============

log "CFG_RELEASE=$CFG_RELEASE"
log "CFG_GIT_SSH_KEY_PATH=$CFG_GIT_SSH_KEY_PATH"


# Generate client code
# ====================

rm -rf build/
mkdir build/
cd build/

cmake -DGENERATE_JS_CLIENT_PROJECT=TRUE -DDISABLE_LIBRARIES_GENERATION=TRUE ..

cd js || {
  log "ERROR: Expected directory doesn't exist: $PWD/js"
  exit 1
}

# When generating from kurento-module-filters, the JSON keys in
# `src/filters.kmd.json` change ordering each time this job runs, which pollutes
# git logs with meaningless variations in key order.
# I haven't found the cause for this issue, and it is really a time sink without
# much payoff, so the easy way is to enforce a sorting order right here.
for FILE in src/*.kmd.json; do
    jq '.remoteClasses? |= sort_by(.name)' "$FILE" >"$FILE.tmp"
    mv "$FILE.tmp" "$FILE"
done



# Commit client code
# ==================

if [[ -n "${CFG_GIT_SSH_KEY_PATH:-}" ]]; then
    # SSH is hardcoded to assume that the current UID is an already existing
    # system user. This was common in the past but not any more with containers.
    # Using the NSS wrapper library we can trick SSH into working with any UID.
    echo "kurento:x:$(id -u):$(id -g)::/home/kurento:/usr/sbin/nologin" >"/tmp/passwd"
    echo "kurento:x:$(id -g):" >"/tmp/group"
    # https://git-scm.com/docs/git#Documentation/git.txt-codeGITSSHCOMMANDcode
    export GIT_SSH_COMMAND="LD_PRELOAD=libnss_wrapper.so NSS_WRAPPER_PASSWD=/tmp/passwd NSS_WRAPPER_GROUP=/tmp/group ssh -i $CFG_GIT_SSH_KEY_PATH -o IdentitiesOnly=yes -o StrictHostKeychecking=no"
fi

PROJECT_NAME="$(get_name.sh)"
PROJECT_VERSION="$(get_version.sh)"

REPO_NAME="$PROJECT_NAME-js"
REPO_URL="git@github.com:Kurento/$REPO_NAME.git"
REPO_DIR="$(mktemp --directory)"

git clone --depth 1 "$REPO_URL" "$REPO_DIR"

rsync -av --delete \
    --exclude='.git*' \
    ./ "$REPO_DIR"/

log "Commit and push changes to Kurento/$REPO_NAME"

{
    pushd "$REPO_DIR"

    # Check if there are any changes; if so, commit them.
    git update-index -q --refresh
    if ! git diff-index --quiet --exit-code HEAD; then
        # `--all` to include possibly deleted files.
        git add --all .

        git commit -m "Code autogenerated from Kurento/kurento@$GIT_HASH_SHORT"

        git push
    fi

    # If release, create an annotated tag.
    if [[ "$CFG_RELEASE" == "true" ]]; then
        # --force: Replace tag if it exists (instead of failing).
        # This is done so it becomes possible to re-issue release builds.
        git tag --force --annotate -m "$PROJECT_VERSION" "$PROJECT_VERSION"
        git push --force origin "$PROJECT_VERSION"
    fi

    popd  # $REPO_DIR
}
