#!/bin/bash
set -o errexit -o pipefail -o nounset -o noclobber

database=$1
application=$2
file="/home/$(whoami)/.config/containers/systemd/user/${database}.service"
if [[ ! -f "${file}" ]]; then
    echo "File ${file} not found"
    exit 1
fi
content="$(cat "${file}")"
version_pattern="^Image=docker.io/postgres:([\d]+)$"
line=""
new_line=""
if [[ "${content}" =~ ${version_pattern} ]]; then
    line="${BASH_REMATCH[0]}"
    version="${BASH_REMATCH[1]}"
    new_version="$(("${version}" + 1))"
    new_line="Image=docker.io/postgres:${new_version}"
else
    echo "Version not found in ${file}"
    exit 1
fi

systemctl --user stop "${application}" "${database}"

podman run "${database}"
podman exec -it "${database}" pg_dumpall -U postgres > dump.sql
podman stop "${database}"

podman volume create db_backup
podman run --rm -it -v "${database}":/from -v db_backup:/to ubuntu bash -c "cd /from ; cp -av . /to"

sed -i "s/${line}/${new_line}/" "${file}"
sed -i "s/Pod=${application}.pod/#Pod=${application}.pod/" "${file}"
sed -i "s/StartWithPod=true/#StartWithPod=true/" "${file}"
systemctl --user daemon-reload

systemctl --user start "${database}"
podman exec -T "${database}" psql -U postgres < dump.sql
read -n 1 -s -r -p "Press any key to continue..."
systemctl --user stop "${database}"

podman volume rm db_backup
rm -f dump.sql

sed -i "s/#Pod=${application}.pod/Pod=${application}.pod/" "${file}"
sed -i "s/#StartWithPod=true/StartWithPod=true/" "${file}"
systemctl --user daemon-reload

systemctl --user start "${application}"
