#!/bin/bash

B=
R=
Y=
N=
if [[ $- != *x* ]] && [[ -t 0 ]]; then
	B=$'\033[1m'
	R=$'\033[31m'
	Y=$'\033[33m'
	N=$'\033[0m'
fi


declare -A FLAGS
FLAGS=(
        [DRYRUN]=0
)

# Display an optional error, the usage text and then exit
function usage {
local STATUS="$1"
local ERROR="$2"
if [[ -n "$STATUS" && -z "$ERROR" ]]; then
                ERROR="$STATUS"
                STATUS=
fi

cat <<-EOD
        ${ERROR:+${B}${R}ERROR:${N}${B} ${ERROR}${N}}
        ${B}USAGE:${N} $(basename "$0") [options] <version> <project> <username>

        ${B}ARGUMENTS${N}

            ${N}<project>${B}	    := Repository project name (e.g. xxx-forms)

            ${N}<version>${B}       := Code version (e.g. 20180618T070646Z)

            ${N}<username>${B}      := Username (e.g. noggin-xxxx) for authentication to repository

       ${B}OPTIONS${N}

            ${B}--repo-url${N} The target repository URL (defaults to https://api.bitbucket.org/2.0/repositories/noggin-ondemand)

            ${B}--dry-run${N}   Just show what would be done, do not actually apply any changes to the system


EOD
[ -n "$STATUS" ] && exit $STATUS
[ -n "$ERROR"  ] && exit 1
exit 0
}


# Parse argument flags
while [ "${1:0:2}" ==  "--" ]; do
        case "$1" in
                --repo-url)
                        # Modify RepoPath
			shift
			REPOURL="$1"
                        ;;

                --dry-run)
                        FLAGS[DRYRUN]=1
                        ;;

                --help|--usage)
                        usage
                        ;;

                --)
                        # End of arguments, exit the loop
                        shift;
                        break;
                        ;;

                --*)
                        # Unknown flag
                        usage "Unknown flag '$1' (use -- to terminate flags?)"
                        ;;
        esac
        shift
done

PROJECT="$1"
VERSION="$2"
USERNAME="$3"
PROJECTDIR=$(getent passwd $USER | cut -d: -f6)
CODEDIR="${PROJECTDIR}/code"

[[ $# -lt 3 ]] && usage "Too few arguments passed"
[[ $# -gt 3 ]] && usage "Too many arguments passed"
[[ $(id -u) -eq 0 ]] && usage "This script must be run as the nif_xxx user (not root)"
! [[ -d ${PROJECTDIR} ]] && usage "${PROJECTDIR} does not exist"
! [[ -d ${CODEDIR} ]] && usage "${CODEDIR} does not exist"
[[ -z ${REPOURL} ]] && REPOURL="https://api.bitbucket.org/2.0/repositories/noggin-ondemand"

REPOPATH="${REPOURL}/${PROJECT}/downloads/${PROJECT}."

if [ ${FLAGS[DRYRUN]} -eq 1 ]; then
        echo -e "\\n${B}# Changing to project code directory (dry-run)${N}"
        echo "pushd ${CODEDIR}"

        echo -e "\\n${B}# Downloading code from (dry-run)${N}"
        echo "curl -L -O -u ${USERNAME} ${REPOPATH}${VERSION}.tar.gz"

        echo -e "\\n${B}# Extracting downloaded tarball (dry-run)${N}"
        echo "tar xzf ${PROJECT}.${VERSION}.tar.gz"
        echo "rm -f ${PROJECT}.${VERSION}.tar.gz"

        echo -e "\\n${B}# Setting permissions with canned script (dry-run)${N}"
        echo "/usr/bin/nif-setperms-secure ${PROJECTDIR}"

        echo -e "\\n${B}# Exiting project code directory (dry-run)${N}"
        echo -e "popd\n"

	exit 0
fi

# Goto code directory
pushd "${CODEDIR}" >/dev/null

# Validate we don't already have this version
[[ -d ${PROJECT}.${VERSION} ]] && popd && usage "Version already installed: ${VERSION}"

# Get the file
echo -e "${B}# Enter your password for ${USERNAME} authentication to ${REPOPATH}${VERSION}.tar.gz ${N}"
curl -L -O -u ${USERNAME} ${REPOPATH}${VERSION}.tar.gz

# If the file doesn't exist then the download probably didn't exist
# NOTE: we can't just check the curl exit code because HTTP error codes are not returned to the posix exit code)
! [[ -f ${PROJECT}.${VERSION}.tar.gz ]] && popd >/dev/null && echo "${R}ERR: Target file was not downloaded succesfully (bad auth or wrong URL??)${N}" && exit 1

# Munge tarball
tar xzf ${PROJECT}.${VERSION}.tar.gz
rm -f ${PROJECT}.${VERSION}.tar.gz

# Set perms
/usr/bin/nif-setperms-secure "${PROJECTDIR}"

# Exit code directory
popd >/dev/null
