#!/bin/sh

PSQL=psql

TMP_DIR=/tmp/backups
APP_NAME=suite
DB_NAME=${APP_NAME}
DATA_SRC_DIR="/app/data/${APP_NAME}"

if [ -z "$1" ]
  then
	ARCHIVE_PATH="$(ls ${TMP_DIR}/${APP_NAME}* | sort -V | tail -n 1)"
	ARCHIVE="$(basename ${ARCHIVE_PATH})"
  else
	DATETIME=$1
	ARCHIVE="${APP_NAME}_${DATETIME}.tgz"
fi

echo Using archive ${ARCHIVE}

ARCHIVE_DIR="${TMP_DIR}/${ARCHIVE}_tmp"
ARCHIVE_DATA_DIR="${ARCHIVE_DIR}/data"
ARCHIVE_DB_DIR="${ARCHIVE_DIR}/db"


OLD_PWD=`pwd`

mkdir $ARCHIVE_DIR
cd $TMP_DIR

echo `pwd`

# unzip
tar xf "${ARCHIVE}" -C $ARCHIVE_DIR

cd $ARCHIVE_DIR


# stop application
echo Shutting down application ${APP_NAME}
docker stop ${APP_NAME}

# copy data
/bin/cp -rf "./data/." $DATA_SRC_DIR

# restore DB
$PSQL -U postgres --host 127.0.0.1 -d template1 < "./db/db.sql"

# start app
echo Starting application ${APP_NAME}
docker start ${APP_NAME} &

cd $OLD_PWD

# remove unzipped data
rm -rf $ARCHIVE_DIR
