#!/bin/bash

INVENTORY=ansible_hosts
PLAYBOOK=iiab-from-cmdline.yml
CWD=`pwd`
IIAB_STATE_FILE=/etc/iiab/iiab_state.yml
IIAB_ENV_FILE=/etc/iiab/iiab.env

if [ ! -f $PLAYBOOK ]; then
    echo -e "\nEXITING: IIAB Playbook ""$PLAYBOOK"" not found."
    echo -e "\nPlease run this in /opt/iiab/iiab (top level of the git repo)."
    exit 1
fi

if [ -f $IIAB_ENV_FILE ]; then
    STAGE=0
    if grep -q STAGE= /etc/iiab/iiab.env ; then
        source /etc/iiab/iiab.env
        echo -e "\nExtracted STAGE=$STAGE (counter) from /etc/iiab/iiab.env"
        if ! [ "$STAGE" -eq "$STAGE" ] 2> /dev/null; then
            echo -e "\nEXITING: STAGE (counter) value == ""$STAGE"" is non-integer"
            exit 1
        elif [ "$STAGE" -lt 0 ] || [ "$STAGE" -gt 9 ]; then
            echo -e "\nEXITING: STAGE (counter) value == ""$STAGE"" is out-of-range"
            exit 1
        elif [ "$STAGE" -lt 3 ]; then
            echo -e "\nEXITING: STAGE (counter) value == ""$STAGE"
            echo -e "\nIIAB Stage 3 not complete."
            echo -e "\nPlease run: ./iiab-install"
            exit 1
        fi
    else
        echo -e "\nEXITING: STAGE (counter) not found"
        echo -e "\nIIAB not installed."
        echo -e "\nPlease run: ./iiab-install"
        exit 1
    fi
else
    echo -e "\nEXITING: /etc/iiab/iiab.env not found"
    echo -e "\nIIAB not installed."
    echo -e "\nPlease run: ./iiab-install"
    exit 1
fi
cp ./scripts/local_facts.fact /etc/ansible/facts.d/local_facts.fact

# Workaround for (web-published) images; will go away later
if grep -q sugar $IIAB_STATE_FILE && ! grep -q mongodb $IIAB_STATE_FILE; then
    echo "mongodb_installed: True" >> $IIAB_STATE_FILE
fi

export ANSIBLE_LOG_PATH="$CWD/iiab-configure.log"
ansible -m setup -i $INVENTORY localhost ${ARGS} --connection=local | grep python
ansible-playbook -i $INVENTORY $PLAYBOOK --connection=local
