#!/usr/bin/env bash -l

set -e

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

VAGRANT_STARTED=false

green="\x1B[0;32m" # '\e[1;32m' is too bright for white bg.
blue="\x1B[1;34m"
endColor="\x1B[0m"

function echoblue() {
    echo -e "${blue}$1${endColor}"
}

function install() {
    pushd "$DIR"

    echoblue "---> checking vagrant"
    if vagrant status | grep -q -v "running"; then
        echoblue "---> starting vagrant"
        # if which virtualenvwrapper.sh > /dev/null 2>&1 ; then
        #     echoblue "---> activating ansible"
        #     source `which virtualenvwrapper.sh`
        #     workon ansible
        # fi
        vagrant up
        VAGRANT_STARTED=true
        # if type -t deactivate > /dev/null 2>&1 ; then
        #     deactivate
        # fi
    fi

    echoblue "---> done"

    popd > /dev/null

    return 0
}

function usage() {
    cat <<EOF
Usage: $0 [-I] [-h]
    -I : do not run install
    -h : print this message
EOF
}

environment=""
do_install=true


while getopts "Ih" opt; do
  case $opt in
    I) do_install=false ;;
    h) usage; exit 0 ;;
    \?) usage >&2; exit 1 ;;
  esac
done
shift $((OPTIND-1))

echo "do_install: $do_install"
[[ "$do_install" == true ]] && echoblue "DO INSTALL" && install;

pushd "$DIR"

echoblue "---> cleaning build folder"
rm -fr root-puppet

echoblue "---> creating build folder"
mkdir -p root-puppet/var/lib/puppet/provision
mkdir -p root-puppet/etc/puppet/hiera

echoblue "---> copying provision files"
rsync --exclude='.git' --exclude='.hg*' --exclude='custom.yaml' -aviuPz ../dev/provisioning/ root-puppet/var/lib/puppet/provision/
echoblue "---> copying provision files done"

echoblue "---> copying template file"
cp -a ../dev/provisioning/custom.yaml.tmpl root-puppet/etc/puppet/hiera
echoblue "---> copying template files done"

#  :datadir: "."
echoblue "---> add path in root-puppet/var/lib/puppet/provision/hiera.yaml"
sed -i "" -E 's/^([[:space:]]+\:datadir\:).*$/\1 \"\/etc\/puppet\/hiera\"/' root-puppet/var/lib/puppet/provision/hiera.yaml
echoblue "---> add path in root-puppet/var/lib/puppet/provision/hiera.yaml done"


echoblue "---> building package"
vagrant ssh -c "/vagrant/build_rpm_puppet.sh"
echoblue "---> building package done"

if [ "$VAGRANT_STARTED" = true ]; then
    echoblue "---> Stopping vagrant"
    vagrant halt
    echoblue "---> Stopping vagrant done"
fi

popd > /dev/null

echoblue "---> done"

