#!/usr/bin/env bash

WATCH_DIR="/.snapshots"
BASE_CONFIG="/etc/limine-snapper-sync.conf"
DEFAULT_CONFIG="/etc/default/limine"
TMP_CONFIG="/tmp/limine-snapper-sync.conf"
SYNC_CMD=(limine-snapper-sync --no-force-save)

### Check if the script is being run with root privileges
require_root() {
    if ((EUID != 0)); then
        echo -e "\033[91m limine-snapper-watcher must be run with root privileges.\033[0m" >&2
        exit 1
    fi
}

### Check if you are not in Btrfs.
require_btrfs_root() {
    local fstype
    read -r fstype < <(findmnt --mountpoint / -no FSTYPE)
    if [[ "$fstype" != "btrfs" ]]; then
        echo -e "\033[91m Root filesystem is not Btrfs. limine-snapper-watcher stopped.\033[0m" >&2
        exit 0
    fi
}

is_btrfs_ro() {
    [[ $(btrfs property get / ro) == *true ]]
}

### Check if you are in snapshot
is_snapshot() {
    cmdline=$(</proc/cmdline)
    if [[ $cmdline =~ rootflags.*subvol=.*?/([0-9]+)/snapshot ]]; then
        return 0
    else
        return 1
    fi
}

copy_config_if_needed() {
    if is_btrfs_ro && is_snapshot && [[ ! -f "${TMP_CONFIG}" ]]; then
        if [[ -f "${DEFAULT_CONFIG}" ]]; then
            cp "${DEFAULT_CONFIG}" "${TMP_CONFIG}"
        elif [[ -f "${BASE_CONFIG}" ]]; then
            cp "${BASE_CONFIG}" "${TMP_CONFIG}"
        fi
    fi
}

### Remove pacman lock after restore for Arch Linux & Arch based distros
remove_pacman_lock() {
    if [[ -f /var/lib/pacman/db.lck ]]; then
        if ! pgrep -x pacman &>/dev/null; then
            rm /var/lib/pacman/db.lck
        fi
    fi
}

### Main logic
require_root
require_btrfs_root
copy_config_if_needed

if is_btrfs_ro; then
    echo -e "\033[91m You are in the read-only Btrfs. limine-snapper-watcher stopped.\033[0m" >&2
    exit 0
fi

if is_snapshot; then
    echo -e "\033[91m You are booted from the snapshot. limine-snapper-watcher stopped.\033[0m" >&2
    exit 0
fi

remove_pacman_lock

### Initial sync
if [ ! -d "$WATCH_DIR" ]; then
    echo "Directory $WATCH_DIR does not exist. limine-snapper-sync is triggered to initialize a snapper config for $WATCH_DIR."
    "${SYNC_CMD[@]}"
fi

### Monitoring the directory for creation or deletion events.
inotifywait -q -m -e create -e delete --format '%e|%f' "${WATCH_DIR}" | while IFS='|' read -r event snapID; do
    echo "[EVENT] $event -> $snapID"
    if [[ -e /run/limine-snapper-cleanup.lock ]]; then
        echo "[SKIP] Cleanup lock is active, skipping sync for snapshot ID: $snapID"
    else
        "${SYNC_CMD[@]}" &
    fi
done
