#!/bin/sh
set -e

J2F_DIRLIST="/etc/json2file-go/dirlist"

HOST_NAME="localhost"
SUBJECT="/CN=$HOST_NAME/"

TLS_DIR="/etc/json2file-go/tls"
CERTFILE="$TLS_DIR/${HOST_NAME}.crt"
KEYFILE="$TLS_DIR/${HOST_NAME}.key"

mkcert() {
	[ -d "$TLS_DIR" ] || mkdir "$TLS_DIR"
	cd "$TLS_DIR"
	openssl req -text -x509 -nodes -days 3650 -newkey rsa:2048 \
				-subj "$SUBJECT" -keyout "$KEYFILE" -out "$CERTFILE"
	chmod 0440 "$KEYFILE"
	chmod 0444 "$CERTFILE"
	chown -R www-data: "$TLS_DIR"
}

override_socket() {
	cat > /etc/systemd/system/json2file-go.socket.d/override.conf << EOF
[Socket]
ListenStream=
ListenStream=443
EOF
}

if [ ! -f "$J2F_DIRLIST" ]; then
	cat << EOF
The '$J2F_DIRLIST' does not exist, you can create a simple one doing:

  echo ':' > $J2F_DIRLIST

Exiting now!
EOF
	exit 0
fi
if [ -f "$CERTFILE" ] && [ -f "$KEYFILE" ]; then
	echo "The TLS files already exist, skipping certificate creation."
else
	mkcert
fi
echo "$CERTFILE" > /etc/json2file-go/certfile
echo "$KEYFILE" > /etc/json2file-go/keyfile

override_socket
service json2file-go restart
