#!/usr/bin/env bash

set -xuo pipefail

image="ghcr.io/ublue-os/${1}"
unit="${2}"

cancel-rebase() {
    echo "Cancelling active transaction..."
    rpm-ostree cancel
    exit 1
}

trap cancel-rebase SIGTERM SIGINT

function send-notification {
    user_name=$(loginctl list-users -j | jq -r '.[] | select(.state == "active") | .user')
    uid=$(loginctl list-users -j | jq -r '.[] | select(.state == "active") | .uid')
         xdg_runtime_path="/run/user/$uid"
    sudo -u "$user_name" DBUS_SESSION_BUS_ADDRESS=unix:path="$xdg_runtime_path"/bus notify-send "$1" "$2" --app-name="Aurora Preferences" -u NORMAL --icon distributor-logo
}

send-notification "System Rebase" "Starting rebase to $1"

# Writing directly to /run/ublue-rebase causes weird non-atomic behavior when reading the file back with Qt
echo "$1 $unit" > /run/ublue-rebase.lock
mv /run/ublue-rebase.lock /run/ublue-rebase

if /usr/bin/grep "^LockLayering=true" /etc/rpm-ostreed.conf &> /dev/null; then
    bootc switch --enforce-container-sigpolicy "${image}"
    if [[ $? -ne 0 ]]; then
        send-notification "System Rebase" "Rebase failed. Check system settings for more details."
        exit 1
    fi
else
    rpm-ostree rebase ostree-image-signed:docker://"${image}"
    if [[ $? -ne 0 ]]; then
        send-notification "System Rebase" "Rebase failed. Check system settings for more details."
        exit 1
    fi
fi

send-notification "System Rebase" "Rebase completed. Please reboot to use the new image."