#!/bin/bash

set -eu

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SERVICE_NAME="Gitea"

. $DIR/../help.sh
. $DIR/../postgres/run --only-source

gitea_help() {
  echo "./run backup    : Lancement de la sauvegarde de ${SERVICE_NAME}"
  echo "./run restore   : Restauration de la sauvegarde de ${SERVICE_NAME}"
}

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_DOMAIN}_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_DOMAIN}_data.tar /data
}

gitea_restore() {
  script_env

  postgres_restore
  docker-compose run --rm -v $GITEA_VOLUME_NAME:/data -v $HOME/backups/gitea:/backup gitea tar xvf /backup/${BACKUP_DATE}_${GITEA_DOMAIN}_data.tar /data --strip 1
}

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