#!/bin/bash
delay=900
version_file=/etc/lixonet/version
log=/app/log/lixonet.log

mkdir /app/log

echo "Lixonet EE started."

while true
do
  set +e
  current_version=`cat $version_file || echo 0`
  
  gpg --import <trusted_signers >> $log 2>&1
  for id in `gpg --list-packets <trusted_signers | awk '$1=="keyid:"{print$2}'`; do
	  (echo 5; echo y; echo save) | gpg --command-fd 0 --no-tty --no-greeting -q --edit-key $id trust >> $log 2>&1
	  if [ $? -ne 0 ]; then
		echo "Import GPG key with id $id from trusted_signers failed. For more details, see $log"
		sleep $delay
		continue
	  fi
  done
  
  git fetch --all >> /dev/null
  if [ $? -ne 0 ]; then
	echo "Git fetch from $GIT_URL failed."
	sleep $delay
	continue
  fi
  
  current_commit=`git rev-parse HEAD`
  latest_commit=`git log "--format=%G? %H" origin/master | grep ^G | head -n 1 | cut -d' ' -f2`
  if test -z $latest_commit; then
	echo "Latest commit couldn't be found."
	sleep $delay
	continue
  fi
  
  if [ $current_commit != $latest_commit ]; then
  	  echo "Checking out $latest_commit..."
	  git reset --hard >> /dev/null
	  git checkout $latest_commit -f
	  if [ $? -ne 0 ]; then
		echo "Git checkout failed."
		sleep $delay
		continue
	  fi
  fi
  
  checkout_version=`cat version`
  if [ "$checkout_version" -gt "$current_version" ]; then
	echo "Updating to version $checkout_version..."
	chmod +x build.sh && ./build.sh
	if [ $? -eq 0 ]; then
		echo "Update completed successfully."
		echo $checkout_version > $version_file
	else
		echo "Update failed; version was not updated. Trying again in $delay seconds."
		sleep $delay
		continue
	fi
  fi
  sleep $delay
done