#!/bin/sh
 
my_curl() {
    timeout 60 curl $@
}
 
my_log() {
    logger -t "my_custom_updater" "$@"
}
 
die() {
    my_log "$@"
    exit
}
 
UPDATE_URL="http://192.168.1.131:5000/update/ezcustom.tar.gz"
LAST_MODIFIED_FILE="/etc/ezcustom/.last_modified"
NEW_CUSTOM="/tmp/custom.tar.gz"
 
my_log "check '$UPDATE_URL' for updates..."
HEADERS="$(my_curl -I "$UPDATE_URL")"
LAST_MODIFIED="$(echo "$HEADERS" | grep -e '^Last-Modified:')"
test -z "$LAST_MODIFIED" && die "unable to check for updates"
my_log "last modified date: '$LAST_MODIFIED'"
test "$LAST_MODIFIED" = "$(cat "$LAST_MODIFIED_FILE")" && die "already at last configuration version"
 
my_log "downloading new version"
my_curl -o "$NEW_CUSTOM" "$UPDATE_URL" || die "unable to download new configuration"
sysupgrade --restore-backup "$NEW_CUSTOM" || die "unable to update configuration"
echo "$LAST_MODIFIED" >"$LAST_MODIFIED_FILE"
sync