#!/bin/bash
#
# push-repository-key -- Push repository key to all nodes
#

if [ "$#" -eq 2 ] ; then
    KEY_PATH="$1"
    KEY=$(cat $KEY_PATH)
else
    echo "No key specified, using newest stable." 1>&2
    echo "To specifiy a key, use: $0 local_gpg_key_path" 1>&2
    test -x /usr/bin/curl && URL_GET="curl -L -s" || URL_GET="wget -qO -"
    MGMT_SERVER_URL=$(grep mgmt_server_url /etc/bondingadmin/bondingadmin.conf | awk '{print $3}')
    REPO="$MGMT_SERVER_URL/download"
    STABLE_VERSIONS=$($URL_GET "$REPO/release/stable")
    LATEST_VERSION=$(echo $STABLE_VERSIONS | jq -r '.[length-1]')
    KEY_PATH="$REPO/$LATEST_VERSION/debian/public.gpg.key"
    KEY=$($URL_GET $KEY_PATH)
fi

SSH_OPTIONS="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=error"


if [ -z "$KEY" ] ; then
    echo "Could not load public key from $KEY_PATH"
    exit 1
fi

failed=''
for ip in $(/usr/bin/ba mgmt_ips) ; do
    echo -n "$ip: "
    echo -n "$KEY" | /usr/bin/ssh $SSH_OPTIONS root@$ip 'apt-key add -'
    if [ $? != 0 ] ; then
        failed="$failed $ip"
    fi
done

if [ ! -z "$failed" ] ; then
    echo "The following addresses were not updated:"
    for ip in $failed ; do
        echo "    $ip"
    done
fi
