#!/bin/bash
set -e

source "$(dirname ${BASH_SOURCE[0]})/.admin-functions.sh"

fix_various
ensure_root "Creating a backup requires root privileges."

FUSION_STARTED_BY_SCRIPT="false"
if ! is_fusion_running; then
  start_fusion
  FUSION_STARTED_BY_SCRIPT="true"
fi

echo -n "Creating database backup... "
pushd /fusion 1> /dev/null
  BACKUP_OUTPUT=$(docker-compose exec database-backup node /scripts/pg_backup "$1" | grep "Backup complete")
  if [ -z "${BACKUP_OUTPUT}" ]; then
    echo "Failed to create database backup"
    exit 1
  fi

  BACKUP_NAME=$(echo ${BACKUP_OUTPUT} | awk -F ': ' '{print $2}')
  if [ -z "${BACKUP_NAME}" ]; then
    echo "Failed to determine backup name"
    exit 1
  fi
popd 1> /dev/null
echo "Done"

if [ "${FUSION_STARTED_BY_SCRIPT}" == "true" ]; then
  stop_fusion
fi

echo "BK_META_BACKUP_NAME=${BACKUP_NAME}" > /fusion/data/backup_metadata

echo -n "Creating Content Fusion backup... "
sudo tar -zc --exclude="./db" -f ./fusion-backup.tar.gz -C /fusion/data .
echo "Done"

echo "Backup created: '`pwd`/fusion-backup.tar.gz'"
