#!/bin/bash
# ================================================================================
#
# LOCALDUMP :: POSTGRES
# create gzipped plain text backups from each scheme
#
# --------------------------------------------------------------------------------
# ah - Axel Hahn <axel.hahn@iml.unibe.ch>
# ds - Daniel Schueler <daniel.schueler@iml.unibe.ch>
#
# 2016-11-10  ah,ds  v1.0
# 2017-03-29  .....  v1.1  added restore
# 2022-01-20         v1.2  fixes with shellcheck
# 2022-03-17         v1.3  WIP: add lines with prefix __DB__
# 2023-09-20         v1.4  FIX could not change directory to "/root": Permission denied
# 2024-10-02  ah     v1.5  rename backup and restore function
# ================================================================================

if [ -z "$BACKUP_TARGETDIR" ]; then
  echo "ERROR: you cannot start $(basename $0) directly"
  rc=$rc+1
  exit 1
fi

# --------------------------------------------------------------------------------
# CONFIG
# --------------------------------------------------------------------------------

  # unix user of postgres database
  PGUSER=postgres


# --------------------------------------------------------------------------------
# FUNCTION
# --------------------------------------------------------------------------------


function pgsql.backup(){

  create_targetdir

  # ----- change owner of directory because of su command
  chown ${PGUSER}. "${BACKUP_TARGETDIR}"

  # ----- GO

  # prevent could not change directory to "/root": Permission denied
  cd /tmp
  sSqlGetDblist="select datname from pg_database where not datistemplate and datallowconn order by datname;"
  for DATABASE in $(su ${PGUSER} -c "psql ${BACKUP_PARAMS} -At -c '$sSqlGetDblist' postgres" 2>/dev/null)
  do
    echo -n "__DB__${SERVICENAME} backup $DATABASE ... "
    OUTFILE="${BACKUP_TARGETDIR}/$(get_outfile ${DATABASE}).sql"
    if su ${PGUSER} -c "pg_dump ${BACKUP_PARAMS} -Fp ${DATABASE} >$OUTFILE"; then
      fetchrc >/dev/null
      db._compressDumpfile "$OUTFILE"
    else
      fetchrc
    fi

  done
  cd -
}


# restore database dump file into database
# param  string  database dump file (gzipped)
# param  string  optional: database to import; default: database is parsed from file
function pgsql.restore(){
  sMyfile=$1
  sMyDb=$2

  if [ -z "$sMyDb" ]; then
    h2 "analyze dump $sMyfile"
    sMyDb="$(guessDB "$sMyfile" )"
    echo "detected db schema from file: [${sMyDb}]"
  else
    echo "db schema from param 2: [${sMyDb}]"
  fi

  echo

  echo import to "$sMyDb"...

  h2 "deleting database [$sMyDb] ..."
  color cmd
  su ${PGUSER} -c "dropdb ${sMyDb}"
  color reset

  h2 "ensure that database exists ..."
  color cmd
  su ${PGUSER} -c "psql ${BACKUP_PARAMS} -c \"CREATE DATABASE ${sMyDb};\""
  fetchrc
  color reset

  h2 "import ..."
  ls -l "${sMyfile}"
  echo "import to database [${sMyDb}]"
  color cmd
  zcat "${sMyfile}" | su ${PGUSER} -c "psql ${BACKUP_PARAMS} -d ${sMyDb}"
  fetchrc
  color reset

}


# --------------------------------------------------------------------------------
# MAIN
# --------------------------------------------------------------------------------

# ----- requirements

j_requireBinary "psql" 1

if [ $rc -ne 0 ]; then
  color.echo error "ERROR: Missing psql binary. Your Sqlite data cannot be dumped."
else

  action=$1
  shift 1
  "${SERVICENAME}.$action" $*

fi


# case $1 in
#   backup)    
#     test $SERVICEFOUND -eq 1 && pgsql.backup
#     ;;
#   restore)
#     shift 1
#     test $SERVICEFOUND -eq 1 && pgsql.restore $*
#     ;;
#   *)
#     echo ERROR: wrong syntax: 
#     echo $0 $*
#     exit 1
#   esac

echo "__DB__$SERVICENAME INFO: $0 $* [$SERVICENAME] final returncode rc=$rc"

# --------------------------------------------------------------------------------
