#!/usr/bin/env bash

# TODO: assert correct system

NSPAWN_NAME=nixos-@hostname@
TARBALL=./nixos-@hostname@.tar.xz

test $(id -u) -eq 0 || {
  >&2 echo you must run this as root
  exit 1
}

if ! >/dev/null command -v systemd-nspawn; then
  >&2 echo "systemd-nspawn" not found in PATH
  >&2 echo consider installing 'systemd-container'
  exit 1
fi

if ! >/dev/null command -v machinectl; then
  >&2 echo "machinectl" not found in PATH
  >&2 echo consider installing 'systemd-container'
  exit 1
fi

set -ex

machinectl remove "$NSPAWN_NAME" || true # TODO: is this interactive?
#machinectl pull-tar "https://github.com/tfc/nspawn-nixos/releases/download/v1.0/nixos-system-x86_64-linux.tar.xz" "$NSPAWN_NAME" --verify=no
machinectl import-tar "$TARBALL" "$NSPAWN_NAME"

# TODO: get sandbox working
# https://wiki.archlinux.org/index.php?title=Systemd-nspawn&oldid=703843#Run_docker_in_systemd-nspawn
#[Files]
#Bind=/sys/fs/cgroup
#Bind=/proc
#[Exec]
#Capability=all
#SystemCallFilter=@known @priviledged
#SystemCallFilter=add_key keyctl bpf
#Parameters=systemd.legacy_systemd_cgroup_controller=yes
#Parameters=systemd.unified_cgroup_hierarchy=0
#PrivateUsers=no
#PrivateUsersOwnership=no

# use host network
mkdir -p /etc/systemd/nspawn
tee /etc/systemd/nspawn/"$NSPAWN_NAME".nspawn <<"EOF"
[Network]
VirtualEthernet=no
EOF

NSPAWN_NAME=nixos-brumlebasse
machinectl enable "$NSPAWN_NAME"
machinectl start "$NSPAWN_NAME"

echo Please set a root password
machinectl shell "$NSPAWN_NAME" /usr/bin/env passwd

machinectl status "$NSPAWN_NAME"
