#!/bin/sh

log_do() {
  printf '\n   . '
  printf "%s" "$1"
  printf '... '
  shift
  $@ && printf 'Done' || printf "\n   ! Some errror happened. Errorcode %s" "$?"
}

model_type="$(cat /sys/firmware/devicetree/base/model)"
if [ "$(expr substr "$model_type" 1 7 )" != "PERCo-C" ] ; then
	printf " ! Not PERCo system! Model is [%s]   Canceling upgrade\n" "$model_type"
	rm -f firmware/s30
	exit 1
fi

model_exact="$(expr substr "$model_type" 7 40)"
if [ "$model_exact" != "CR11.1" ] && [ "$model_exact" != "CT13.1" ] && [ "$model_exact" != "CTL14.1" ] && [ "$model_exact" != "CL15.1" ] && [ "$model_exact" != "CL15.3" ] && [ "$model_exact" != "CL15.7" ]; then
	printf " ! Not v3s system! Model is [%s]   Canceling upgrade\n" "$model_type"
	rm -f firmware/s30
	exit 1
fi

if [ -d firmware/kernelupdate ] ; then
  printf ' . firmware kernelupdate found. Trying to do kernelupdate \n'
  if firmware/kernelupdate/update ; then
    printf ' . kernelupdate successfully finished.\n'
  else
    printf " ! kernelupdate ended with code %s --- exiting\n" "$?"
    rm -f firmware/s30
    exit 1
  fi
fi

if [ -d firmware/systemupdate ] ; then
  printf ' . firmware systemupdate found. Trying to do systemupdate \n'
  if firmware/systemupdate/update ; then
    printf ' . systemupdate successfully finished.\n'
  else
    printf " ! systemupdate ended with code %s --- exiting\n" "$?"
    rm -f firmware/s30
    exit 1
  fi
fi
printf ' . v -- Old data saving script started --\n'
log_do 'Copying database' cp s30/base.db* firmware
log_do 'Copying defaults' cp s30/default.lua firmware
log_do 'Copying SSL keys' cp s30/ssl.pem firmware
sync
log_do 'Request reboot' touch /reboot_me_please
printf '\n'
