#!/bin/bash

set -o pipefail -u -e

ACTIVITIES="team-probing fireball"

usage() {
    echo "Usage: $0 [--dry-run] <activity>"
    echo
    echo "Download scamper configuration for an ark activity."
    echo "Valid activities: $ACTIVITIES"
}

reload_service() {
    if [ -d /run/systemd/system ]; then
        systemctl try-reload-or-restart "$1"
    else
        if sv status "/etc/service/$1" | grep -q "^run:"; then
            sv reload "/etc/service/$1" > /dev/null;
        fi
    fi
}

dryrun=0
while [ "$#" -gt 0 ]; do
    case $1 in
        --dry-run|--dryrun|-n)
            dryrun=1
            shift
            ;;
        --)
            shift
            break
            ;;
        -*)
            echo "Unknown option: $1"
            usage
            exit 2
            ;;
        *)
            break
            ;;
    esac
done

activity=${1:-}
if [ -z "$activity" ]; then
    echo "Missing activity"
    usage
    exit 2
fi

if [ -e /etc/ark/monitor-config ]; then
    . /etc/ark/monitor-config
fi


# check activity is valid
if echo "$ACTIVITIES" | grep -v -q --word-regexp -- "$activity"; then
    echo "Unknown activity: $activity"
    usage
    exit 1
fi

# only fetch config for installed activities
if ! dpkg -l "ark-activity-$activity" 2>/dev/null | grep ^ii > /dev/null; then
    echo "Activity not installed: $activity"
    exit 1
fi

# try to fetch node-specific config from the caida config server
url="https://ca.ark.caida.org/activity/${activity}"
config=$(curl \
        --cert "/etc/ark/ssl/${ARK_MONITOR}.ark.caida.org.crt" \
        --key "/etc/ark/ssl/${ARK_MONITOR}.ark.caida.org.key" \
        --fail \
        --silent \
        --show-error \
        "$url") || true

if [ -z "$config" ]; then
    echo "Ignoring zero length config for $activity"
    exit 1
fi

# check if the new config is different to the old one, and replace it
conffile="/etc/ark/activity-${activity}/scamper-config"
if [ ! -e "$conffile" ] || ! diff -u "$conffile" <(echo "$config"); then
    if [ "$dryrun" -eq 0 ]; then
        # TODO validate the config in any way?
        install -D -o ark -g ark -m 644 <(echo "$config") "$conffile"

        # reload systemd or runit service to get the new config
        case "$activity" in
            "fireball")
                reload_service "ark-activity-$activity"
                ;;
            *)
                # service doesn't need a reload/restart
                ;;
        esac
    fi
fi
