#!/bin/bash

set -u

readonly DATA_ROOT="${SIGNAGE_DATA_ROOT:-/home/signage}"
readonly RUNTIME_ROOT="${SIGNAGE_RUNTIME_ROOT:-/run/signage}"
readonly PLAY_HISTORY="$RUNTIME_ROOT/played-playlists.tsv"
readonly HISTORY_BOOT="$RUNTIME_ROOT/played-playlists.boot"
readonly MAX_AGE_DAYS="${SIGNAGE_PLAYLIST_MAX_AGE_DAYS:-30}"
readonly RETRY_SECONDS="${SIGNAGE_TIME_SYNC_RETRY_SECONDS:-60}"

case "$MAX_AGE_DAYS" in
    ''|*[!0-9]*)
        echo "Invalid SIGNAGE_PLAYLIST_MAX_AGE_DAYS: $MAX_AGE_DAYS" >&2
        exit 1
        ;;
esac
readonly MAX_AGE_SECONDS=$((10#$MAX_AGE_DAYS * 24 * 60 * 60))

# Devices without an RTC can boot near the Unix epoch. Never permit a purge
# until systemd confirms that network time has synchronized. Monotonic uptime
# is still used below for age calculations so later wall-clock corrections or
# jumps cannot make a playlist appear older than it is.
until [[ "$(timedatectl show --property=NTPSynchronized --value 2>/dev/null)" == "yes" ]]; do
    sleep "$RETRY_SECONDS"
done

[[ -d "$DATA_ROOT" ]] || exit 0

# /run is cleared at boot. Do not interpret a missing playlist entry as old
# until this boot's RAM-backed observation window spans the full retention
# period. App restarts preserve the original marker for the current boot.
[[ -r "$HISTORY_BOOT" && -r "$PLAY_HISTORY" ]] || exit 0
read -r history_started < "$HISTORY_BOOT" || exit 0
case "$history_started" in
    ''|*[!0-9]*) exit 0 ;;
esac

read -r uptime _ < /proc/uptime || exit 0
readonly now="${uptime%%.*}"
case "$now" in
    ''|*[!0-9]*) exit 0 ;;
esac
if (( history_started > now || now - history_started < MAX_AGE_SECONDS )); then
    exit 0
fi
readonly cutoff=$((now - MAX_AGE_SECONDS))

declare -A recently_played=()
while IFS=$'\t' read -r played_at account branch playlist; do
    [[ "$played_at" == \#* ]] && continue
    case "$played_at" in
        ''|*[!0-9]*) continue ;;
    esac
    [[ -n "$account" && -n "$branch" && -n "$playlist" ]] || continue
    if (( played_at >= cutoff && played_at <= now )); then
        recently_played["$account/$branch/$playlist"]=1
    fi
done < "$PLAY_HISTORY"

active_playlist="$(readlink -f -- "$DATA_ROOT/playing.json" 2>/dev/null || true)"

while IFS= read -r -d '' playlist_json; do
    # Never remove the playlist currently selected for startup/playback.
    if [[ -n "$active_playlist" && "$playlist_json" == "$active_playlist" ]]; then
        continue
    fi

    playlist_dir="${playlist_json%/playlist.json}"
    relative_playlist="${playlist_dir#"$DATA_ROOT"/}"
    if [[ -n "${recently_played[$relative_playlist]+present}" ]]; then
        continue
    fi

    case "$playlist_dir" in
        "$DATA_ROOT"/*)
            echo "Removing playlist not played for $MAX_AGE_DAYS days: $playlist_dir"
            rm -rf -- "$playlist_dir"
            ;;
    esac
done < <(
    find "$DATA_ROOT" \
        -mindepth 4 -maxdepth 4 \
        -type f -name playlist.json -print0
)

# Remove account/branch directories left empty by the playlist cleanup.
find "$DATA_ROOT" -mindepth 1 -maxdepth 3 -depth -type d -empty -delete
