#!/bin/bash

#
# ScoDoc: save all user data (database, configs, images, archives...) in separate directory
# 
#  Utile pour migrer ScoDoc d'un serveur a un autre
#  Executer en tant que root sur le serveur d'origine
#
# E. Viennet, Sept 2011, Aug 2020, Jul 2021
#
# Le répertoire de ce script:
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

source "$SCRIPT_DIR/config.sh"
source "$SCRIPT_DIR/utils.sh"


check_uid_root "$0"

# Destination directory
if [ ! $# -eq 1 ]
then
  echo "Usage: $0 destination_directory"
  exit 1
fi
DEST=$1
# remove trailing slashs if needed:
shopt -s extglob
DEST="${DEST%%+(/)}"

if [ ! -e "$DEST" ]
then
  echo Creating directory "$DEST"
  mkdir "$DEST"
else
  echo "Error: Directory " "$DEST"  " exists"
  echo "remove it or specify another destination !"
  exit 2
fi

echo "Stopping ScoDoc..."
scodocctl stop

# Dump all postgres databases
echo "Dumping SQL database..."
chown postgres "$DEST"
su -c "pg_dumpall > \"$DEST\"/scodoc.dump.txt" postgres
if [ ! "$?" -eq 0 ] 
then
  printf "Error dumping postgresql database\nPlease check that SQL server is running\nAborting.\n"
  exit 1
fi
chown root "$DEST"

# ScoDoc archives, configuration, photos, etc.
echo "Copying var/ ..." 
cp -rp "$SCODOC_DIR/var" "$DEST"


echo "Copying server logs..."
cp -rp "$SCODOC_DIR/log" "$DEST"


# --- Archive all files in a tarball to ease transfer
echo
echo "Archiving backup files in a $DEST.tgz..."
base=$(basename "$DEST")
(cd "$DEST"/.. || terminate "directory error"; tar cfz "$DEST".tgz "$base")

echo "Done (you can copy " "$DEST"".tgz to destination machine)."
