#!/usr/bin/env bash
# tool/config-export -- the panel's own configuration, without secrets
#
# Used before a migration or when opening a support case. The secret file is
# deliberately excluded and the archive says so, so nobody assumes it is a full
# backup.
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t tool_m_configexport)"

out="/root/nhanhvps-config-$(date -u '+%Y%m%dT%H%M%SZ').tar.gz"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
install -d -m 0700 "$work/config" "$work/sites"

for f in "$NV_CONFIG_FILE" /etc/nginx/conf.d/00-nhanhvps.conf \
         /etc/nginx/conf.d/10-nhanhvps-realip.conf \
         /etc/php/*/fpm/pool.d/nhanhvps.conf /etc/mysql/mariadb.conf.d/99-nhanhvps.cnf \
         /etc/sysctl.d/99-nhanhvps.conf /etc/security/limits.d/99-nhanhvps.conf; do
    [ -f "$f" ] || continue
    cp -a "$f" "$work/config/$(printf '%s' "$f" | tr '/' '_')" 2>/dev/null || true
done
cp -a "$NV_STATE_DIR"/sites/*.conf "$work/sites/" 2>/dev/null || true

cat >"$work/README.txt" <<EOF
$(t cfgexport_readme)
version: $(cat "$NV_BASE/VERSION" 2>/dev/null)
created: $(date -u '+%Y-%m-%dT%H:%M:%SZ')
excluded: $(basename "$NV_SECRET_FILE") and per-site credential files
EOF

if tar czf "$out" -C "$work" . 2>/dev/null; then
    chmod 0600 "$out"
    nv_trace config-export "$out"
    ui_ok "$(t cfgexport_done "$out")"
    ui_kv "$(t col_size)" "$(du -h "$out" | cut -f1)"
    ui_warn "$(t cfgexport_secret_note)"
else
    rm -f "$out"
    nv_fail 4505 "$(t cfgexport_failed)"
    exit 1
fi
exit 0
