#!/bin/bash

# installs codeql in $1

set -e
MYDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

INSTALL_DIR=$1

if [[ -z "$INSTALL_DIR" ]]; then
    echo "Missing an argument.
Usage: $0 directory-to-install-codeql-in" >&2
   exit 1
fi

function abspath() { pushd . > /dev/null; if [ -d "$1" ]; then cd "$1"; dirs -l +0; else cd "`dirname \"$1\"`"; cur_dir=`dirs -l +0`; if [ "$cur_dir" == "/" ]; then echo "$cur_dir`basename \"$1\"`"; else echo "$cur_dir/`basename \"$1\"`"; fi; fi; popd > /dev/null; }
INSTALL_DIR=$(abspath "$INSTALL_DIR")

mkdir -p "${INSTALL_DIR}"
TMP=$(mktemp -d codeql-download-XXXX)
BUNDLE=/bundle.tar.gz

cd $TMP
NAME=codeql-bundle.tar.gz
curl -LO "https://github.com/github/codeql-action/releases/latest/download/${NAME}"
tar xvf "${NAME}" -C "${INSTALL_DIR}" > /dev/null

BIN="${INSTALL_DIR}/codeql/codeql"
if [ ! -f "${BIN}" ]; then
    echo "ERROR: The download and extraction of codeql completed successfully, but ${BIN} does not exist?!">&2
    exit 1
fi
if [ ! -x "${BIN}" ]; then
    echo "ERROR: The download and extraction of codeql completed successfully, but ${BIN} is not executable?! ">&2
    exit 1
fi

MAIN="${MYDIR}/../../../../build/ts/contrib/tools/codeql/src/codeql.js"
MAIN=$(abspath "$MAIN")
echo "The codeql tool has been installed. Add the fragment below to a config.json file:

{
    ...
    \"tools\": {
        ...

        \"codeql-default\": {
            \"bin\": \"node\",
            \"args\": [
                \"${MAIN}\"
            ],
            \"options\": {
              \"codeql\": \"${BIN}\"
            }

        }

        ...
    }
    ...
}

"
