#!/usr/bin/env bash
set -euo pipefail

SITE=/etc/nginx/sites-available/omalled.com
SNIPPET=/etc/nginx/snippets/polyform.conf
SOURCE=/home/omalled/polyform/config/nginx-polyform.conf
BACKUP="${SITE}.before-polyform"

test -f "$SITE"
test -f "$SOURCE"
cp -a "$SITE" "$BACKUP"
install -o root -g root -m 0644 "$SOURCE" "$SNIPPET"

if ! grep -qF "include $SNIPPET;" "$SITE"; then
    sed -i "0,/^[[:space:]]*listen \[::\]:443 ssl/{s|^[[:space:]]*listen \[::\]:443 ssl|    include $SNIPPET;\n\n    listen [::]:443 ssl|}" "$SITE"
fi

if ! nginx -t; then
    cp -a "$BACKUP" "$SITE"
    nginx -t
    exit 1
fi

systemctl reload nginx
printf 'Polyform nginx route configured successfully.\n'
