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

# Example:  chmod 755 import.sh
#           apt install libxml2-utils
#           import.sh hapi
#           import.sh hapi 12345
#           https://www.hl7.org/fhir/http.html

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

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/"
)

SERVER=$1
if [[ -z "$SERVER" || -z "${SERVERS[$SERVER]}" ]]; then
    echo -e "Usage:   ./import.sh \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

BASE_URL=${SERVERS[$SERVER]}
AUTH_HEADER=""
if [[ -n "$2" ]]; then
    AUTH_HEADER="-H \"Authorization: Bearer $2\""
fi

file_count=0
files=$(find $ROOTDIR/testdata/STU3/ -type f -name "*.xml")
echo "$files" | while read -r file; do
    ((file_count++))

    RESOURCE_TYPE=$(xmllint --xpath 'name(/*)' "$file")    
    RESOURCE_ID=$(xmllint --xpath 'string(//*[local-name()="id"]/@value)' "$file")
    RESOURCE_URI=$BASE_URL$RESOURCE_TYPE/$RESOURCE_ID # http://localhost:8100/fhir/DiagnosticReport/medmij-bgz-laboratorytestresult-diagnosticreport-01
    # RESOURCE_BODY=$(tail -n +2 "$file" | sed 's/"/\\"/g')
    # RESOURCE_BODY=$(sed '1d' "$file" | sed 's/"/\\"/g')
    # RESOURCE_BODY=$(sed '0,/^<?xml /d' "$file" | sed 's/"/\\"/g') # <?xml-model />, <?xml />
    RESOURCE_BODY=$(sed 's/"/\\"/g' "$file")
    REQUEST="curl -s -o /dev/null -w \"%{http_code}\" -k -X PUT -H \"Content-Type: application/xml\" $AUTH_HEADER -d \"$RESOURCE_BODY\" \"$RESOURCE_URI\""
    RESPONSE=$(eval $REQUEST)

    if [[ "$RESPONSE" =~ ^2 ]]; then
        printf "%2d (OK)| %s\n" "$file_count" "$file"
    else
        printf "%2d (HTTP $RESPONSE)| %s\n" "$file_count" "$file"
        echo
        echo "Probeer eens: curl -k -X PUT -H \"Content-Type: application/xml\" $AUTH_HEADER -d \"$RESOURCE_BODY\" \"$RESOURCE_URI\""
        echo
        read -p "Doorgaan?"
        # exit
    fi
done
