#!/bin/sh

#
# Copyright (C) 2022 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

# Execute the backup.
# If the backup has changes since last run, upload it to remote server

set -e

WORK_DIR="/var/backup"
BACKUP="$WORK_DIR/backup-$(date +%s).tar.gz"
MD5="$WORK_DIR/md5"
MD5_LAST="/etc/backup.md5"
PASSPHRASE="/etc/backup.pass"

function send {
    if [ -s $PASSPHRASE ]; then
        # send encrypted backup
        gpg --batch -c --yes --passphrase-file $PASSPHRASE $BACKUP
        remote-backup upload "$BACKUP.gpg"
        mv $MD5 $MD5_LAST
    else
        # password not set, abort upload
        exit 4
    fi
    rm -f "$BACKUP" "$BACKUP.gpg"
    exit $?
}

SYSTEM_ID=$(uci -q get ns-plug.config.system_id)
SYSTEM_SECRET=$(uci -q get ns-plug.config.secret)

if [ -z "$SYSTEM_ID" ] || [ -z "$SYSTEM_SECRET" ]; then
    # System ID and System secret not found, configure ns-plug to enable it
    exit 0
fi

# hack: avoid to backup non-config file
if [ -f /etc/acme/http.header ]; then
    mv /etc/acme/http.header /tmp
fi

# Create the backup
mkdir -p $WORK_DIR
sysupgrade -k -b $BACKUP 2>/dev/null
md5sum $BACKUP | awk '{print $1}' > $MD5

# hack: restore acme working file
if [ -f /tmp/http.header ]; then
    mv /tmp/http.header /etc/acme
fi

# Send backup if there is no md5 saved
if [ ! -f "$MD5_LAST" ]; then
    send
fi

# Send backup if the md5 is changed
if [ -f "$MD5_LAST" ] && [ "$(cat $MD5_LAST)" != "$(cat $MD5)" ]; then
    send
fi
