#!/bin/sh

set -e
#set -x

if [ -z "${1}" ] ; then
	echo "Missing destination host"
	exit 1
fi

DEST_OCI=${1}
shift

echo "===========> Syncing PHP code <==========="
cd src
tar -czf php.tar.gz *.php *.json inc
echo "===> Copying PHP to ${DEST_OCI}"
scp php.tar.gz root@${DEST_OCI}:
rm php.tar.gz
cd ..
echo "===> Extracting PHP in OCI"
ssh -A root@${DEST_OCI} "cd /usr/share/openstack-cluster-installer ; tar -xzf /root/php.tar.gz ; rm /root/php.tar.gz"

echo "===> Synching db"
ssh -A root@${DEST_OCI} "php /usr/share/openstack-cluster-installer/db_sync.php"

echo "===========> Syncing Puppet code <==========="
echo "===> Making Puppet manifests tarball"
cd puppet
tar -czf puppet.tar.gz manifests files lib templates
echo "===> Copying Puppet code to ${DEST_OCI}"
scp puppet.tar.gz root@${DEST_OCI}:
rm puppet.tar.gz
echo "===> Extracting Puppet code in OCI"
ssh -A root@${DEST_OCI} "cd /usr/share/puppet/modules/oci ; tar -xzf /root/puppet.tar.gz ; rm /root/puppet.tar.gz"
ssh -A root@${DEST_OCI} "/etc/init.d/puppet-master restart"
cd ..

echo "===========> Syncing shell scripts <==========="
echo "===> Making bin shell scripts tarball"
tar -czf bin.tar.gz bin
echo "===> Copying bin shell scripts to ${DEST_OCI}"
scp bin.tar.gz root@${DEST_OCI}:
rm bin.tar.gz
echo "===> Extracting bin shell scripts in OCI"
ssh -A root@${DEST_OCI} "tar -xzf bin.tar.gz ; cd bin ; chown -R root:root . ; chmod -R 755 . ; cp ./* /usr/bin ; cd ~ ; rm -r bin bin.tar.gz ;"

echo "===========> Syncing ocicli and auto-complete <==========="
scp ocicli/ocicli root@${DEST_OCI}:/usr/bin
scp ocicli/completions/ocicli root@${DEST_OCI}:/usr/share/bash-completion/completions
ssh root@${DEST_OCI} "mkdir -p /etc/ocicli"
scp src/variables.json root@${DEST_OCI}:/etc/ocicli/
