#!/bin/sh
#
# public domain.
#

set -eu

#
# Tested on OpenBSD 7.2.
#

if test $(id -u) -ne 0; then
	echo "This script must be run as root."
	exit 1
fi

local default=/var/git
read CHROOT?"chroot install directory [$default]: "
: ${CHROOT:=$default}

# daemon seems like an appropriate group.
mkdir -p ${CHROOT}
chgrp daemon ${CHROOT}

# git-daemon requires /dev/null, create it
rm -f ${CHROOT}/dev/null
mkdir -p ${CHROOT}/dev
mknod -m 666 ${CHROOT}/dev/null c 3 2

# Check if nodev is a mount option
if grep var /etc/fstab | grep nodev; then
	echo "error: /var mount has 'nodev' option; this must be removed"
	echo "       Do not forget to remount the filesystem afterwards."
	exit 1
fi

#
# Copy dynamic library dependencies into CHROOT
# Knock off the first 2 lines of `ldd' output, field 7 contains the library
# path.
#
ldd /usr/local/libexec/git/git-daemon | tail -n +3 | awk '{ print $7 }' |
while read -r lib_path
do
	mkdir -p ${CHROOT}/$(dirname $lib_path)
	cp $lib_path ${CHROOT}/$lib_path
done

# Copy git binary for `upload-pack'.
git_bin=/usr/local/bin/git
mkdir -p ${CHROOT}/$(dirname $git_bin)
cp $git_bin ${CHROOT}/$git_bin

#
# Kinda tricky.. we want to substitute the CHROOT picked above into this diff,
# but not expand the other rc variables at this time.
#
cat - << EOF | patch -d /etc/rc.d
--- /etc/rc.d/gitdaemon.orig	Sat Jan 18 17:47:47 2020
+++ /etc/rc.d/gitdaemon	Sat Jan 18 17:33:42 2020
@@ -7,6 +7,10 @@

 . /etc/rc.d/rc.subr

+rc_start() {
+	chroot -u \${daemon_user} ${CHROOT} \${daemon} \${daemon_flags}
+} 
+
 pexp="/usr/local/libexec/git/git-daemon --detach\${daemon_flags:+ \${daemon_flags}}"
 rc_reload=NO
EOF
