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

BACKUP_DIR=/var/backups/reverse-proxy
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
STAGING=$(mktemp -d)
ARTIFACT="$BACKUP_DIR/reverse-proxy-nginx-config-$STAMP.tar.gz"
MANIFEST="$BACKUP_DIR/reverse-proxy-nginx-config-$STAMP.sha256"
trap 'rm -rf "$STAGING"' EXIT

install -d -m 0700 -o root -g root "$BACKUP_DIR"
mkdir -p "$STAGING/include"

for path in \
  /etc/nginx/nginx.conf \
  /etc/nginx/conf.d \
  /etc/nginx/sites-available \
  /etc/nginx/sites-enabled \
  /etc/nginx/snippets; do
  if [ -e "$path" ]; then
    printf '%s\n' "${path#/}" >> "$STAGING/include/paths.txt"
  fi
done

if [ ! -s "$STAGING/include/paths.txt" ]; then
  echo "No Nginx config paths found to back up" >&2
  exit 1
fi

tar -C / -czf "$ARTIFACT" --files-from "$STAGING/include/paths.txt"
chmod 0600 "$ARTIFACT"

cd "$BACKUP_DIR"
sha256sum "$(basename "$ARTIFACT")" > "$MANIFEST"
chmod 0600 "$MANIFEST"
sha256sum -c "$MANIFEST"
echo "$ARTIFACT"
