#!/bin/bash
set -e

../scripts/build-luan.sh

mkdir -p local
mkdir -p logs
rm -f logs/*
hg identify >logs/changeset.txt

if [ ! -f local/tiny_account.key ]; then
	echo "Register letsencrypt (tiny-acme)"
	openssl genrsa 4096 >local/tiny_account.key
fi

nginx_conf_dir=$(
	for d in \
		/usr/local/etc/nginx/servers \
		/etc/nginx/conf.d; do
		if [ -d "$d" ]; then
			echo "$d"
			break
		fi
	done
)

if [ -n "$nginx_conf_dir" ]; then
	echo "using nginx conf dir: $nginx_conf_dir"
else
	echo "ERROR: No nginx conf dir found.\nFind it and add it to update2.sh."
	exit 1
fi

# id -gn gets the name of the primary group of the current user (staff)
luan startup/nginx/nginx.conf.luan $(pwd) $nginx_conf_dir $(whoami) $(id -gn) | sudo tee $nginx_conf_dir/luanhost.conf >/dev/null
# DON'T put this in the auto-loaded configs dir,
# it is not meant to be loaded on its own.
luan startup/nginx/nginx.default.conf.luan $(pwd) >$(pwd)/local/luanhost.default.conf

# this is done because the nginx conf uses absolute paths
# and this breaks sites when the luan/host directory is moved
luan classpath:luan/host/update.luan

echo Starting...
./start.sh
