#!/bin/bash

# Source: https://docs.bigbluebutton.org/admin/customize.html#delete-recordings-older-than-n-days

set -e
LOGFILE=/var/log/bigbluebutton/bbb-recording-cleanup-$(date --iso-8601='seconds' -u).log
shopt -s nullglob
NOW=$(date +%s)

echo "$(date --rfc-3339=seconds) Deleting recordings older than ${RECORDING_MAX_AGE_DAYS} days" >"${LOGFILE}"

# Find the name of recordings container in order to access `bbb-record` utility
BBB_RECORDINGS_CONTAINER_NAME=$(docker ps --filter "name=recordings" --filter "status=running" --format "{{.Names}}")
if [ $BBB_RECORDINGS_CONTAINER_NAME == "" ]; then
  echo "$(date --rfc-3339=seconds) ERROR: recordings container is not running" >>"${LOGFILE}"
  exit 1
fi

for donefile in /var/bigbluebutton/recording/status/published/*-presentation.done ; do
        MTIME=$(stat -c %Y "${donefile}")
        # Check the age of the recording
        if [ $(( ( $NOW - $MTIME ) / 86400 )) -gt $RECORDING_MAX_AGE_DAYS ]; then
                MEETING_ID=$(basename "${donefile}")
                MEETING_ID=${MEETING_ID%-presentation.done}
                echo "${MEETING_ID}" >> "${LOGFILE}"

                docker exec "$BBB_RECORDINGS_CONTAINER_NAME" bbb-record --delete "${MEETING_ID}" >>"${LOGFILE}"
        fi
done

for eventsfile in /var/bigbluebutton/recording/raw/*/events.xml ; do
        MTIME=$(stat -c %Y "${eventsfile}")
        # Check the age of the recording
        if [ $(( ( $NOW - $MTIME ) / 86400 )) -gt $RECORDING_MAX_AGE_DAYS ]; then
                MEETING_ID="${eventsfile%/events.xml}"
                MEETING_ID="${MEETING_ID##*/}"
                echo "${MEETING_ID}" >> "${LOGFILE}"

                docker exec "$BBB_RECORDINGS_CONTAINER_NAME" bbb-record --delete "${MEETING_ID}" >>"${LOGFILE}"
        fi
done
