#!/bin/bash
cd $(dirname $0)
cd ..

get_ip() {
    ping -c 1 "$1" | head -1 | tr '(' ')' | cut -d')' -f 2
}

trim () {
    read -rd '' $1 <<<"${!1}"
}

die () {
    echo "$@"
    exit 1
}

if [ "$1" == "" ]; then
    die "You must supply a hostname."
fi

hostname="$1"
shift

src_directories="maascli maasserver provisioningserver metadataserver"
remote_src_base=/usr/lib/python3/dist-packages
rsync_options=rlptvz
ssh_run="ssh -oBatchMode=yes -l root $hostname"

echo "Checking $hostname..."
maas_version=$($ssh_run "dpkg -s maas-region-api | grep ^Version") \
    || die "Cannot SSH to root@$hostname."
ip_address=$(get_ip $hostname)
maas_version=$(echo $maas_version | cut -d':' -f 2)
trim maas_version
trim hostname
trim ip_address
echo ""
echo "Current MAAS version is: $maas_version"
echo ""
echo "WARNING: This will LIVE UPDATE the MAAS server at:"
if [ $hostname == $ip_address ]; then
    echo "    $hostname"
else
    echo "    $hostname ($ip_address)"
fi
echo ""
echo "This is a DESTRUCTIVE script that will OVERWRITE files installed by the"
echo "MAAS packages, and DELETE any extra files found on the server."
echo ""
echo "The MAAS server must be running Xenial with MAAS 2.0+ for this to work."
echo ""
echo "Destination directories:"
for dir in $src_directories; do
echo "    $remote_src_base/$dir"
done
echo "    /etc/maas"
echo ""
echo "The following directories from this sandbox will be copied:"
for dir in $src_directories; do
echo "    src/$dir"
done
echo "    etc/maas"
echo ""
echo "Press <enter> to continue, ^C to cancel."
read

echo "Synchronizing Python code..."
for dir in $src_directories; do
    remote_dir=${remote_src_base}/${dir}
    rsync -${rsync_options} --delete-after --exclude 'tests/' src/${dir}/ \
        root@${hostname}:${remote_dir} \
        && echo "Success." || die "Syncrhonization failed."
    $ssh_run "python3 -c \"import compileall; compileall.compile_dir('$remote_dir', force=True)\""
done

echo "Updating /etc/maas..."
rsync -${rsync_options} etc/maas/ \
    root@${hostname}:/etc/maas \
    && echo "Success." || die "Syncrhonization failed."
$ssh_run "chown -R maas:maas /etc/maas"

echo "Updating /usr/share/maas/maas..."
rsync -${rsync_options} src/maas/ \
    root@${hostname}:/usr/share/maas/maas \
    && echo "Success." || die "Syncrhonization failed."

echo ""
echo "Restarting services and ensuring migrations are up to date..."
$ssh_run rm -rf /usr/share/maas/web/static/*
$ssh_run mv /usr/lib/python3/dist-packages/maasserver/static/* /usr/share/maas/web/static/
$ssh_run service maas-regiond stop
$ssh_run maas-region migrate
sleep 1
$ssh_run service maas-regiond start
$ssh_run service apache2 restart
$ssh_run service maas-rackd restart
