#!/bin/bash

# Role is first argument
role="$1"
if [ -z "$role" ]; then
    echo Need a role as first argument.
    exit 1
fi

# Handle verbosity
if [ "$1" == "-v" ]; then
    set -x
    shift
    role="$1"
fi

# Handle usage
if [ "$role" == "-h" ] || [ "$role" == "--help" ]; then
    echo "Usage: $0 -h"
    echo "       $0 \$role \$targetgroup [\$optional_inventory]"
    exit 0
fi

# Find the root of the git clone
while [ ! -d .git ]; do
    cd ..
    if [ "$PWD" == '/' ]; then
        echo "This needs to be run from the Ubiqtorate checkout"
        exit 3
    fi
done

# Get the targetgroup
targetgroup="$2"
if [ -z "$targetgroup" ]; then
    targetgroup="$role" # Deploy a role to the server named for that function
fi

# Allow an inventory override
inventory="$3"
if [ -z "$inventory" ]; then
    inventory=examples/msn0.yml
fi

# Invoke the one-role playbook for the role on the targetgroup
ansible-playbook -i "$inventory" -e "role=$role" -e "targets=$targetgroup" playbooks/one-role.yml
# and return the exit status
exit $?