#!/bin/bash


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

# Ensure we are in the source directory.
cd $(dirname $1)/..

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

# Handle usage
if [ "$taskfile" == "-h" ] || [ "$taskfile" == "--help" ]; then
    echo "Usage: $0 -h"
    echo "       $0 \$taskfile \$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 Kapisi checkout"
        exit 3
    fi
done

# Get the targetgroup
targetgroup="$2"
if [ -z "$targetgroup" ]; then
    targetgroup="$taskfile" # Deploy a taskfile 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-taskfile playbook for the taskfile on the targetgroup
ansible-playbook -i "$inventory" -e "taskfile=$taskfile" -e "targets=$targetgroup" "$(dirname $0)/../playbooks/one-taskfile.yml"
# and return the exit status
exit $?
