#!/bin/bash

set -eu

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. $DIR/../help.sh
. $DIR/../postgres/run --only-source

gitea_help() {
  echo "./run backup    : Lancement de la sauvegarde de Gitea"
  echo "./run restore   : Restoration de la sauvegarde de Gitea"
}

gitea_backup() {
  script_env
  BACKUP_DATE_DEFAULT=`date +%Y%m%d_%H%M%S`
  BACKUP_DATE=${BACKUP_DATE:-$BACKUP_DATE_DEFAULT}
  backup_folder_create

  POSTGRES_BACKUP_FILE=backups/${BACKUP_DATE}_gitea_postgres.sql
  postgres_backup

  docker-compose run --rm -v $GITEA_VOLUME_NAME:/data -v $HOME/backups/gitea:/backup gitea tar cvf /backup/${BACKUP_DATE}_gitea_data.tar /data
}

gitea_restore() {
  script_start
  script_env
  echo "🏁 Start restore PostgreSQL database '$POSTGRES_DB' from '$POSTGRES_BACKUP_FILE'"
  cat $POSTGRES_BACKUP_FILE | docker exec -i $POSTGRES_CONTAINER_NAME psql -U $POSTGRES_USER -d $POSTGRES_DB
  script_end
}

if [ $# -ge 1 ]; then
  if [ "${1}" == "backup" ]; then
    script_start
    gitea_backup
    script_end
  elif [ "${1}" == "restore" ]; then
    script_start
    gitea_restore
    script_end
  elif [ "${1}" != "--only-source" ]; then
    gitea_help
  fi
else
  gitea_help
fi