#!/bin/sh

set -eu
umask 022

root=
if [ "$#" -ne 0 ]; then
    if [ "$#" -ne 2 ] || [ "$1" != "--root" ] || [ ! -d "$2" ]; then
        printf 'Usage: %s [--root DIRECTORY]\n' "$0" >&2
        exit 2
    fi
    root=$(realpath -e -- "$2")
    [ "$root" != / ] || root=
fi

if [ -z "$root" ] && [ "$(id -u)" -ne 0 ]; then
    printf 'rg-cnc-update-apt-sources: must be run as root\n' >&2
    exit 1
fi

if [ ! -f "$root/etc/os-release" ]; then
    printf 'rg-cnc-update-apt-sources: no os-release, skipping\n'
    exit 0
fi

ID= VERSION_ID= VERSION_CODENAME= DEBIAN_CODENAME=
. "$root/etc/os-release"
if [ "$ID" != linuxmint ] || [ "$VERSION_ID" != 5 ] ||
   [ "$VERSION_CODENAME" != elsie ] || [ "$DEBIAN_CODENAME" != bullseye ]; then
    printf 'rg-cnc-update-apt-sources: not LMDE 5 Elsie, skipping\n'
    exit 0
fi

template="$root/usr/share/rg-cnc-sysadj-lmde/official-package-repositories.list"
sources_dir="$root/etc/apt/sources.list.d"
sources="$sources_dir/official-package-repositories.list"
lock_dir="$root/run/rg-cnc-sysadj-lmde"

mkdir -p -- "$lock_dir"
exec 9>"$lock_dir/apt-sources.lock"
flock -x -w 30 9

if [ ! -f "$template" ]; then
    printf 'rg-cnc-update-apt-sources: template missing: %s\n' "$template" >&2
    exit 1
fi
if [ -L "$sources" ] || { [ -e "$sources" ] && [ ! -f "$sources" ]; }; then
    printf 'rg-cnc-update-apt-sources: not a regular file: %s\n' "$sources" >&2
    exit 1
fi
if [ -f "$sources" ] && cmp -s -- "$template" "$sources"; then
    exit 0
fi

mkdir -p -- "$sources_dir"
temporary=$(mktemp "$sources_dir/.rg-cnc-apt-sources.XXXXXXXX")
trap 'rm -f -- "$temporary"' 0
trap 'exit 1' HUP INT TERM
install -m 0644 -- "$template" "$temporary"
if [ "$(id -u)" -eq 0 ]; then
    chown 0:0 "$temporary"
fi

# Keep every replaced version outside sources.list.d so APT never reads backups.
if [ -f "$sources" ]; then
    backup_dir="$root/var/backups/rg-cnc-sysadj-lmde"
    install -d -m 0700 -- "$backup_dir"
    backup=$(mktemp "$backup_dir/official-package-repositories.list.XXXXXXXX")
    if ! cp -p -- "$sources" "$backup"; then
        rm -f -- "$backup"
        exit 1
    fi
    printf 'rg-cnc-update-apt-sources: previous file saved to %s\n' "$backup"
fi

mv -f -- "$temporary" "$sources"
printf 'rg-cnc-update-apt-sources: updated %s\n' "$sources"
