#!/bin/bash

#
# @new-otdt.itk.ppke.hu : run as "divad" !!!
#

if [ "$(id -u)" == "0" ]; then
   echo "Do not run this script as root. " 1>&2
   exit 1
fi

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

read -p "Start update process? [y/N] " choice
case "$choice" in
  y|Y ) 
	$DIR/symfony project:disable prod
        echo "Pulling... "
	hg pull -R $DIR
        echo "Updating... "
	hg update -R $DIR
	;;
  n|N )
	echo "Cancelled, exiting. "
	exit
	;;
  * )
	echo "Exiting. "
	exit
esac

read -p "Update the database? [y/n] " choice
case "$choice" in
  y|Y ) 
        $DIR/symfony doctrine:migrate
	;;
  n|N )
        echo "Skipping database upgrade. "
        ;;
  * )
        echo "Invalid answer."
esac

read -p "Re-enable the site? [y/n] " choice
case "$choice" in
  y|Y )
	echo "Enabling... ";
        $DIR/symfony project:enable prod
	echo "Clearing the cache... ";
	$DIR/symfony cc
        ;;
  n|N )
        echo "Cancelled."
        ;;
  * )
        echo "Invalid answer."
esac

egrep -i "^otdt" /etc/group
if [ $? -eq 0 ]; then
	echo "Updating file permissions...";
	chgrp -R otdt $DIR/apps
        chgrp -R otdt $DIR/backup
        chgrp -R otdt $DIR/config
        chgrp -R otdt $DIR/data
        chgrp -R otdt $DIR/lib
        chgrp -R otdt $DIR/plugins
        for i in $(ls $DIR/web); do
            if [ "$i" != "uploads" ]; then
                chgrp -R otdt $DIR/web/$i;
            fi
        done
fi

HOSTNAME=$(hostname)
if [ "$HOSTNAME" == "new-otdt.itk.ppke.hu" ]; then
	read -p "Update the TEST system, too? [y/n] " choice
	case "$choice" in
		y|Y )
			$DIR/../test/seal/otdt-update.sh
			;;
		n|N )
			echo "Ignoring TEST system update."
			;;
		* )
			"Invalid answer."
esac
fi
