#!/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__
# ================================================================================

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

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

  SERVICEFOUND=0
  # unix user of postgres database
  PGUSER=postgres


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

function checkRequirements(){
  j_requireBinary "pg_dump"   1
  j_requireProcess "postgres" 1

  # set flag and reset return code
  test $rc -eq 0 && SERVICEFOUND=1
  rc=0
}

function doPgsqlBackup(){

  create_targetdir

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

  # ----- GO

  sSqlGetDblist="select datname from pg_database where not datistemplate and datallowconn order by datname;"
  for DATABASE in $(su ${PGUSER} -c "psql -At -c '$sSqlGetDblist' postgres" 2>/dev/null)
  do
    echo -n "__DB__${SERVICENAME} backup $_dbname ... "
    OUTFILE="${BACKUP_TARGETDIR}/$(get_outfile ${DATABASE}).sql"
    su ${PGUSER} -c "pg_dump -Fp ${DATABASE} >$OUTFILE"
    fetchrc >/dev/null

    db._compressDumpfile "$OUTFILE"

    # if [ $myrc -eq 0 ]; then
    #   echo -n "compress ... "
    #   compress_file "$OUTFILE"
    # else
    #   color error
    #   echo "ERROR occured - no gzip"
    #   color reset
    #   # mv $OUTFILE $OUTFILE
    #   echo "__DB__$SERVICENAME INFO: backed up ${DATABASE}"
    # fi
    # ls -l "$OUTFILE"*
  echo
  done
}


# 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 restoreByFile(){
  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 -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 -d ${sMyDb}"
  fetchrc
  color reset

}


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

  # ----- requirements
checkRequirements >/dev/null 2>&1
if [ $SERVICEFOUND -eq 0 ]; then
  echo "__DB__$SERVICENAME INFO: service [$SERVICENAME] is not avilable on this machine."
fi

case $1 in
  check)
    # repeat check ... but show output
    echo
    echo Details:
    checkRequirements
    echo
    ;;
  backup)    
    test $SERVICEFOUND -eq 1 && doPgsqlBackup
    ;;
  restore)
    shift 1
    test $SERVICEFOUND -eq 1 && restoreByFile $*
    ;;
  *)
    echo ERROR: wrong syntax: 
    echo $0 $*
    exit 1
  esac

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

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