#/bin/bash

function chkerr {
	if [ $1 -ne 0 ]; then
		echo "Error: $2"
		exit 2
	fi
}

if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ]; then
    echo "Usage: <workdir> <host> <code> <sdm data dir>"
    echo "  Workdir: used for temporary storage during download"
    echo "  Host: The host (and port) where SEB is available"
    echo "  Code: The API key/code that should be used for authentication"
    echo "  SDM Data dir: The inbox of the SEB Importer (or it's preflight equivalent)"
    exit 1
fi

WORKDIR=$1
# sebuseradmin-function-nsp-test.azurewebsites.net
HOST=$2
# a3oswyv4Up9n1CqdhpYuoH2ZQuRwqa9XAiBtKmLh804InXJKZL7awA==
CODE=$3

TARGET=$4

if [ ! -d ${WORKDIR} ]; then
    echo "${WORKDIR} not found or not a directory"
    exit 1
fi
if [ ! -w ${WORKDIR} ]; then
    echo "${WORKDIR} not writeable by `whoami`"
    exit 1
fi

if [ ! -d ${TARGET} ]; then
    echo "${WORKDIR} not found or not a directory"
    exit 1
fi
if [ ! -w ${TARGET} ]; then
    echo "${WORKDIR} not writeable by `whoami`"
    exit 1
fi

TIMESTAMP=`date +%Y%m%d%H%M%S`
DATADIR="SEBRoles-${TIMESTAMP}"

echo "${TIMESTAMP}: Pulling SEB data from ${HOST} into ${WORKDIR}"

mkdir ${WORKDIR}/${DATADIR}
chkerr $? "Could not create temporary download directory ${WORKDIR}/${DATADIR}"

curl "https://${HOST}/api/UsersWithRoles?code=${CODE}" -H 'Accept: application/xml' > ${WORKDIR}/${DATADIR}/${TIMESTAMP}.xml
chkerr $? "An error occured download from ${HOST} using the code ${CODE}. - Manual cleanup of ${WORKDIR}/${DATADIR} is needed"

mv ${WORKDIR}/${DATADIR} ${TARGET}/
chkerr $? "Could not move the incomming data to ${TARGET}/ - Manual cleanup of ${WORKDIR}/${DATADIR} is needed"

echo "Done"