#!/bin/bash
# -----------------------------------------------------------------------------
# Secures the ONOS console for all instances in the cell ONOS cluster.
# -----------------------------------------------------------------------------

[ ! -d "$ONOS_ROOT" ] && echo "ONOS_ROOT is not defined" >&2 && exit 1
. $ONOS_ROOT/tools/build/envDefaults

# Scan arguments for user/password or other options...
while getopts u:p: o; do
    case "$o" in
        u) user=$OPTARG;;
        p) password=$OPTARG;;
    esac
done
password=${password:-$user} # password defaults to the user if not specified
let OPC=$OPTIND-1
shift $OPC

user=${user:-$ONOS_WEB_USER}
password=${password:-$ONOS_WEB_PASS}
nodes=${1:-$(env | sort | egrep "^OC[0-9]+" | cut -d= -f2)}

# ensure known_hosts file exist
(umask 077; touch "$HOME/.ssh/known_hosts")
set -x
for node in $nodes; do
    # Setup passwordless login for the local user on the remote node
    ssh $ONOS_USER@$node "
        set -x
        [ ! -f ~/.ssh/id_rsa.pub ] && ssh-keygen -t rsa -f ~/.ssh/id_rsa -P '' -q
        $ONOS_INSTALL_DIR/bin/onos-user-key \$(id -un) \$(cut -d\\  -f2 ~/.ssh/id_rsa.pub)
        $ONOS_INSTALL_DIR/bin/onos-user-password $user $password

        # Implicitly accept the new server key in dev/test environments
        while ! ssh -p 8101 -o StrictHostKeyChecking=no localhost list 2>/dev/null; do
            echo Waiting for connection...
            sleep 1
        done
    "

    # Setup passwordless login for the remote user on the local bench host
    # For now, we let the local public key override the remote one
    # TODO: fix username collision between workbench and the remote hosts
    onos-user-key $node
done
