#!/bin/bash
# GetPageSpeed license heartbeat for the Debian and Ubuntu PHP channels.
#
# Reports this channel's presence to the license endpoint and refreshes the
# enforcement verdict the statically built gps_license PHP extension reads.
# Fail-open by design: any error (network, non-JSON answer, missing curl)
# leaves the previous verdict in place and exits 0. Never writes to stdout
# or stderr, so cron never emails.
#
# php72 / 7.2.34-66+gps1+ubuntu1804+stable.1 / bionic are substituted by debian/rules.

exec >/dev/null 2>&1

VERDICT_DIR=/var/lib/gps-license-php-deb
VERDICT_FILE=$VERDICT_DIR/verdict.json
ENDPOINT=https://www.getpagespeed.com/wp-json/getpagespeed/v1/license/report

[ -d "$VERDICT_DIR" ] || exit 0
command -v curl >/dev/null || exit 0

# Splay within the cron.daily window so the fleet does not thundering-herd.
sleep $((RANDOM % 1800))

payload=$(printf '{"package_source":"php_deb","nginx_version":"%s","module_version":"%s","distro":"bionic","arch":"%s"}' \
    "7.2.34-66+gps1+ubuntu1804+stable.1" "php72" "$(dpkg --print-architecture)")

tmp=$(mktemp "$VERDICT_FILE.XXXXXX") || exit 0
trap 'rm -f "$tmp"' EXIT

if ! curl --silent --fail --max-time 10 \
        --header 'Content-Type: application/json' \
        --data "$payload" \
        --output "$tmp" \
        "$ENDPOINT"; then
    exit 0
fi

# Only accept an answer that carries a verdict; anything else is left alone.
grep -q '"enforcement"' "$tmp" || exit 0

chmod 0644 "$tmp"
mv -f "$tmp" "$VERDICT_FILE"
trap - EXIT
exit 0
