#!/usr/bin/env bash
#set -x

## must run as root
if [ "`whoami`" != "root" ] ; then 
        echo "You must run $0 as root" 
        exit 1
fi

if [ $# != 1 ]; then 
	usage
	exit 
fi

function usage() {
	echo
	echo -e "Usage: bats-qa-reports COMMAND"
	echo -e "\t-h/help: print these words"
	echo -e "\tsetup: setup BATS QA Reports system"
	echo -e "\tstart: start BATS QA Reports system"
	echo -e "\tstop: stop BATS QA Reports system"
	echo
}

cd /srv/www/bats-qa-reports

case $1 in
"-h"|"help")
	usage
	exit
	;;
"setup")
	gem update --system && \
	gem install bundler && \
	bundle install --without test staging production --binstubs && \
	bin/rake db:migrate && \
	echo "Succeeded to setup bats-qa-reports!!" || \
	echo "Failed to setup bats-qa-reports!!"
	;;
"start")	
	bin/rails server -d && \
	echo "=========================================================================" && \
	echo "You can access BATS qa reports system now! Try: http://localhost:3000" && \
	echo "=========================================================================" || \
	echo "Failed to start bats-qa-reports!!"
	;;
"stop")
	pid=$(cat tmp/pids/server.pid) && \
	kill -9 $pid && sleep 3 && \
	rm -f tmp/pids/server.pid && \
	echo "Succeeded to stop bats-qa-reports!!" || \
	echo "Failed to stop bats-qa-reports!! Please do it manually..."
	;;
*)
	usage
	exit
	;;
esac
