#!/bin/sh

set -eu

PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH

ROOT_LABEL_PREFIX=${FORGEOS_ROOT_LABEL:-FORGE_ROOT}
APP_LABEL=${FORGEOS_APP_LABEL:-FORGE_APPS}
DD_BS=${FORGEOS_ROLLBACK_BS:-16M}
ASSUME_YES=0
FORCE_RW_SOURCE=0
VERSION=2026.06.18.9

usage() {
    cat <<'EOF'
Usage:
  forgeos-rollback status
  forgeos-rollback create [ROLLBACK_SLOT]
  forgeos-rollback promote [CURRENT_SLOT]
  forgeos-rollback relabel [SLOT]
  forgeos-rollback version

Options:
  --yes                   Do not prompt before copying a base slot.
  --force-rw-source       Allow copying from a read-write mounted root.

Slots:
  root                    Current base slot.
  root-rollback           First rollback slot.
  root-rollback-N         Additional rollback slot.
  0, 1, 2...              Numeric aliases for the same slots.

Examples:
  forgeos-rollback status
  forgeos-rollback create
  forgeos-rollback promote
EOF
}

die() {
    printf 'error: %s\n' "$*" >&2
    exit 1
}

warn() {
    printf 'warning: %s\n' "$*" >&2
}

show_device_diagnostics() {
    local current
    local current_slot
    local selected_arg
    local selected_slot
    local path
    local dev

    current=$(current_root_device 2>/dev/null || true)
    current_slot=unknown
    if [ -n "$current" ]; then
        current_slot=$(slot_for_device "$current" 2>/dev/null || true)
        [ -n "$current_slot" ] || current_slot=unknown
    fi

    selected_arg=$(selected_root_spec 2>/dev/null || true)
    selected_slot=unknown
    if [ -n "$selected_arg" ]; then
        selected_slot=$(slot_from_root_spec "$selected_arg" 2>/dev/null || true)
        [ -n "$selected_slot" ] || selected_slot=unknown
    fi

    printf 'Current boot slot: %s\n' "$current_slot" >&2
    printf 'Selected boot slot: %s\n' "$selected_slot" >&2
    printf 'Selected root arg: %s\n' "${selected_arg:-unknown}" >&2
    printf 'Current root device: %s\n' "${current:-unknown}" >&2
    printf 'Slot symlinks:\n' >&2
    for path in \
        /dev/disk/by-partlabel/root \
        /dev/disk/by-partlabel/root-rollback \
        /dev/disk/by-partlabel/root-rollback-*; do
        [ -e "$path" ] || continue
        printf '  %s -> %s\n' "$path" "$(real_device "$path")" >&2
    done
    printf 'Detected ForgeOS base partitions:\n' >&2
    device_candidates | while IFS= read -r dev; do
        case "$(partition_partlabel "$dev")" in
            root|root-rollback|root-rollback-*)
                printf '  %s: %s\n' "$dev" "$(blkid "$dev" 2>/dev/null || true)" >&2
                ;;
        esac
    done
}

die_same_slot() {
    local src_slot=$1
    local dst_slot=$2
    local src=$3
    local dst=$4

    printf 'error: source and destination resolve to the same block device\n' >&2
    printf '  source slot:      %s -> %s\n' "$src_slot" "$(real_device "$src")" >&2
    printf '  destination slot: %s -> %s\n' "$dst_slot" "$(real_device "$dst")" >&2
    show_device_diagnostics

    if [ "$src_slot" = "$dst_slot" ] && [ "$src_slot" != "root" ]; then
        printf "hint: you are already booted from %s; run 'forgeos-rollback promote' to copy it back to root.\n" "$src_slot" >&2
    else
        printf "hint: check for duplicate or stale GPT partition labels with 'ls -l /dev/disk/by-partlabel' and 'blkid'.\n" >&2
    fi

    exit 1
}

need_root() {
    [ "$(id -u 2>/dev/null || echo 1)" = "0" ] || die "must run as root"
}

cmdline_value() {
    local key=$1
    local arg
    local value=

    for arg in $(cat /proc/cmdline 2>/dev/null); do
        case "$arg" in
            "$key="*)
                value=${arg#*=}
                ;;
        esac
    done

    [ -n "$value" ] || return 1
    printf '%s\n' "$value"
}

real_device() {
    readlink -f "$1" 2>/dev/null || printf '%s\n' "$1"
}

same_device() {
    local a=$1
    local b=$2
    local aid
    local bid

    [ -b "$a" ] || return 1
    [ -b "$b" ] || return 1

    aid=$(block_device_id "$a" 2>/dev/null || true)
    bid=$(block_device_id "$b" 2>/dev/null || true)
    [ -n "$aid" ] && [ -n "$bid" ] && [ "$aid" = "$bid" ]
}

block_device_id() {
    local dev=$1
    local name
    local sys_dev
    local stat_dev

    name=$(basename "$(real_device "$dev")")
    sys_dev=/sys/class/block/$name/dev
    if [ -r "$sys_dev" ]; then
        cat "$sys_dev"
        return 0
    fi

    stat_dev=$(stat -c '%t:%T' "$dev" 2>/dev/null || true)
    case "$stat_dev" in
        ''|0:0)
            return 1
            ;;
    esac
    printf '%s\n' "$stat_dev"
}

device_candidates() {
    local dev

    for dev in \
        /dev/nvme[0-9]n[0-9]p[0-9] \
        /dev/sd[a-z][0-9] \
        /dev/mmcblk[0-9]p[0-9] \
        /dev/vd[a-z][0-9]; do
        [ -b "$dev" ] || continue
        printf '%s\n' "$dev"
    done
}

blkid_value() {
    local dev=$1
    local key=$2

    blkid "$dev" 2>/dev/null | sed -n "s/.* ${key}=\"\\([^\"]*\\)\".*/\\1/p" | head -n 1
}

partition_partlabel() {
    blkid_value "$1" PARTLABEL
}

partition_label() {
    blkid_value "$1" LABEL
}

is_forgeos_system() {
    grep -qx 'ID=forgeos' /etc/os-release 2>/dev/null || [ -f /etc/forgeos-nix ]
}

current_root_device_from_mountinfo() {
    local devnum
    local sys_path
    local block_name
    local dev

    devnum=$(awk '$5 == "/" { print $3; exit }' /proc/self/mountinfo 2>/dev/null || true)
    [ -n "$devnum" ] || return 1

    sys_path=/sys/dev/block/$devnum
    [ -e "$sys_path" ] || return 1

    block_name=$(basename "$(readlink -f "$sys_path" 2>/dev/null || true)")
    [ -n "$block_name" ] || return 1

    dev=/dev/$block_name
    [ -b "$dev" ] || return 1
    printf '%s\n' "$dev"
}

block_name_for_device() {
    basename "$(real_device "$1")"
}

partition_number_for_device() {
    local name
    local path

    name=$(block_name_for_device "$1")
    path=/sys/class/block/$name/partition
    [ -r "$path" ] || return 1
    cat "$path"
}

parent_block_name_for_device() {
    local name
    local real_sys

    name=$(block_name_for_device "$1")
    real_sys=$(readlink -f "/sys/class/block/$name" 2>/dev/null || true)
    [ -n "$real_sys" ] || return 1
    [ -r "/sys/class/block/$name/partition" ] || return 1
    basename "$(dirname "$real_sys")"
}

partition_path_for_number() {
    local parent=$1
    local number=$2
    local path

    case "$parent" in
        *[0-9])
            path="/dev/${parent}p${number}"
            ;;
        *)
            path="/dev/${parent}${number}"
            ;;
    esac

    [ -b "$path" ] || return 1
    printf '%s\n' "$path"
}

slot_from_partition_number() {
    local number=$1

    case "$number" in
        ''|*[!0-9]*)
            return 1
            ;;
    esac

    [ "$number" -ge 2 ] || return 1
    if [ "$number" = "2" ]; then
        printf 'root\n'
    elif [ "$number" = "3" ]; then
        printf 'root-rollback\n'
    else
        printf 'root-rollback-%s\n' "$((number - 2))"
    fi
}

slot_device_by_layout() {
    local slot=$1
    local current
    local parent
    local slot_num
    local part_num
    local dev

    is_forgeos_system || return 1

    current=$(current_root_device_from_mountinfo 2>/dev/null || true)
    [ -n "$current" ] || return 1

    parent=$(parent_block_name_for_device "$current" 2>/dev/null || true)
    [ -n "$parent" ] || return 1

    slot_num=$(slot_number "$slot")
    part_num=$((slot_num + 2))
    dev=$(partition_path_for_number "$parent" "$part_num" 2>/dev/null || true)
    [ -n "$dev" ] || return 1

    [ "$(partition_label "$dev")" != "$APP_LABEL" ] || return 1
    printf '%s\n' "$dev"
}

normalize_slot() {
    local slot=${1:-root-rollback}
    local n

    case "$slot" in
        current|primary|root|0)
            printf 'root\n'
            ;;
        rollback|root-rollback|1)
            printf 'root-rollback\n'
            ;;
        root-rollback-*)
            n=${slot#root-rollback-}
            case "$n" in
                ''|*[!0-9]*)
                    die "invalid rollback slot: $slot"
                    ;;
            esac
            printf '%s\n' "$slot"
            ;;
        *[!0-9]*)
            die "invalid slot: $slot"
            ;;
        *)
            [ "$slot" -gt 1 ] || die "invalid slot: $slot"
            printf 'root-rollback-%s\n' "$slot"
            ;;
    esac
}

slot_number() {
    local slot=$1
    local n

    case "$slot" in
        root)
            printf '0\n'
            ;;
        root-rollback)
            printf '1\n'
            ;;
        root-rollback-*)
            n=${slot#root-rollback-}
            case "$n" in
                ''|*[!0-9]*)
                    die "invalid rollback slot: $slot"
                    ;;
            esac
            printf '%s\n' "$n"
            ;;
        *)
            die "invalid slot: $slot"
            ;;
    esac
}

slot_fs_label() {
    local slot=$1
    local n

    n=$(slot_number "$slot")
    if [ "$n" = "0" ]; then
        printf '%s\n' "$ROOT_LABEL_PREFIX"
    else
        printf '%s_%s\n' "$ROOT_LABEL_PREFIX" "$n"
    fi
}

slot_device() {
    local slot
    local path
    local dev
    local actual

    slot=$(normalize_slot "${1:-root-rollback}")
    path="/dev/disk/by-partlabel/$slot"
    if [ -b "$path" ] && [ "$(partition_partlabel "$path")" = "$slot" ]; then
        printf '%s\n' "$path"
        return 0
    fi

    while IFS= read -r dev; do
        [ "$(partition_partlabel "$dev")" = "$slot" ] || continue
        printf '%s\n' "$dev"
        return 0
    done <<EOF
$(device_candidates)
EOF

    dev=$(slot_device_by_layout "$slot" 2>/dev/null || true)
    if [ -n "$dev" ]; then
        printf '%s\n' "$dev"
        return 0
    fi

    if [ -b "$path" ]; then
        actual=$(partition_partlabel "$path")
        if [ -n "$actual" ] && [ "$actual" != "$slot" ]; then
            die "slot $slot exists at $path but blkid reports PARTLABEL='$actual'; run 'partprobe' or reboot to refresh partition labels"
        fi
        printf '%s\n' "$path"
        return 0
    fi

    die "missing rollback slot $slot"
}

resolve_root_spec() {
    local spec=$1
    local kind
    local value
    local path

    case "$spec" in
        PARTLABEL=*)
            kind=partlabel
            value=${spec#PARTLABEL=}
            case "$value" in
                root|root-rollback|root-rollback-*)
                    slot_device "$value"
                    return $?
                    ;;
            esac
            ;;
        LABEL=*)
            kind=label
            value=${spec#LABEL=}
            ;;
        UUID=*)
            kind=uuid
            value=${spec#UUID=}
            ;;
        PARTUUID=*)
            kind=partuuid
            value=${spec#PARTUUID=}
            ;;
        /dev/*)
            [ -b "$spec" ] || return 1
            printf '%s\n' "$spec"
            return 0
            ;;
        *)
            return 1
            ;;
    esac

    path="/dev/disk/by-$kind/$value"
    [ -b "$path" ] || return 1
    printf '%s\n' "$path"
}

mount_source() {
    awk '$2 == "/" { print $1; exit }' /proc/mounts 2>/dev/null
}

mount_options() {
    awk '$2 == "/" { print $4; exit }' /proc/mounts 2>/dev/null
}

current_root_device() {
    local spec
    local dev
    local src

    dev=$(current_root_device_from_mountinfo 2>/dev/null || true)
    if [ -n "$dev" ]; then
        printf '%s\n' "$dev"
        return 0
    fi

    spec=$(cmdline_value forgeos.root 2>/dev/null || true)
    if [ -z "$spec" ]; then
        spec=$(cmdline_value root 2>/dev/null || true)
    fi
    if [ -n "$spec" ]; then
        dev=$(resolve_root_spec "$spec" 2>/dev/null || true)
        if [ -n "$dev" ]; then
            printf '%s\n' "$dev"
            return 0
        fi
    fi

    src=$(mount_source)
    [ -n "$src" ] || return 1
    printf '%s\n' "$src"
}

selected_root_spec() {
    local spec

    spec=$(cmdline_value forgeos.root 2>/dev/null || true)
    if [ -z "$spec" ]; then
        spec=$(cmdline_value root 2>/dev/null || true)
    fi

    case "$spec" in
        ''|rootfs|tmpfs)
            return 1
            ;;
    esac

    printf '%s\n' "$spec"
}

slot_from_root_spec() {
    local spec=$1
    local value
    local dev

    case "$spec" in
        PARTLABEL=*)
            value=${spec#PARTLABEL=}
            case "$value" in
                root|root-rollback|root-rollback-*)
                    normalize_slot "$value"
                    return 0
                    ;;
            esac
            ;;
    esac

    dev=$(resolve_root_spec "$spec" 2>/dev/null || true)
    [ -n "$dev" ] || return 1
    slot_for_device "$dev"
}

selected_boot_slot() {
    local spec

    spec=$(selected_root_spec 2>/dev/null || true)
    [ -n "$spec" ] || return 1
    slot_from_root_spec "$spec"
}

slot_for_current_root() {
    local current
    local slot
    local selected

    current=$(current_root_device 2>/dev/null || true)
    if [ -n "$current" ]; then
        slot=$(slot_for_device "$current" 2>/dev/null || true)
        if [ -n "$slot" ]; then
            printf '%s\n' "$slot"
            return 0
        fi
    fi

    selected=$(selected_boot_slot 2>/dev/null || true)
    if [ -n "$selected" ]; then
        warn "mounted root device could not be classified; using selected boot slot '$selected' from kernel command line"
        printf '%s\n' "$selected"
        return 0
    fi

    return 1
}

is_initramfs_root() {
    case "$(mount_source 2>/dev/null || true)" in
        rootfs|tmpfs)
            return 0
            ;;
    esac

    return 1
}

recovery_promote_slot() {
    local dst_slot=$1

    [ "$dst_slot" = "root" ] || return 1
    is_initramfs_root || return 1
    [ -b /dev/disk/by-partlabel/root ] || return 1
    [ -b /dev/disk/by-partlabel/root-rollback ] || return 1

    warn "running from initramfs/rootfs; using root-rollback as promotion source"
    printf 'root-rollback\n'
}

die_unknown_current_slot() {
    printf 'error: current root is not a known ForgeOS base slot\n' >&2
    show_device_diagnostics
    exit 1
}

slot_for_device() {
    local dev=$1
    local path
    local slot
    local part_num

    slot=$(partition_partlabel "$dev")
    case "$slot" in
        root|root-rollback|root-rollback-*)
            printf '%s\n' "$slot"
            return 0
            ;;
    esac

    part_num=$(partition_number_for_device "$dev" 2>/dev/null || true)
    if is_forgeos_system && [ -n "$part_num" ] && [ "$(partition_label "$dev")" != "$APP_LABEL" ]; then
        slot=$(slot_from_partition_number "$part_num" 2>/dev/null || true)
        if [ -n "$slot" ]; then
            printf '%s\n' "$slot"
            return 0
        fi
    fi

    for path in \
        /dev/disk/by-partlabel/root \
        /dev/disk/by-partlabel/root-rollback \
        /dev/disk/by-partlabel/root-rollback-*; do
        [ -b "$path" ] || continue
        same_device "$dev" "$path" || continue
        slot=${path##*/}
        printf '%s\n' "$slot"
        return 0
    done

    return 1
}

is_root_read_only() {
    local opts

    opts=$(mount_options)
    case ",$opts," in
        *,ro,*)
            return 0
            ;;
    esac

    return 1
}

is_device_mounted() {
    local dev=$1
    local src
    local target
    local _fstype
    local _opts
    local _rest

    while read -r src target _fstype _opts _rest; do
        case "$src" in
            /dev/*)
                [ -b "$src" ] || continue
                same_device "$src" "$dev" && return 0
                ;;
        esac
    done < /proc/mounts

    return 1
}

mountpoints_for_device() {
    local dev=$1
    local src
    local target
    local _fstype
    local _opts
    local _rest
    local sep=
    local found=0

    while read -r src target _fstype _opts _rest; do
        case "$src" in
            /dev/*)
                [ -b "$src" ] || continue
                same_device "$src" "$dev" || continue
                printf '%s%s' "$sep" "$target"
                sep=,
                found=1
                ;;
        esac
    done < /proc/mounts

    [ "$found" -eq 1 ] || printf '-'
}

bytes_to_mib() {
    local bytes=$1

    case "$bytes" in
        ''|*[!0-9]*)
            printf '-'
            ;;
        *)
            printf '%sMiB' "$((bytes / 1024 / 1024))"
            ;;
    esac
}

slot_paths() {
    local dev
    local path
    local found=0
    local current
    local parent
    local number
    local label

    while IFS= read -r dev; do
        case "$(partition_partlabel "$dev")" in
            root|root-rollback|root-rollback-*)
                printf '%s\n' "$dev"
                found=1
                ;;
        esac
    done <<EOF
$(device_candidates)
EOF

    for path in \
        /dev/disk/by-partlabel/root \
        /dev/disk/by-partlabel/root-rollback \
        /dev/disk/by-partlabel/root-rollback-*; do
        [ -b "$path" ] || continue
        [ -n "$(partition_partlabel "$path")" ] && continue
        printf '%s\n' "$path"
        found=1
    done

    [ "$found" -eq 1 ] && return 0
    is_forgeos_system || return 0

    current=$(current_root_device_from_mountinfo 2>/dev/null || true)
    [ -n "$current" ] || return 0
    parent=$(parent_block_name_for_device "$current" 2>/dev/null || true)
    [ -n "$parent" ] || return 0

    number=2
    while :; do
        dev=$(partition_path_for_number "$parent" "$number" 2>/dev/null || true)
        [ -n "$dev" ] || break
        label=$(partition_label "$dev")
        [ "$label" = "$APP_LABEL" ] && break
        slot_from_partition_number "$number" >/dev/null 2>&1 && printf '%s\n' "$dev"
        number=$((number + 1))
    done
}

show_status() {
    local current
    local current_slot
    local root_arg
    local forgeos_arg
    local selected_arg
    local selected_dev
    local selected_slot
    local path
    local slot
    local dev
    local marker
    local size
    local mounts
    local info

    current=$(current_root_device 2>/dev/null || true)
    current_slot=unknown
    if [ -n "$current" ]; then
        current_slot=$(slot_for_device "$current" 2>/dev/null || true)
        [ -n "$current_slot" ] || current_slot=unknown
    fi

    root_arg=$(cmdline_value root 2>/dev/null || true)
    forgeos_arg=$(cmdline_value forgeos.root 2>/dev/null || true)
    selected_arg=$(selected_root_spec 2>/dev/null || true)
    selected_slot=unknown
    if [ -n "$selected_arg" ]; then
        selected_slot=$(slot_from_root_spec "$selected_arg" 2>/dev/null || true)
        [ -n "$selected_slot" ] || selected_slot=unknown
    fi

    printf 'ForgeOS rollback slots\n'
    printf 'Command version: %s\n' "$VERSION"
    printf 'Current boot slot: %s\n' "$current_slot"
    printf 'Selected boot slot: %s\n' "$selected_slot"
    printf 'Selected root arg: %s\n' "${selected_arg:-unknown}"
    printf 'Mounted root device: %s\n' "${current:-unknown}"
    printf '%-2s %-18s %-16s %-12s %-12s %s\n' '' SLOT DEVICE SIZE MOUNTED BLKID

    slot_paths | while IFS= read -r path; do
        slot=$(slot_for_device "$path" 2>/dev/null || true)
        [ -n "$slot" ] || slot=$(partition_partlabel "$path")
        [ -n "$slot" ] || slot=${path##*/}
        dev=$(real_device "$path")
        marker=' '
        if [ -n "$current" ] && same_device "$current" "$path"; then
            marker='*'
        fi
        size=$(blockdev --getsize64 "$path" 2>/dev/null || true)
        mounts=$(mountpoints_for_device "$path")
        info=$(blkid "$path" 2>/dev/null || true)
        printf '%-2s %-18s %-16s %-12s %-12s %s\n' \
            "$marker" "$slot" "$dev" "$(bytes_to_mib "$size")" "$mounts" "$info"
    done

    printf '\n* marks the slot backing the currently booted root filesystem.\n'
}

confirm_copy() {
    local src_slot=$1
    local dst_slot=$2
    local src=$3
    local dst=$4
    local reply

    [ "$ASSUME_YES" -eq 1 ] && return 0

    cat >&2 <<EOF
About to overwrite $dst_slot from $src_slot.
  source:      $(real_device "$src")
  destination: $(real_device "$dst")
Type COPY to continue:
EOF
    read -r reply
    [ "$reply" = "COPY" ] || die "aborted"
}

relabel_slot() {
    local slot=$1
    local dev
    local label

    slot=$(normalize_slot "$slot")
    dev=$(slot_device "$slot")
    label=$(slot_fs_label "$slot")

    if ! command -v tune2fs >/dev/null 2>&1; then
        warn "tune2fs is unavailable; $slot may retain the source filesystem UUID and label"
        warn "boot selection uses GPT PARTLABEL, but install e2fsprogs and run: forgeos-rollback relabel $slot"
        return 0
    fi

    if is_device_mounted "$dev"; then
        die "refusing to relabel mounted slot $slot"
    fi

    tune2fs -U random -L "$label" "$dev" >/dev/null
    blkid "$dev" 2>/dev/null || true
}

copy_slot() {
    local src_slot=$1
    local dst_slot=$2
    local src
    local dst
    local src_size
    local dst_size
    local current
    local current_slot

    need_root

    src_slot=$(normalize_slot "$src_slot")
    dst_slot=$(normalize_slot "$dst_slot")
    src=$(slot_device "$src_slot")
    dst=$(slot_device "$dst_slot")

    same_device "$src" "$dst" && die_same_slot "$src_slot" "$dst_slot" "$src" "$dst"
    is_device_mounted "$dst" && die "refusing to overwrite mounted slot $dst_slot"

    src_size=$(blockdev --getsize64 "$src")
    dst_size=$(blockdev --getsize64 "$dst")
    [ "$dst_size" -ge "$src_size" ] || die "$dst_slot is smaller than $src_slot"

    current=$(current_root_device 2>/dev/null || true)
    current_slot=
    if [ -n "$current" ]; then
        current_slot=$(slot_for_device "$current" 2>/dev/null || true)
    fi

    if [ "$FORCE_RW_SOURCE" -ne 1 ] && [ "$src_slot" = "$current_slot" ] && ! is_root_read_only; then
        die "root is mounted read-write; remount read-only or rerun with --force-rw-source"
    fi

    confirm_copy "$src_slot" "$dst_slot" "$src" "$dst"

    sync
    dd if="$src" of="$dst" bs="$DD_BS" iflag=fullblock conv=fsync
    sync
    relabel_slot "$dst_slot"
    sync
}

create_rollback() {
    local dst_slot=${1:-root-rollback}
    local src_slot

    dst_slot=$(normalize_slot "$dst_slot")
    src_slot=$(slot_for_current_root || true)
    [ -n "$src_slot" ] || die_unknown_current_slot

    if [ "$src_slot" = "$dst_slot" ]; then
        if [ "$src_slot" = "root" ]; then
            die "cannot create a rollback by copying root to itself; choose an inactive rollback slot"
        fi
        die "currently booted from $src_slot; run 'forgeos-rollback promote' to make it the current root, or choose a different inactive rollback slot"
    fi

    copy_slot "$src_slot" "$dst_slot"
}

promote_current() {
    local dst_slot=${1:-root}
    local src_slot

    dst_slot=$(normalize_slot "$dst_slot")
    src_slot=$(slot_for_current_root || true)
    if [ -z "$src_slot" ]; then
        src_slot=$(recovery_promote_slot "$dst_slot" || true)
    fi
    [ -n "$src_slot" ] || die_unknown_current_slot
    [ "$src_slot" != "root" ] || die "boot a rollback slot before promoting it to root"

    copy_slot "$src_slot" "$dst_slot"
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        --yes|-y)
            ASSUME_YES=1
            shift
            ;;
        --force-rw-source)
            FORCE_RW_SOURCE=1
            shift
            ;;
        --help|-h)
            usage
            exit 0
            ;;
        *)
            break
            ;;
    esac
done

cmd=${1:-status}
[ "$#" -eq 0 ] || shift

case "$cmd" in
    status|list)
        show_status
        ;;
    create)
        create_rollback "${1:-root-rollback}"
        ;;
    promote)
        promote_current "${1:-root}"
        ;;
    relabel)
        need_root
        relabel_slot "${1:-root-rollback}"
        ;;
    version)
        printf '%s\n' "$VERSION"
        ;;
    help)
        usage
        ;;
    *)
        usage >&2
        exit 2
        ;;
esac
