#!/bin/sh

#
# Files in this folder are executed last when the new rootfs
# is booted for the first time
#
# To activate this script link it into /etc/systemupdate/user-post-update.d
#  cd /etc/systemupdate/user-post-update.d
#  ln -s ../user-handler-examples/install-automatic-updates .
#
# All files in /etc/systemupdate/user-post-update.d are automatically backed up
#

cat <<"EOT" > /usr/bin/automatic_update.sh
#!/bin/sh

release_type=$(cat /etc/release-type)
if [ $release_type == "devel" ]; then
    hw_info=$(cat /etc/hwrevision | cut -d " " -f1)
    update_test_status=$(curl -s https://nwadststpyt-dssupdatestatus.azurewebsites.net/$hw_info | jq -r '.update_status')
else
    update_test_status="OK"
fi

if [ $update_test_status == "OK" ]; then
    /bin/echo "Safe to update, proceeding"
    cd /www/pages/cgi-bin && ./systemupdate.sh update
else
    /bin/echo "Update not safe, update test status: $update_test_status"
fi
EOT
chmod +x /usr/bin/automatic_update.sh

cat <<EOT > /etc/cron.d/automatic-update
#  +---------------- minute (0 - 59)
#  |  +------------- hour (0 - 23)
#  |  |  +---------- day of month (1 - 31)
#  |  |  |  +------- month (1 - 12)
#  |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
#  |  |  |  |  |
  00  3  *  *  *  root /usr/bin/automatic_update.sh

EOT
chmod 0644 /etc/cron.d/automatic-update
