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

mkdir /app/log

while true
do
  set +e
  current_version=`cat $version_file || echo 0`
  
  gpg --import <trusted_signers >> $log 2>&1
  (echo 5; echo y; echo save) | gpg --command-fd 0 --no-tty --no-greeting -q --edit-key "$(gpg --list-packets <trusted_signers | awk '$1=="keyid:"{print$2;exit}')" trust >> $log 2>&1
  if [ $? -ne 0 ]; then
	echo "GPG import from trusted_signers failed. For more details, see $log"
	sleep $delay
	continue
  fi
  
  git fetch $GIT_URL >> $log 2>&1
  if [ $? -ne 0 ]; then
	echo "Git fetch from $GIT_URL failed. For more details, see $log"
	sleep $delay
	continue
  fi
  
  latest_commit=`git log "--format=%G? %H" | grep ^G | head -n 1 | cut -d' ' -f2`
  if test -z $latest_commit; then
	sleep $delay
	continue
  fi
  
  git reset --hard >> $log 2>&1
  git checkout $latest_commit >> $log 2>&1
  if [ $? -ne 0 ]; then
	echo "Git checkout failed. For more details, see $log"
	sleep $delay
	continue
  fi
  
  checkout_version=`cat version`
  if [ "$checkout_version" -gt "$current_version" ]; then
	echo "Updating to version $checkout_version..."
	chmod +x build.sh && ./build.sh >> $log 2>&1
	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. For more details, see $log"
		sleep $delay
		continue
	fi
  fi
  sleep $delay
done