#!/bin/bash
export PATH=/4PROJECTS/bin:$PATH
if [ ! -n "$2" ]; then
  echo "Missing Parameters <UUID> <FILE>"
  exit 0
fi

UUID=$1
echo "UUID: $UUID"

source /4server/sbin/helpers

get_contract_info


#export ODOO_DB_PASSWORD=$(echo "$SECRET" | jq -r '.psql')

echo "PASSWORD $ODOO_DB_PASSWORD"

echo "Restoring $FILENAME to $UUID"
echo "status of container"
doas docker ps -a --filter "id=$UUID"
echo "POSTGRES HOST: $POSTGRES_HOST"
BACKUP="/mnt/backup/$2"
TEMPLATE="/mnt/db_images/$2"
doas docker exec "$UUID" /bin/bash -c "[ -f $TEMPLATE ]"

if  doas docker exec "$UUID" /bin/bash -c "[ -f $BACKUP ]"; then
    FILENAME="$BACKUP"
elif  doas docker exec "$UUID" /bin/bash -c "[ -f $TEMPLATE ]"; then
    FILENAME="$TEMPLATE"
else
  echo "File not exists"
  exit 0
fi


### DELETE AND CREATE DATABASE
PGPASSWORD="$POSTGRES_ADMIN_PASSWORD" psql -h "$POSTGRES_HOST" -U "$POSTGRES_ADMIN_USER" -d postgres -c "
SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = '$UUID' AND pid <> pg_backend_pid();
"
PGPASSWORD="$POSTGRES_ADMIN_PASSWORD" psql -h "$POSTGRES_HOST" -U "$POSTGRES_ADMIN_USER" -d postgres -c "
DROP DATABASE IF EXISTS \"$UUID\";
"

PGPASSWORD="$POSTGRES_ADMIN_PASSWORD" psql \
  -h "$POSTGRES_HOST" -U "$POSTGRES_ADMIN_USER" -p "$POSTGRES_PORT" -d postgres \
  -c "ALTER ROLE \"$UUID\" CREATEDB;"


doas docker exec "$UUID" rm -rf /home/odoo/.local/share/Odoo/filestore
doas docker exec "$UUID" rm -rf /root/.local/share/Odoo/filestore

doas docker exec "$UUID" odoo db --db_host beedb -w "$ODOO_DB_PASSWORD" -r "$UUID" load "$UUID" $FILENAME -f

PGPASSWORD="$POSTGRES_ADMIN_PASSWORD" psql \
  -h "$POSTGRES_HOST" -U "$POSTGRES_ADMIN_USER" -p "$POSTGRES_PORT" -d postgres \
  -c "ALTER ROLE \"$UUID\" NOCREATEDB;"


doas docker exec "$UUID" cp -r /root/.local/share/Odoo/filestore /home/odoo/.local/share/Odoo/filestore
doas docker exec "$UUID" chown -R odoo:odoo /home/odoo/.local

doas docker exec "$UUID" mkdir -p /var/lib/odoo/.local/share/Odoo/
doas docker exec "$UUID" ln -s /home/odoo/.local/share/Odoo/filestore /var/lib/odoo/.local/share/Odoo/filestore

docker restart "$UUID"
