#!/usr/bin/bash
# Cron de verificación diaria de updates del webphone (03:00).
# Escribe resultado en webphone_global_settings para que
# update.php?action=check_update solo lea la tabla.
set -euo pipefail

LOCK="/tmp/webphone_cron_update.lock"
exec 200>"$LOCK"
flock -n 200 || exit 0

DB="/var/www/db/webphone.db"
[ -f "$DB" ] || exit 0

RESULT=$(/usr/bin/issabel-helper webphone check_update 2>/dev/null) || exit 1

case "$RESULT" in
    *'"installed"'*) ;;
    *) exit 1 ;;
esac

TS=$(date +%s)

sqlite3 "$DB" "INSERT OR REPLACE INTO webphone_global_settings (setting_key, setting_value) VALUES ('update_check_ts', '$TS');"
sqlite3 "$DB" "INSERT OR REPLACE INTO webphone_global_settings (setting_key, setting_value) VALUES ('update_check_data', '$RESULT');"

if echo "$RESULT" | grep -q '"update_available":true'; then
    AVAILABLE=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('available',''))" 2>/dev/null || echo "")
    INSTALLED=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('installed',''))" 2>/dev/null || echo "")
    if [ -n "$AVAILABLE" ]; then
        LAST=$(sqlite3 "$DB" "SELECT setting_value FROM webphone_global_settings WHERE setting_key = 'last_update_notified';" 2>/dev/null || echo "")
        if [ "$LAST" != "$AVAILABLE" ]; then
            /usr/bin/issabel-notification --level warning --resource webphone \
                --message "Webphone update disponible: $INSTALLED -> $AVAILABLE" 2>/dev/null || :
            sqlite3 "$DB" "INSERT OR REPLACE INTO webphone_global_settings (setting_key, setting_value) VALUES ('last_update_notified', '$AVAILABLE');"
        fi
    fi
fi
