#!/bin/sh
# gotd(8) and gotwebd(8) behind httpd(8), run once as puffy on the first boot:
#   ssh chroot.dev new -n gotd -w -s /dev/stdin < gotd-setup.sh
set -e

# another mirror while the -current package snapshot is syncing, see new(1)
doas pkg_add -I got gotd gotwebd ||
    doas env PKG_PATH=https://ftp.openbsd.org/pub/OpenBSD/snapshots/packages/amd64/ \
    pkg_add -I got gotd gotwebd

# git user with gotsh(1) as its shell and the account's keys
grep -q gotsh /etc/shells || echo /usr/local/bin/gotsh | doas tee -a /etc/shells >/dev/null
doas useradd -m -s /usr/local/bin/gotsh git
doas install -d -o git -g git -m 700 /home/git/.ssh
doas install -o git -g git -m 600 ~/.ssh/authorized_keys /home/git/.ssh/authorized_keys

# repository with a first commit
src=$(mktemp -d)
printf '# hello\n\nServed by gotd(8) and gotwebd(8) on an OpenBSD VM.\n' >$src/README.md
printf '#include <stdio.h>\n\nint\nmain(void)\n{\n\tputs("hello");\n\treturn 0;\n}\n' >$src/hello.c
chmod -R a+rX $src
doas install -d -o _gotd -g _gotd -m 755 /var/git
doas -u _gotd gotadmin init -b main /var/git/hello.git
doas -u _gotd env GOT_AUTHOR="puffy <puffy@chroot.dev>" \
    got import -r /var/git/hello.git -b main -m "initial import" $src >/dev/null
echo "hello: a tiny C program, served by gotd" |
    doas -u _gotd tee /var/git/hello.git/description >/dev/null
rm -rf $src

doas tee /etc/gotd.conf >/dev/null <<EOT
repository "hello" {
	path "/var/git/hello.git"
	permit rw git
}
EOT
doas chmod 600 /etc/gotd.conf

doas tee /etc/gotwebd.conf >/dev/null <<EOT
server "localhost" {
	site_name	"gotd on chroot.dev"
	site_owner	"puffy"
	repos_path	"/var/git"
	show_repo_owner	off
}
EOT

doas tee /etc/httpd.conf >/dev/null <<EOT
types { include "/usr/share/misc/mime.types" }

server "*" {
	listen on * port 80
	location match "^/[^/]*%.[a-z]+$" { root "/htdocs/gotwebd" }
	location "/*" { fastcgi socket "/run/gotweb.sock" }
}
EOT

doas rcctl enable gotd gotwebd httpd
doas rcctl start gotd gotwebd httpd
