#!/bin/bash
# Enable automatic masterfiles updates from local git repository
# CFEngine AS, May 2014

die () { echo "$(basename $0): $1"; exit 1; }
export PATH="/var/cfengine/bin:${PATH}"

cat <<EOHIPPUS
This script will enable automatic updating of /var/cfengine/masterfiles
from the built-in local git repository that ships with CFEngine Enterprise,
according to these instructions:

https://docs.cfengine.com/docs/master/guide-enterprise-cfengine-guide-version-control-policy.html

***************************************************************************
PLEASE NOTE: this will overwrite the current contents of that directory.
***************************************************************************

Please type 'yes' to continue, anything else to abort:
EOHIPPUS

read ANS

if [[ "$ANS" != "yes" ]]; then
   echo "Good bye."
   exit
fi

echo "OK, proceeding..."
echo ""

echo "First, I need a name and email address. These will be used in the git commit log."

echo -n "Name: "
read NAME

echo -n "Email: "
read EMAIL

echo "Thank you. Configuring git."

su - -c "git config --global user.name '$NAME'; git config --global user.email '$EMAIL'; git config --global push.default matching" cfapache || die "Couldn't configure Git"

echo "Checking out local git repository as user 'cfapache'"
su - -c "rm -rf masterfiles; git clone /opt/cfengine/masterfiles.git" cfapache || die "Couldn't clone /opt/cfengine/masterfiles.git"

echo "Editing update.cf file to enable automatic VCS deployment"

sed -i 's/"cfengine_internal_masterfiles_update" expression => "!any";/#"cfengine_internal_masterfiles_update" expression => "!any";/; s/#"cfengine_internal_masterfiles_update" expression => "enterprise.!(cfengine_3_4|cfengine_3_5)";/"cfengine_internal_masterfiles_update" expression => "enterprise.!(cfengine_3_4|cfengine_3_5)";/' /var/cfengine/cfapache/masterfiles/update.cf || die "Couldn't edit masterfiles/update.cf to enable cfengine_internal_masterfiles_update"

echo "Committing changes"
su - -c "cd masterfiles; git add update.cf; git commit -m 'Enabled auto-policy updates'; git push" cfapache || due "Couldn't commit the changes back to /opt/cfengine/masterfiles.git"

BAK="/var/cfengine/masterfiles.$(date +%s)"

echo "Backing up /var/cfengine/masterfiles to $BAK"

cp -a /var/cfengine/masterfiles "$BAK" || die "Couldn't back up /var/cfengine/masterfiles"

echo "Doing one-time manual update from git"

cf-agent -KI -Dcfengine_internal_masterfiles_update -f update.cf || die "Couldn't do the first-time update"

echo ""

echo "Done. From now on /var/cfengine/masterfiles/ will automatically"
echo "update from the git repository at /opt/cfengine/masterfiles.git"
