#!/bin/sh
# Copies everything that a factory restore would lose to /data/eurogard-failsafe/export-<time>.tgz (own partition, root only).
# Small (a few MB): router configuration, Eurogard/fleet state, Node-RED data without its modules, user accounts, SSH host keys.
# Keeps the three newest. Exit 0 = exported, 1 = not exported (never stops an update).
#
# Restore by hand after a factory reset and a reinstall of the Eurogard packages (check the paths in the archive first):
#   tar -C / -xzpf /data/eurogard-failsafe/export-<time>.tgz
. "$(dirname "$0")/common.sh"

FILES=""
for f in app/config app/eurogard docker/data etc/passwd etc/shadow etc/group etc/gshadow etc/sudoers.d etc/ssh/ssh_host_* \
         etc/openvpn etc/stunnel root/.ssh/authorized_keys; do
    for m in /$f; do
        [ -e "$m" ] && FILES="${FILES} ${m#/}"
    done
done

NEW="${STATE}/export-$(date '+%Y%m%d-%H%M%S').tgz"
EXCLUDES="--exclude=docker/data/node_modules --exclude=docker/data/.npm --exclude=*.log"

# a rough size check: the uncompressed data without the excluded modules
KB=$(cd / && du -sk --exclude=node_modules --exclude=.npm ${FILES} 2> /dev/null | awk '{s+=$1} END {print s+0}')
FREE=$(df -Pk "${STATE}" | awk 'NR==2 {print $4}')
if [ "${FREE:-0}" -lt $(( KB * 2 + 5120 )) ]; then
    log "export skipped: ${KB} KB of data, only ${FREE} KB free on ${STATE}"
    exit 1
fi

# shellcheck disable=SC2086
if (cd / && tar -czpf "${NEW}.tmp" ${EXCLUDES} ${FILES} 2> "${STATE}/export.err"); then
    mv -f "${NEW}.tmp" "${NEW}"
    sync
    chmod 600 "${NEW}"
    ls -1t "${STATE}"/export-*.tgz 2> /dev/null | tail -n +4 | xargs -r rm -f
    log "exported $(cd / && echo ${FILES} | wc -w) paths to ${NEW} ($(stat -c %s "${NEW}") bytes)"
    echo "${NEW}"
    exit 0
fi
rm -f "${NEW}.tmp"
log "export failed: $(head -c 300 "${STATE}/export.err" 2> /dev/null | tr '\n' ' ')"
exit 1
