#!/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 6 )" != "PERCo-" ] ; 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" != "CTL14.1P" ] && [ "$model_exact" != "CTL16DINP" ] && [ "$model_exact" != "CTL16.DINP" ] && [ "$model_exact" != "CTL14.2" ] ; then
	printf " ! Not t113 system! Model is [%s]   Canceling upgrade\n" "$model_type"
	rm -f firmware/s30
	exit 1
fi

model_small="$(echo "$model_exact" |  tr '[:upper:].' '[:lower:]-')"
if [ -r firmware/systemupdate/sun8i-t113-$model_small.dtb ] ; then
  mkdir -p /mnt/boot ; mount -o ro /dev/mmcblk0p1 /mnt/boot
  first_crc="$(crc32 /mnt/boot/sun8i-t113-$model_small.dtb | cut -d' ' -f1)"
  second_crc="$(crc32 firmware/systemupdate/sun8i-t113-$model_small.dtb | cut -d' ' -f1)"
  if [ ! $first_crc == $second_crc ] ; then
    mount -o remount,rw /mnt/boot
    cp -f firmware/systemupdate/sun8i-t113-$model_small.dtb /mnt/boot/sun8i-t113-$model_small.dtb &2> /crc
  fi
# if [ ! -f /mnt/boot/version ] || [ "$(cat /mnt/boot/version)" != "2" ] ; then
# 	umount /mnt/boot
# 	printf " ! Wrong version, install previous update   Canceling upgrade\n"
# 	rm -f firmware/s30
# 	exit 1
# fi
  umount /mnt/boot
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 -l s30/base.db* firmware
log_do 'Copying defaults' cp -l s30/default.lua firmware
log_do 'Copying SSL keys' cp -l s30/ssl.pem firmware
sync
log_do 'Request reboot' touch /reboot_me_please
printf '\n'
