#!/bin/bash
if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: $(basename "$0") must be run as root"
    exit 1
fi

if condor_config_val CONDOR_HOST >/dev/null 2>&1; then
    echo "CONDOR_HOST is already defined as $(condor_config_val CONDOR_HOST)"
    if [ -f /etc/condor/config.d/01-condor-host ]; then
        read -p "Do you wish to change it? [Y/n] " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Nn]$ ]]; then
            exit 1;
        fi
    else
        echo "This value was not set by the condor_join_pool script."
        echo "You must update this value manually."
        exit 1;
    fi
fi

if [ $# -eq 1 ]; then
    CONDOR_HOST=$1
else
    echo -n "Enter the hostname of the central manager: "
    read -r CONDOR_HOST
fi

echo "Checking for collector..."
if ! condor_status -total -pool "$CONDOR_HOST" >/dev/null 2>/tmp/condor_join_pool_err$$; then
    if ! grep SECMAN /tmp/condor_join_pool_err$$ | grep '"DENIED"'; then
        echo Failed to connect to "$CONDOR_HOST"
        rm /tmp/condor_join_pool_err$$
        exit 1;
    fi
fi
rm /tmp/condor_join_pool_err$$

cat > /etc/condor/config.d/01-condor-host <<EOF
# This file was generated by running $(basename "$0").
# Don't not add any other configuration values as they will be lost if
# $(basename "$0") is run again.
CONDOR_HOST=$CONDOR_HOST
EOF

echo "Setting CONDOR_HOST=$CONDOR_HOST."

echo "Restarting condor to update value of CONDOR_HOST."
systemctl restart condor

cat <<EOF

If the master, schedd, or startd fails to authenticate when trying to
advertise to the collector, they will automatically send a token request
to that collector. These two lines should appear in the daemon log:

    Collector update failed; will try to get a token request for trust domain %s, identity %s.
    Token requested; please ask collector %s admin to approve request ID %s.

The admin should run the following command on the CM as root:

    condor_token_request_approve -reqid <val>

The requesting daemon periodically polls the collector to see if its token
request has been approved, so it should pick the token automatically after
the approval.
EOF
