#!/bin/bash
# Starting a snapshot from the boot menu: the snapshot stays read-only, with a writable layer in memory on top, and
# the boot partition is mounted read-only, so an update run from the snapshot can't replace the normal system's
# kernel. Only acts when the command line has starchaser.snapshot= (the snapshot entries bootsnap.py writes).

build() {
    add_module overlay
    for binary in findmnt cp rm awk mkdir dirname mount umount cat; do
        add_binary "/usr/bin/$binary"
    done
    # Current identity precedes all snapshot services. Only this bounded list
    # goes into the RAM overlay; recovery exclusions can include huge data stores.
    # Includes current security-key mappings and fingerprint enrollment. Updating
    # this build hook forces mkinitcpio to replace images with the older list.
    add_file /usr/lib/initcpio/starchaser-snapshot-identity-list /etc/starchaser-snapshot-identity-list 644
    add_file /usr/lib/initcpio/starchaser-snapshot-identity /usr/bin/starchaser-snapshot-identity 755
    add_file /usr/lib/initcpio/starchaser-snapshot-fstab /usr/bin/starchaser-snapshot-fstab 755
    # HOOKS is the image's hook list (mkinitcpio sources its config before running each hook's build)
    if [[ " ${HOOKS[*]} " == *" systemd "* ]]; then
        # systemd's own overlay (systemd.volatile=overlay on a snapshot entry's command line). Only the program and its
        # unit go in: systemd-fstab-generator pulls the unit in by itself when systemd.volatile= is on the command line.
        # Never link it into a target here: the unit runs `systemd-volatile-root yes`, and with nothing on the command
        # line that argument decides, so every normal start would come up as an empty system in memory (v1.0.4-1).
        add_binary /usr/lib/systemd/systemd-volatile-root
        add_systemd_unit systemd-volatile-root.service
        add_file /usr/lib/initcpio/starchaser-snapshot.service /usr/lib/systemd/system/starchaser-snapshot.service 644
        add_symlink /usr/lib/systemd/system/initrd-root-fs.target.requires/starchaser-snapshot.service \
            ../starchaser-snapshot.service
    else
        add_runscript
    fi
}

help() {
    cat <<HELPEOF
Starts a snapshot chosen in the boot menu read-only, with changes kept in memory until the next restart.
HELPEOF
}
