#!/bin/bash

fetch () {
    local src=$1 dst=$2
    local tmp=$2.tmp
    local ret

    if [[ ! -d $(dirname "$dst") ]]; then
        echo >&2 "Destination directory does not exist"
        return 1
    fi
    rm -f "$tmp"
    wget "$src" -q --content-on-error -O "$tmp"; ret=$?
    if [[ $ret != 0 ]]; then
        echo >&2 "Error fetching $src"
        if [[ -s $tmp ]]; then
            echo >&2 "File contents:"
            cat >&2 "$tmp"
        fi
        return 1
    else
        mv -f "$tmp" "$dst"
    fi
}

die_with_usage () {
    echo >&2 "Usage: $(basename "$0") --cache|--origin"
    echo >&2 "Environment variables used:"
    echo >&2 "CACHE_FQDN        FQDN used for cache authfile query (default `hostname -f`)"
    echo >&2 "ORIGIN_FQDN       FQDN used for origin authfile query (default `hostname -f`)"
    echo >&2 "TOPOLOGY          Topology server to get the data from (default https://topology.opensciencegrid.org)"
    exit 2
}

if [[ $# -ne 1 ]]; then
    die_with_usage
fi

TOPOLOGY=${TOPOLOGY:-https://topology.opensciencegrid.org}

if [[ $1 == --cache ]]; then
    CACHE_FQDN=${CACHE_FQDN:-$(hostname -f)}
    ret=0
    fetch "${TOPOLOGY}/stashcache/authfile?cache_fqdn=${CACHE_FQDN}"        /run/stash-cache-auth/Authfile
    ret=$(( $ret | $? ))
    fetch "${TOPOLOGY}/stashcache/authfile-public?cache_fqdn=${CACHE_FQDN}" /run/stash-cache/Authfile
    ret=$(( $ret | $? ))
    fetch "${TOPOLOGY}/stashcache/scitokens?cache_fqdn=${CACHE_FQDN}"        /run/stash-cache-auth/scitokens.conf
    ret=$(( $ret | $? ))
    exit $ret
elif [[ $1 == --origin ]]; then
    ORIGIN_FQDN=${ORIGIN_FQDN:-$(hostname -f)}
    ret=0
    fetch "${TOPOLOGY}/stashcache/origin-authfile?fqdn=${ORIGIN_FQDN}"        /run/stash-origin-auth/Authfile
    ret=$(( $ret | $? ))
    fetch "${TOPOLOGY}/stashcache/origin-authfile-public?fqdn=${ORIGIN_FQDN}" /run/stash-origin/Authfile
    ret=$(( $ret | $? ))
    fetch "${TOPOLOGY}/stashcache/scitokens?origin_fqdn=${ORIGIN_FQDN}"        /run/stash-origin-auth/scitokens.conf
    ret=$(( $ret | $? ))
    exit $ret
else
    die_with_usage
fi

