#!/bin/bash

set -euo pipefail

now=$(date +"%Y%m%d%H%M")

declare -a arr=("mail" "matrix" "monitoring")
declare -a monitoring=("monitoring_prometheus-data" "monitoring_grafana-storage" "monitoring_loki-data" "monitoring_alloy-data")
declare -a matrix=("matrix_db")
declare -a immich=("systemd-immich-pgdata" "systemd-immich-upload")

gitea_uid=$(id -u gitea)
immich_uid=$(id -u immich)

restore() {
    for i in "${arr[@]}"; do
        cd /opt/beeserver/${i}
        podman-compose up -d
    done

    for j in "${monitoring[@]}"; do
        rm -rf /opt/beeserver/monitoring/${j}.tar
    done

    for j in "${matrix[@]}"; do
        rm -rf /opt/beeserver/matrix/${j}.tar
    done

    systemctl --user --machine gitea@.host start gitea-db.service gitea-server.service || true
    systemctl --user --machine immich@.host start immich-db.service immich-redis.service immich-server.service || true
    rm -f /home/immich/systemd-immich-*.tar
}

trap restore EXIT

for i in "${arr[@]}"
do
    cd /opt/beeserver/${i}
    podman-compose down -t 60
    if [[ "$i" == "monitoring" ]]
    then
        for j in "${monitoring[@]}"
        do
            podman volume export ${j} --output ${j}.tar
        done
    fi

    if [[ "$i" == "matrix" ]]
    then
        for j in "${matrix[@]}"
        do
            podman volume export ${j} --output ${j}.tar
        done
    fi
    rsync -aH /opt/beeserver/${i} /opt/backup/beeserver
    podman-compose up -d
done

systemctl --user --machine gitea@.host stop gitea-server.service gitea-db.service
rsync -aH /home/gitea/data /opt/backup/beeserver/gitea
systemctl --user --machine gitea@.host start gitea-db.service gitea-server.service

systemctl --user --machine immich@.host stop immich-server.service immich-db.service immich-redis.service
for v in "${immich[@]}"
do
    sudo -u immich XDG_RUNTIME_DIR=/run/user/${immich_uid} podman volume export ${v} --output /home/immich/${v}.tar
done
systemctl --user --machine immich@.host start immich-db.service immich-redis.service immich-server.service
mkdir -p /opt/backup/beeserver/immich/
mv /home/immich/systemd-immich-*.tar /opt/backup/beeserver/immich/

tar -czf - /opt/backup/beeserver | gpg --batch --passphrase-file /opt/backup/passphrase.txt -c -o /home/beeshare/raid/serverBackup/beeserver_daily_${now}.tar.gz.gpg
