#!/usr/bin/env bash
set -e

# Thank you composer for figuring this out!
selfArg="$BASH_SOURCE"
if [ -z "$selfArg" ]; then
    selfArg="$0"
fi

self=$(realpath $selfArg 2> /dev/null)
if [ -z "$self" ]; then
    self="$selfArg"
fi

dir=$(cd "${self%[/\\]*}" > /dev/null; cd '../scripts' && pwd)

PATH="$dir:$PATH"
DEVSHOP_PATH=$(realpath $dir/..)

# If /path/to/devshop/ANSIBLE_PLAYBOOK exists, use that path. Otherwise pass it directly.
if [ -f "${DEVSHOP_PATH}/${ANSIBLE_PLAYBOOK}" ]; then
  ANSIBLE_PLAYBOOK="${DEVSHOP_PATH}/${ANSIBLE_PLAYBOOK}"
fi

ANSIBLE_PLAYBOOK=${ANSIBLE_PLAYBOOK:-"$DEVSHOP_PATH/roles/devshop.server/play.yml"}
ANSIBLE_CONFIG=${ANSIBLE_CONFIG:-""}
ANSIBLE_TAGS=${ANSIBLE_TAGS:-""}
ANSIBLE_SKIP_TAGS=${ANSIBLE_SKIP_TAGS:-""}
ANSIBLE_EXTRA_VARS=${ANSIBLE_EXTRA_VARS:-""}
ANSIBLE_PLAYBOOK_COMMAND_OPTIONS=${ANSIBLE_PLAYBOOK_COMMAND_OPTIONS:-}
ANSIBLE_VERBOSITY=${ANSIBLE_VERBOSITY:-"0"}

# Used for validating inventory is setup correctly. Set to match the devshop role play.yml and inventory.
DEVSHOP_ANSIBLE_GROUP_NAME=${DEVSHOP_ANSIBLE_GROUP_NAME:-"devshop_server"}

# Build options string if ENV vars exist.
if [[ -n "${ANSIBLE_TAGS}" ]]; then
  ANSIBLE_PLAYBOOK_COMMAND_OPTIONS="--tags $ANSIBLE_TAGS $ANSIBLE_PLAYBOOK_COMMAND_OPTIONS"
fi
if [[ -n "${ANSIBLE_SKIP_TAGS}" ]]; then
  ANSIBLE_PLAYBOOK_COMMAND_OPTIONS="--skip-tags $ANSIBLE_SKIP_TAGS $ANSIBLE_PLAYBOOK_COMMAND_OPTIONS"
fi
if [[ -n "${ANSIBLE_EXTRA_VARS}" ]]; then
  ANSIBLE_PLAYBOOK_COMMAND_OPTIONS="--extra-vars $ANSIBLE_EXTRA_VARS $ANSIBLE_PLAYBOOK_COMMAND_OPTIONS"
fi

ON_FAIL=${ON_FAIL:-"systemctl status --no-pager"}

cd $DEVSHOP_PATH
devshop-logo "Checking Ansible Inventory for group '$DEVSHOP_ANSIBLE_GROUP_NAME' ..."
echo "> Contents of /etc/ansible/hosts:"
cat /etc/ansible/hosts
echo "> Contents of $ANSIBLE_PLAYBOOK:"
cat $ANSIBLE_PLAYBOOK
echo "> Running ansible all --list-hosts --limit $DEVSHOP_ANSIBLE_GROUP_NAME:"
ansible all --list-hosts --limit $DEVSHOP_ANSIBLE_GROUP_NAME

devshop-logo "Running Ansible Playbook..."
echo "ANSIBLE_CONFIG: $ANSIBLE_CONFIG"
echo "ANSIBLE_PLAYBOOK: $ANSIBLE_PLAYBOOK"
echo "ANSIBLE_TAGS: $ANSIBLE_TAGS"
echo "ANSIBLE_SKIP_TAGS: $ANSIBLE_SKIP_TAGS"
echo "ANSIBLE_EXTRA_VARS: $ANSIBLE_EXTRA_VARS"
echo "ANSIBLE_VERBOSITY: $ANSIBLE_VERBOSITY"
echo "ANSIBLE_PLAYBOOK_COMMAND_OPTIONS: $ANSIBLE_PLAYBOOK_COMMAND_OPTIONS"
echo "Additional Arguments: $*"
devshop-line

ANSIBLE_PLAYBOOK_FULL_COMMAND="ansible-playbook $ANSIBLE_PLAYBOOK \
    $ANSIBLE_PLAYBOOK_COMMAND_OPTIONS \
    $*"

echo $ANSIBLE_PLAYBOOK_FULL_COMMAND
devshop-line

set -ex
exec $ANSIBLE_PLAYBOOK_FULL_COMMAND || \
    devshop-log "Call to ansible-playbook failed. (exit $?) Running $ON_FAIL ..." && \
    $ON_FAIL; exit $?
