#!/bin/bash

# Script to get the complete configuration backup archive.
#
# Must pass the path of the file were to save the backup as first argument.
#
# NOTE: the request is done via the HTTP endpoint instead of directly to
# avoid races with any concurrent configuration commands, the HTTP endpoints
# are all single process so no concurrency is possible.
#

TOKEN_FILE=
TOKEN=
OUTPUT_FILE=

function cleanup() {
    [ -z "$TOKEN_FILE" ] || rm -f "$TOKEN_FILE"
}
trap cleanup EXIT

OUTPUT_FILE="$1"
if [ -z "$OUTPUT_FILE" ]; then
    echo "ERROR: must specify the output file as first argument" >&2
    exit 1
fi

TOKEN="$(< /proc/sys/kernel/random/uuid)"
if [ -z "$TOKEN" ]; then
    echo "ERROR: failed generating temporary token" >&2
    exit 1
fi
TOKEN_FILE=/var/run/spxmanage/www-auth/admin_auth-"$TOKEN"

if ! touch "$TOKEN_FILE"; then
    echo "ERROR: failed registering the temporary token" >&2
    exit 1
fi

# Pass the bearer token via stdin so that it does not appear in the command line
curl --disable --fail --show-error --max-time 30 --silent -o "$OUTPUT_FILE" -K - http://localhost/getconfig <<EOF
header "Authorization: Bearer $TOKEN"
EOF

if [ $? -ne 0 ]; then
    rm -f "$OUTPUT_FILE"
    echo "ERROR: failed getting the configuration" >&2
    exit 1
fi

# The configuration must be a valid 7-Zip archive
if ! 7za t -t7z "$OUTPUT_FILE" > /dev/null; then
    rm -f "$OUTPUT_FILE"
    echo "ERROR: configuration backup is corrupted or has unexpected format" >&2
    exit 1
fi
