#!/usr/bin/env bash
set -euo pipefail

data_dir="${IKAR_DATA_PATH:-/mnt/data/ikar-data}"
backup_dir="${IKAR_BACKUP_PATH:-/mnt/data/ikar-backups}"
retention_days="${IKAR_BACKUP_RETENTION_DAYS:-14}"
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
work_dir="${backup_dir}/.ikar-${timestamp}.tmp"
archive="${backup_dir}/ikar-${timestamp}.tar.gz"

test -f "${data_dir}/ikar.db"
mkdir -p "${backup_dir}"
rm -rf "${work_dir}"
mkdir -p "${work_dir}/Data"

sqlite3 "${data_dir}/ikar.db" ".timeout 10000" ".backup '${work_dir}/Data/ikar.db'"
test "$(sqlite3 "${work_dir}/Data/ikar.db" 'PRAGMA integrity_check;')" = "ok"

for directory in Attachments AppUpdates secrets; do
    if test -d "${data_dir}/${directory}"; then
        rsync -a "${data_dir}/${directory}/" "${work_dir}/Data/${directory}/"
    fi
done

tar -C "${work_dir}" -czf "${archive}.partial" Data
gzip -t "${archive}.partial"
mv "${archive}.partial" "${archive}"
sha256sum "${archive}" > "${archive}.sha256"
rm -rf "${work_dir}"

find "${backup_dir}" -maxdepth 1 -type f -name 'ikar-*.tar.gz' -mtime "+${retention_days}" -delete
find "${backup_dir}" -maxdepth 1 -type f -name 'ikar-*.tar.gz.sha256' -mtime "+${retention_days}" -delete

printf '%s\n' "${archive}"
