#!/bin/sh

# Super stupid and lazy way to chroot
# Borrow some stuff from https://github.com/alpinelinux/alpine-chroot-install

chroot_dir="{{ chroot_dir }}"

user='root'
if [ $# -ge 2 ] && [ "$1" = '-u' ]; then
    user="$2"; shift 2
fi

[ "$(id -u)" -eq 0 ] || _sudo='doas'

# Pre
$_sudo mount -t proc none "${chroot_dir}/proc"
$_sudo mount -o bind,ro /dev "${chroot_dir}/dev"
$_sudo mount -o bind,ro /sys "${chroot_dir}/sys"
$_sudo cp -L /etc/resolv.conf "${chroot_dir}/etc/"

# chroot
$_sudo chroot "${chroot_dir}" /usr/bin/env -i su -l "$user" \
    sh -c ". /etc/profile; \"\$@\"" \
    -- "${@:-sh}"

# Post
$_sudo umount -l "${chroot_dir}/dev"
$_sudo umount -l "${chroot_dir}/proc"
$_sudo umount -l "${chroot_dir}/sys"
