#!/bin/bash
set -euo pipefail

# One-time bootstrap for encrypted (commercial) DVD-Video playback.
#
# Most retail DVDs are CSS encrypted. Debian cannot ship the decryption
# library, so libdvdcss has to be built on the machine from the contrib
# package libdvd-pkg. This is deliberately NOT run from the package
# postinst: it needs the network, it compiles a package, and it must not
# run while dpkg already holds the apt lock during an OTA update.
#
# Run this once, as root, on any classroom that needs commercial discs:
#
#     sudo classroom-dvd-css-setup
#
# Unencrypted discs (church curriculum, home-burned video) play without it.

if [[ "$(id -u)" -ne 0 ]]; then
    echo "classroom-dvd-css-setup must be run as root." >&2
    exit 1
fi

if [[ -e /usr/lib/x86_64-linux-gnu/libdvdcss.so.2 ]]; then
    echo "libdvdcss is already installed. Nothing to do."
    exit 0
fi

echo "Enabling the Debian contrib component..."

if ! grep -rqs 'contrib' /etc/apt/sources.list /etc/apt/sources.list.d/; then
    if [[ -f /etc/apt/sources.list.d/debian.sources ]]; then
        sed -i 's/^\(Components:.*\)$/\1 contrib/' \
            /etc/apt/sources.list.d/debian.sources
    else
        echo "Could not find a Debian sources file to add contrib to." >&2
        echo "Add 'contrib' manually and re-run this script." >&2
        exit 1
    fi
fi

echo "Installing libdvd-pkg..."

export DEBIAN_FRONTEND=noninteractive

apt-get update
apt-get install -y libdvd-pkg

echo "Building libdvdcss..."

# libdvd-pkg downloads and builds libdvdcss during reconfigure.
dpkg-reconfigure -f noninteractive libdvd-pkg

if [[ -e /usr/lib/x86_64-linux-gnu/libdvdcss.so.2 ]]; then
    echo
    echo "libdvdcss installed. Commercial DVDs should now play."
    echo "Test with an actual disc before relying on it."
else
    echo
    echo "libdvdcss was not installed. Commercial discs will not play." >&2
    exit 1
fi
