#!/usr/bin/env bash

# The inputs to this script are:
#
#   1.[LAUNCHERS_DIR]
#

# get arguments
LAUNCHERS_DIR=$1
INSTALL_DIR=/usr/local/bin

# check LAUNCHERS_DIR
if [[ ! -d ${LAUNCHERS_DIR} ]]; then
    echo >&2 "ERROR: The path ${LAUNCHERS_DIR} does not exists or it is not a directory"
    exit 1
fi

# create destination if it does not exist
mkdir -p ${INSTALL_DIR}

# install launchers
n=0
for filepath in "${LAUNCHERS_DIR}"/*; do
    base=$(basename "${filepath}")
    filename=${base%.*}
    destination="${INSTALL_DIR}/launcher-${filename}"
    # remove overlapping link (if any)
    rm -f "${destination}"
    # create a link to the launcher
    ln -s "${filepath}" "${destination}"
    if [[ ! -x "${filepath}" ]]; then
        # the launcher is not executable, check if it has a shebang
        if [[ "$(head -c 2 "${filepath}")" == "#!" ]]; then
            chmod +x "${destination}"
        else
            echo >&2 "ERROR: The launcher '${filename}' is not executable and does not have a shebang"
            exit 2
        fi
    fi
    ((n++))
done

# everything should be OK
echo "DONE: Installed ${n} launchers!"
