#!/bin/bash
# Usage:    export.sh <testname> <server> [auth_token]

# Example:  export.sh test1 firely
#           export.sh test1 firely dXlBleGFtcGxlLmNvbTpzZNyZXQ=

DIRNAME=$(dirname "$0")
ROOTDIR=$(dirname "$DIRNAME")

declare -A TESTNAMES=(
    [test1]="Patient/\$everything"
    [test2]="Patient/\$everything?_count=1"

    [test3]="Patient/medmij-bgz-patient-01/\$everything" # medmij-medication-patient-01
    [test4]="Patient/medmij-bgz-patient-01/\$everything?_count=1"

    [test5]="Patient/\$export"
    [test6]="Patient/\$export?_count=1"

    [test7]="Patient/medmij-bgz-patient-01/\$export"
    [test8]="Patient/medmij-bgz-patient-01/\$export?_count=1"
)

declare -A SERVERS=(
    [hapi]="http://localhost:8100/fhir/"
    [medplum]="http://localhost:8200/fhir/R4/"
    [firely]="http://localhost:8300/"
    [microsoft]="http://localhost:8400/"
    [linuxforhealth]="https://localhost:9443/fhir/"
)

TESTNAME=$1
if [[ -z "$TESTNAME" || -z "${TESTNAMES[$TESTNAME]}" ]]; then
    echo -e "Usage:   ./export.sh \e[31m<testname>\e[0m <server> [auth_token]"
    echo -e "Geef \e[33m<testname>\e[0m op, kies uit: \e[33m${!TESTNAMES[@]}\e[0m"
    exit 1
fi

SERVER=$2
if [[ -z "$SERVER" || -z "${SERVERS[$SERVER]}" ]]; then
    echo -e "Usage:   ./export.sh <testname> \e[31m<server>\e[0m [auth_token]"
    echo -e "Geef \e[33m<server>\e[0m op, kies uit: \e[33m${!SERVERS[@]}\e[0m"
    exit 1
fi

AUTH_HEADER=""
if [[ -n "$3" ]]; then
    AUTH_HEADER="-H \"Authorization: Bearer $3\""
fi

BASE_URL=${SERVERS[$SERVER]}
HTTP_QUERY=${BASE_URL}${TESTNAMES[$TESTNAME]}
curl -k $AUTH_HEADER "${HTTP_QUERY}" -o "${ROOTDIR}/testresults/STU3/result_${TESTNAME}_${SERVER}.json" -s
echo -e "${HTTP_QUERY} -> result_${TESTNAME}_${SERVER}.json"
