#!/bin/sh

usage() {
    echo -e "Usage: $0 [OPTION...]\n"
    echo -e "  -?, --help\tgive this help list"
    echo -e "  -R\trollback to the last binary backup"
}

while getopts "R" opt; do
    case $opt in
        R|r)
	    ROLLBACK=1
	    ;;
	\?)
	    usage
	    exit 1
	    ;;
    esac
done

/etc/init.d/lxc.{{ ctr_name }}-final status > /dev/null 2> /dev/null
FINAL_UP=$?

[ "$FINAL_UP" = 0 ] && /etc/init.d/lxc.{{ ctr_name }}-final stop
/etc/init.d/lxc.{{ ctr_name }} stop

for b in checker token-validator
do
    echo -n " * Updating $b ..."
    if [ -n "$ROLLBACK" ]
    then
	[ -f "/var/lib/lxc/{{ ctr_name }}/rootfs/home/backups/$b" ] || echo " Doesn't exists"
	[ -f "/var/lib/lxc/{{ ctr_name }}/rootfs/home/backups/$b" ] && {
	    mv "/var/lib/lxc/{{ ctr_name }}/rootfs/usr/sbin/$b" /var/lib/lxc/{{ ctr_name }}/rootfs/home/newbuilds/
	    cp "/var/lib/lxc/{{ ctr_name }}/rootfs/home/backups/$b" /var/lib/lxc/{{ ctr_name }}/rootfs/usr/sbin/
	} && echo " DONE"
    else
	[ -f "/var/lib/lxc/{{ ctr_name }}/rootfs/home/newbuilds/$b" ] || echo " Doesn't exists"
	[ -f "/var/lib/lxc/{{ ctr_name }}/rootfs/home/newbuilds/$b" ] && {
	    cp "/var/lib/lxc/{{ ctr_name }}/rootfs/usr/sbin/$b" /var/lib/lxc/{{ ctr_name }}/rootfs/home/backups/
	    mv "/var/lib/lxc/{{ ctr_name }}/rootfs/home/newbuilds/$b" /var/lib/lxc/{{ ctr_name }}/rootfs/usr/sbin/
	} && echo " DONE"
    fi
done

/etc/init.d/lxc.{{ ctr_name }} start
[ "$FINAL_UP" = 0 ] && /etc/init.d/lxc.{{ ctr_name }}-final start
