#!/bin/sh
set -e

case "$1" in
  configure)
    mkdir -p /etc/nc-backup /var/backups/nextcloud
    chmod 700 /var/backups/nextcloud 2>/dev/null || true
    if [ ! -f /etc/nc-backup/config.yaml ] && [ -f /etc/nc-backup/config.example.yaml ]; then
      cp /etc/nc-backup/config.example.yaml /etc/nc-backup/config.yaml
      chmod 600 /etc/nc-backup/config.yaml
    fi
    python3 - <<'PY' || true
from nc_backup.secrets import ensure_web_token
from nc_backup.detect import apply_detected_defaults
ensure_web_token()
apply_detected_defaults()
PY
    if command -v ufw >/dev/null 2>&1; then
      ufw allow 42173/tcp comment 'nc-backup-web' >/dev/null 2>&1 || true
    fi
    if command -v systemctl >/dev/null; then
      systemctl daemon-reload || true
      systemctl enable --now nc-backup-web.service || true
    fi
    ;;
esac

#DEBHELPER#

exit 0
