#!/usr/bin/env bash

set -o nounset -o errexit -o pipefail -o xtrace

if [[ $container == docker ]]
then
    # Mask tty0..tty6 systemd services, so they cannot be started.
    systemctl mask getty@tty0.service
    systemctl mask getty@tty1.service
    systemctl mask getty@tty2.service
    systemctl mask getty@tty3.service
    systemctl mask getty@tty4.service
    systemctl mask getty@tty5.service
    systemctl mask getty@tty6.service
    systemctl mask autovt@tty2.service
    systemctl enable getty@tty10.service

    mkdir -p /home/oleg/.config/systemd/user/default.target.wants
    ln -s /home/oleg/.config/systemd/user/foot.service /home/oleg/.config/systemd/user/default.target.wants/foot.service

    rm -vf /usr/lib/systemd/system/systemd-networkd*
    rm -vf /usr/lib/systemd/system/systemd-firstboot.service
    rm -vf /usr/lib/systemd/system/systemd-resolved.service

    passwd --delete root

    # Keyboard and mouse access are essential components for efficient operation
    # within the Sway window manager environment. Running 'udevadm trigger' will
    # grant access to the keyboard and mouse. You can verify their addition by
    # using 'libinput list-devices'."
    mount -o remount,rw /sys

    umount /sys/fs/cgroup
    mount -t cgroup2 -o rw,relatime,nsdelegate,memory_recursiveprot cgroup2 /sys/fs/cgroup

    if [[ -e /mnt/rootfs ]]
    then
        if (shopt -s nullglob; files=(/mnt/rootfs/*); [[ ${#files[@]} -eq 0 ]])
        then
            rsync --one-file-system --sparse --archive --hard-links --acls --xattrs --numeric-ids / /mnt/rootfs/
        else
            printf "\n/mnt/rootfs/ is not empty directory, skipping syncing files from '/' to '/mnt/rootfs/'." 1>&2
        fi
        mapfile -t targets < <(tail -n+2 "/proc/$$/mounts" | cut -d ' ' -f 2)
        for target in "${targets[@]}"
        do
            mount -o X-mount.mkdir --bind "$target" "/mnt/rootfs${target}"
        done
        exec -a /sbin/init chroot /mnt/rootfs /sbin/init
    else
        exec /sbin/init
    fi
else
    exec /bin/sleep infinity
fi
