#!/bin/bash
#
# fingerprint.sh — turn a film's audio into a .shazamcatalog the Boo Cue app can match.
#
#   ./fingerprint.sh <audio-file> <output.shazamcatalog>
#
# Needs macOS with Apple's `shazam` command (built in; check with `shazam --help`). The
# input must be an audio file macOS can read (.m4a, .wav, .aiff, .mp3); see README.md for
# getting one out of a video with ffmpeg.
#
# WHY THIS EXISTS RATHER THAN ONE `shazam` COMMAND
#
# A single ShazamKit signature silently stops matching after roughly 35 minutes of audio:
# nothing fails, the file looks fine, and the second half of the film simply never matches.
# So the audio is fingerprinted in overlapping 15-minute segments, and each segment is
# tagged with the second it starts at, in a property named `ajsSegmentOffset`. The app adds
# that number to wherever ShazamKit says a match landed inside the segment. That property
# name is the only Boo Cue-specific thing in the file — spell it exactly.
#
# Prints the `fingerprints` entry for the film's JSON when it finishes.

set -euo pipefail

SEGMENT=${SEGMENT:-900}   # seconds per segment; comfortably under the ~35 minute ceiling
OVERLAP=${OVERLAP:-30}    # so a few seconds heard at a boundary sit wholly inside one segment

if [[ $# -ne 2 ]]; then
  echo "usage: $0 <audio-file> <output.shazamcatalog>" >&2
  exit 1
fi
input=$1
output=$2

command -v shazam >/dev/null || { echo "error: Apple's 'shazam' command was not found (macOS only)." >&2; exit 1; }
[[ -f $input ]] || { echo "error: no such file: $input" >&2; exit 1; }

# afinfo ships with macOS and reads any format Core Audio does.
duration=$(afinfo "$input" 2>/dev/null | awk '/estimated duration/ { print int($3) }')
[[ -n $duration && $duration -gt 0 ]] || { echo "error: could not read a duration from $input — is it an audio file?" >&2; exit 1; }

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
rm -f "$output"

echo "input     $input ($duration s)"
start=0
count=0
while (( start < duration )); do
  length=$(( duration - start < SEGMENT ? duration - start : SEGMENT ))
  (( length >= 1 )) || break
  count=$((count + 1))

  # `shazam signature` rejects --start 0, so the first segment simply omits it.
  args=(--input "$input" --duration "$length" --output "$work/segment.shazamsignature")
  (( start > 0 )) && args+=(--start "$start")
  shazam signature "${args[@]}" >/dev/null

  # One media item per segment, carrying only the offset. The app takes the film's title
  # and everything else from the JSON, so nothing else needs to be in here. `shazam`
  # guesses each CSV value's type — 0 comes out as the boolean False and 870 as the string
  # "870" — and the app reads all of those as the number they look like.
  printf 'ajsSegmentOffset\n%s\n' "$start" > "$work/segment.csv"

  if (( count == 1 )); then
    shazam custom-catalog create --signature-asset "$work/segment.shazamsignature" \
      --media-items "$work/segment.csv" --output "$output" >/dev/null
  else
    # `update` refuses to overwrite the catalog it is reading, so write beside it and swap.
    shazam custom-catalog update --input "$output" --signature-asset "$work/segment.shazamsignature" \
      --media-items "$work/segment.csv" --output "$work/next.shazamcatalog" >/dev/null
    /bin/mv -f "$work/next.shazamcatalog" "$output"
  fi
  echo "segment   $count at ${start}s (${length}s)"

  start=$(( start + SEGMENT - OVERLAP ))
done

sha256=$(shasum -a 256 "$output" | cut -d ' ' -f 1)
bytes=$(stat -f %z "$output")
name=$(basename "$output")

cat <<EOF
output    $output

Add this to the film's "fingerprints" list, with "path" set to wherever you host the file:

    { "sha256": "$sha256", "bytes": $bytes,
      "path": "/v1/catalogs/$name",
      "audio": { "language": "en" } }

Scare times must be measured in seconds from the start of $(basename "$input").
EOF
