#!/usr/bin/env bash
# seameet-backup.sh — copy your SeaMeet recordings into Google Drive (or any
# folder): each recording's audio or video file plus its Word document
# (summary, action items, chapters, notes and transcript).
#
# Run it by hand or daily from cron. Each run copies what is new or changed
# since the last one; the first run copies everything.
#
#   SEAMEET_API_KEY=smk_...   a read-scoped key from https://app.seameet.ai/account
#   DEST=...                  where to put it:
#                               - a folder, e.g. the Google Drive for desktop
#                                 folder "$HOME/Google Drive/My Drive/SeaMeet";
#                               - or an rclone remote, e.g. "gdrive:SeaMeet"
#                                 (set up once with: rclone config).
# Optional:
#   SEAMEET_TIMEZONE=Asia/Taipei  meeting times and dates in the Word file (default UTC)
#   SEAMEET_LANGUAGE=zh-TW        the Word file's headings (default: the spoken language)
#   SEAMEET_INCLUDE_SHARED=1      also copy recordings others shared with you
#   SEAMEET_STATE_DIR=...         where it remembers progress (default ~/.seameet-backup)
#
# Needs bash, curl and jq; rclone only for an rclone DEST.
# Cron, daily at 02:00:
#   0 2 * * * SEAMEET_API_KEY=smk_... DEST="gdrive:SeaMeet" /path/to/seameet-backup.sh >> ~/seameet-backup.log 2>&1
#
# Each recording gets a folder "<date> <title> (<id>)". A recording whose
# summary or transcript changes gets a fresh Word file; its media file is
# copied again only if its size changed. Renaming a recording starts a new
# folder (the old one stays).
#
# Step-by-step guide: https://app.seameet.ai/google-drive-backup

set -euo pipefail

API="${SEAMEET_API_URL:-https://api.seameet.ai/functions/v1/sync-api}"
DOC_API="${SEAMEET_DOC_URL:-https://mcp.seameet.ai/v1/recordings}"
STATE_DIR="${SEAMEET_STATE_DIR:-$HOME/.seameet-backup}"
: "${SEAMEET_API_KEY:?Set SEAMEET_API_KEY to a key from https://app.seameet.ai/account}"
: "${DEST:?Set DEST to a folder or an rclone remote such as gdrive:SeaMeet}"
for tool in curl jq; do
  command -v "$tool" >/dev/null || { echo "seameet-backup: needs $tool" >&2; exit 1; }
done

# DEST is an rclone remote when it looks like "name:path" and is not an
# existing local path (Windows drive letters are one character: C:\...).
is_remote=0
if [[ "$DEST" =~ ^[A-Za-z0-9_.-]{2,}: ]] && [ ! -e "$DEST" ]; then
  is_remote=1
  command -v rclone >/dev/null || { echo "seameet-backup: DEST=$DEST needs rclone" >&2; exit 1; }
fi

mkdir -p "$STATE_DIR"
SINCE_FILE="$STATE_DIR/since"
MEDIA_FILE="$STATE_DIR/media.tsv" # assetId <tab> sizeBytes already copied
touch "$MEDIA_FILE"
since="$(cat "$SINCE_FILE" 2>/dev/null || echo '1970-01-01T00:00:00Z')"
run_started="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT

# One sync-api call; prints the JSON body, or fails with the HTTP status.
api() {
  local out status
  out="$work/api.json"
  status="$(curl -sS -o "$out" -w '%{http_code}' -X POST "$API" \
    -H "X-Api-Key: $SEAMEET_API_KEY" -H 'Content-Type: application/json' -d "$1")"
  if [ "$status" != 200 ]; then
    echo "HTTP $status $(cat "$out")" >&2
    return 1
  fi
  cat "$out"
}

# File- and Drive-safe names: no slashes, colons or control characters. Long
# titles are cut to 150 bytes (never inside a character: iconv drops the
# stub), keeping a file's extension.
safe() { printf '%s' "$1" | tr '/\\:*?"<>|' '_________' | tr -d '\000-\037'; }
clip() { printf '%s' "$1" | cut -b1-150 | iconv -f UTF-8 -t UTF-8 -c; }
file_name() {
  local n tail ext=''
  n="$(safe "$1")"
  tail="${n##*.}"
  if [[ "$n" == *.* ]] && [ "${#tail}" -le 5 ]; then ext=".$tail"; fi
  printf '%s%s' "$(clip "${n%"$ext"}")" "$ext"
}

# The Word file's name, as the web download names it: the UTF-8 filename*
# from Content-Disposition (curl -J only reads the ASCII fallback).
doc_name() {
  local enc
  enc="$(tr -d '\r' <"$1" | grep -o "filename\*=UTF-8''[^;]*" | head -n1 | sed "s/^filename\*=UTF-8''//")"
  if [ -n "$enc" ]; then file_name "$(printf '%b' "${enc//%/\\x}")"; else file_name "$2.docx"; fi
}

# Put one local folder's files into DEST/<name>.
deliver() {
  local from="$1" name="$2"
  if [ "$is_remote" = 1 ]; then
    rclone copy "$from" "$DEST/$name"
  else
    mkdir -p "$DEST/$name"
    cp -f "$from"/* "$DEST/$name"/
  fi
}

copied=0; skipped=0; failed=0
before='null'
while :; do
  page="$(api "$(jq -nc --arg since "$since" --argjson before "$before" \
    '{op:"list-library", since:$since, limit:100} + (if $before then {before:$before} else {} end)')")"
  while IFS= read -r row; do
    id="$(jq -r .id <<<"$row")"
    kind="$(jq -r .kind <<<"$row")"
    scope="$(jq -r '.accessScope // "owned"' <<<"$row")"
    # Recordings only (not screenshots), and only your own unless asked.
    if [ "$kind" != audio ] && [ "$kind" != video ]; then continue; fi
    if [ "$scope" != owned ] && [ "${SEAMEET_INCLUDE_SHARED:-0}" != 1 ]; then continue; fi
    title="$(jq -r '.display_name // .client_ref // "Untitled"' <<<"$row")"
    day="$(jq -r '.created_at // "" | .[0:10]' <<<"$row")"
    folder="$(clip "$(safe "$day $title")") (${id:0:8})"
    stage="$work/$id"; mkdir -p "$stage"
    ok=1

    # The media file: once, and again only if its size changed.
    if dl="$(api "$(jq -nc --arg id "$id" '{op:"download-url", assetId:$id, disposition:"attachment"}')" 2>"$work/err")"; then
      size="$(jq -r '.sizeBytes // ""' <<<"$dl")"
      if ! grep -qx "$id	$size" "$MEDIA_FILE"; then
        name="$(file_name "$(jq -r '.filename // "recording"' <<<"$dl")")"
        if curl -sSfL -o "$stage/$name" "$(jq -r .url <<<"$dl")"; then
          media_line="$id	$size"
        else
          echo "  ! $title: media download failed" >&2; ok=0
        fi
      fi
    elif grep -q 'HTTP 40[04]' "$work/err"; then
      : # no media file (still uploading, or text only): the Word file still comes
    else
      echo "  ! $title: $(cat "$work/err")" >&2; ok=0
    fi

    # The Word document, every time the recording changed. 404 = no text yet.
    q="?timeZone=${SEAMEET_TIMEZONE:-UTC}${SEAMEET_LANGUAGE:+&language=$SEAMEET_LANGUAGE}"
    status="$(curl -sS -o "$work/doc" -D "$work/doc.headers" -w '%{http_code}' \
      -H "X-Api-Key: $SEAMEET_API_KEY" "$DOC_API/$id/document.docx$q" || true)"
    if [ "$status" = 200 ]; then
      mv "$work/doc" "$stage/$(doc_name "$work/doc.headers" "$title")"
    elif [ "$status" != 404 ]; then
      echo "  ! $title: Word document failed (HTTP $status)" >&2; ok=0
    fi

    if [ -n "$(ls -A "$stage")" ]; then
      if deliver "$stage" "$folder"; then
        [ -n "${media_line:-}" ] && printf '%s\n' "$media_line" >>"$MEDIA_FILE"
        if [ "$ok" = 1 ]; then echo "  ✓ $folder"; else echo "  ~ $folder (partly copied; retried next run)"; fi
        copied=$((copied + 1))
      else
        echo "  ! $title: could not write to $DEST" >&2; ok=0
      fi
    else
      skipped=$((skipped + 1))
    fi
    media_line=''
    rm -rf "$stage"
    [ "$ok" = 1 ] || failed=$((failed + 1))
  done < <(jq -c '.assets[]' <<<"$page")
  before="$(jq -c '.next' <<<"$page")"
  [ "$before" = null ] && break
done

echo "seameet-backup: $copied copied, $skipped unchanged or empty, $failed failed (changes since $since)"
# Only a clean run moves the mark forward, so a failure is retried next time.
if [ "$failed" = 0 ]; then echo "$run_started" >"$SINCE_FILE"; fi
[ "$failed" = 0 ]
