#!/bin/bash

YELLOW='\033[0;33m'
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

if [ "$USER" != "root" ] && [ "`whoami`" != "root" ]; then
    echo -e "${RED}This script needs sudo :(${NC}"
    exit 1
fi

if [ "$#" -ne 10 ] && [ "$#" -ne 11 ]; then
    echo -e "${YELLOW}Usage: $0 <host> <user> <password> <psql_db_name_from> <psql_db_name_to> <psql_port> <ch_def_user_password> <ch_db_name_from> <ch_db_name_to> <ch_port> <license>${NC}"
    exit 1
fi

required_space_gb=25
available_space_gb=$(df -BG / | awk 'NR==2 {print $4}' | tr -d 'G')

if [ "$available_space_gb" -lt "$required_space_gb" ]; then
    echo -e "${RED}ERROR:${NC} requires minimum $required_space_gb GB free memory on the disk"
    echo "Now available: ${available_space_gb} GB"
    exit 1
fi

host=$1
user=$2
password=$3
psql_db_name_from=$4
psql_db_name_to=$5
psql_port=$6
ch_def_user_password=$7
ch_db_name_from=$8
ch_db_name_to=$9
ch_port=${10}
license=${11}

if [[ -z "$license" ]]; then
    license=0
fi

./src/dump.sh "$host" "$user" "$password" "$psql_db_name_from" "$psql_port" "$ch_def_user_password" "$ch_db_name_from" "$ch_port" "$license"
exit_code_dump=$?

if [ $exit_code_dump -eq 0 ]; then
    echo -e "\t${GREEN}Dumping DB done <3${NC}"
else
    echo -e "${RED}ERROR:${NC} dumping DB error!"
    exit 1
fi

./src/restore.sh "$host" "$user" "$password" "$psql_db_name_to" "$psql_port" "$ch_def_user_password" "$ch_db_name_from" "$ch_db_name_to" "$ch_port" "$license"
exit_code_restore=$?

if [ $exit_code_restore -eq 0 ]; then
    echo -e "\t${GREEN}Restoring DB done <3${NC}"
else
    echo -e "${RED}ERROR:${NC} restoring DB error!"
    exit 1
fi

rm -rf dumps
rm -rf restores
rm -rf /backups
