#!/bin/sh

set -e
DIR="/etc/routerich/certs"
DAYS=7300

pkg_installed() {
	for pkg in "$@"; do
		if command -v opkg >/dev/null 2>&1; then
			opkg list-installed 2>/dev/null | grep -qE "^$pkg " && return 0
		elif command -v apk >/dev/null 2>&1; then
			apk info 2>/dev/null | grep -qE "^$pkg$" && return 0
		fi
	done
	return 1
}

if ! pkg_installed openssl-util; then
	exit 0
fi

mkdir -p "$DIR"
cd "$DIR"

if [ -f ca.key ] && [ -f ca.crt ] && \
	[ -f server.key ] && [ -f server.crt ] && \
	[ -f client.key ] && [ -f client.crt ]; then
	exit 0
fi

openssl genrsa -out ca.key 2048 >/dev/null 2>&1
openssl req -new -x509 -days "$DAYS" -key ca.key -out ca.crt -subj "/C=RU/O=RouteRich/CN=RouteRich Root CA" -addext "basicConstraints=critical,CA:TRUE" >/dev/null 2>&1
openssl genrsa -out server.key 2048 >/dev/null 2>&1
openssl req -new -key server.key -out server.csr -subj "/C=RU/O=RouteRich/CN=192.168.1.1" >/dev/null 2>&1
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days "$DAYS" -sha256 >/dev/null 2>&1
openssl genrsa -out client.key 2048 >/dev/null 2>&1
openssl req -new -key client.key -out client.csr -subj "/C=RU/O=RouteRich/CN=rr-client" >/dev/null 2>&1
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days "$DAYS" -sha256 >/dev/null 2>&1

CLIENT_KEY="$DIR/client.key"
CLIENT_CRT="$DIR/client.crt"
CA_CRT="$DIR/ca.crt"
OUT_P12="$DIR/client.p12"

openssl pkcs12 -export \
	-in "$CLIENT_CRT" \
	-inkey "$CLIENT_KEY" \
	-certfile "$CA_CRT" \
	-out "$OUT_P12" \
	-name "ClientCert" \
	-passout pass:

chmod 644 "$DIR"/*
ln -s /etc/routerich/certs/client.p12 /www/client.p12
