#!/bin/bash
# n-os-tr-firstboot: one-shot provisioning for directory structure and TLS.
# Identity and key generation are handled by interactive n_signer (manual start on tty1).
# This script is independent of signer startup.
set -euo pipefail

STATE=/var/lib/n-os-tr

# 1. Create required directories
mkdir -p "$STATE" /var/www/blobs /var/lib/c-relay /var/lib/ginxsom

# 2. Self-signed TLS cert if none exists
if [[ ! -f /etc/ssl/n-os-tr/fullchain.pem ]]; then
    mkdir -p /etc/ssl/n-os-tr
    openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \
        -subj "/CN=$(hostname)" \
        -keyout /etc/ssl/n-os-tr/privkey.pem \
        -out /etc/ssl/n-os-tr/fullchain.pem 2>/dev/null
    chmod 0600 /etc/ssl/n-os-tr/privkey.pem
fi

# 3. Ownership
chown -R www-data:www-data /var/www/blobs 2>/dev/null || true
chown -R c-relay:c-relay /var/lib/c-relay 2>/dev/null || true

# 4. Mark provisioned
touch "$STATE/.provisioned"
