#!/bin/bash
set -uo pipefail

# Installs Google Chrome from Google's own APT repository.
#
# Chrome is not in Debian, and a classroom is not usable without it, so
# a fresh machine provisions it itself rather than waiting for someone to
# install it by hand on every box. Using the repository rather than a
# one-off .deb means Chrome keeps getting security updates.
#
#   sudo classroom-chrome-setup
#
# Idempotent: once Chrome is installed this returns immediately.

KEYRING=/etc/apt/keyrings/google-chrome.gpg

# The same path Google's own package manages, so the two cannot end up
# as two copies of the same repository.
LIST=/etc/apt/sources.list.d/google-chrome.list

REPOSITORY="https://dl.google.com/linux/chrome/deb/"
KEY_URL="https://dl.google.com/linux/linux_signing_key.pub"

log() {
    echo "[classroom-chrome-setup] $1"
}

if command -v google-chrome >/dev/null 2>&1; then
    log "Google Chrome is already installed; nothing to do"
    exit 0
fi

if [[ "$(id -u)" -ne 0 ]]; then
    log "must be run as root: sudo classroom-chrome-setup"
    exit 1
fi

install -d -m 0755 /etc/apt/keyrings

if [[ ! -s "$KEYRING" ]]; then
    log "fetching Google's signing key"

    if ! curl -fsS --retry 3 --max-time 60 "$KEY_URL" |
            gpg --dearmor --batch --yes --output "$KEYRING.new"; then
        rm -f "$KEYRING.new"
        log "could not fetch Google's signing key; is this machine online?"
        exit 1
    fi

    chmod 0644 "$KEYRING.new"
    mv "$KEYRING.new" "$KEYRING"
fi

# Google's own package migrates whatever we write here into a deb822
# /etc/apt/sources.list.d/google-chrome.sources of its own, so look for
# the repository everywhere rather than only in the file we would write.
# Otherwise a machine that has had Chrome removed would end up with two
# copies of the same repository.
if ! grep -rqsF "dl.google.com/linux/chrome" \
        /etc/apt/sources.list /etc/apt/sources.list.d/; then
    log "adding the Google Chrome repository"
    printf 'deb [arch=amd64 signed-by=%s] %s stable main\n' \
        "$KEYRING" "$REPOSITORY" > "$LIST"
    chmod 0644 "$LIST"
else
    log "the Google Chrome repository is already configured"
fi

export DEBIAN_FRONTEND=noninteractive

# The OTA install or the update timer may hold the lock; wait it out
# rather than failing the whole provisioning run.
APT=(apt-get -o DPkg::Lock::Timeout=600)

log "updating package lists"

if ! "${APT[@]}" update; then
    log "apt-get update failed; is this machine online?"
    exit 1
fi

log "installing google-chrome-stable"

if ! "${APT[@]}" install -y google-chrome-stable; then
    log "could not install Google Chrome"
    exit 1
fi

log "Google Chrome installed"
