#!/bin/bash
set -eu
set -o pipefail
SCRIPT_NAME=$(basename $0)
SCRIPT_HOME=$(dirname $0)

function show_options {
    echo "Usage: $SCRIPT_NAME"
    echo
    echo "Pull the latest tripleo-cd-admin ssh keys into a user account."
    echo
    echo "Assumes it is running as that user."
    echo
    echo "Options:"
    echo "    -u|--users -- Update passwords for individual user accounts"
    echo "                  instead of the root account."
    echo "    -h|--help -- This help."
    echo
    exit $1
}


TEMP=$(getopt -o hu -l help,users -n $SCRIPT_NAME -- "$@")
if [ $? != 0 ]; then
    echo "Terminating..." >&2;
    exit 1;
fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

INDIVIDUAL_USERS=

while true ; do
    case "$1" in
        -h|--help) show_options 0;;
        -u|--users) shift ; INDIVIDUAL_USERS=1;;
        --) shift ; break ;;
        *) echo "Error: unsupported option $1." ; exit 1 ;;
    esac
done

if [ -n "${1:-}" ]; then
    show_options 1
fi

cd ~
mkdir -p .ssh
chmod 0700 .ssh
mkdir -p .cache/tripleo-cd

# Get the keys
cd .cache/tripleo-cd
if [ ! -d tripleo-incubator ]; then
    git clone https://git.openstack.org/openstack/tripleo-incubator
    cd tripleo-incubator
else
    cd tripleo-incubator
    git pull
fi
TMP_SSH_KEYS=$(mktemp)
for FILE in tripleo-cloud/ssh-keys/*; do
    if [ -n "$INDIVIDUAL_USERS" ]; then
        USER=$(basename $FILE)
        if ! getent passwd $USER &>/dev/null; then
            useradd --create-home --user-group $USER
        fi
        eval mkdir -p ~$USER/.ssh
        eval chown -R $USER:$USER ~$USER/.ssh
        eval chmod 700 ~$USER/.ssh
        eval cp -f $FILE ~$USER/.ssh/authorized_keys
        eval chmod 600 ~$USER/.ssh/authorized_keys
        touch /etc/sudoers.d/$USER
        chmod 0440 /etc/sudoers.d/$USER
        echo "$USER ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$USER
    else
        cat $FILE >> $TMP_SSH_KEYS
    fi
done

if [ -z "$INDIVIDUAL_USERS" ]; then
    # Allow tripleo-incubator stuff that wants to add local keys...
    # they'll get wiped on the next run (and obviously aren't relevant for bm
    # access).
    chmod 0600 $TMP_SSH_KEYS
    mv $TMP_SSH_KEYS ~/.ssh/authorized_keys
else
    # in individual users mode lets... lets check sudo syntax
    visudo -c -q
    rm $TMP_SSH_KEYS
fi
