#!/bin/bash
set -e

echo
echo "------------------------------------------------------------"
echo "Script pour importer les enregistrements et la configuration"
echo "d'un BBB distant sur un BBB installé localement"
echo "------------------------------------------------------------"
echo
read -p "Nom de domaine du BBB distant à récupérer: " OLD_BBB_HOST
read -p "Utilisateur SSH du BBB distant: " OLD_BBB_USER
read -p "Nom de domaine du BBB local: " NEW_BBB_HOSTNAME
echo
echo "----------------------------------------------"
echo "Ce script va récupérer la configuration de $OLD_BBB_USER pour l'appliquer sur ce serveur $NEW_BBB_HOSTNAME"
read -p "C'est partis? " -n 1 -r
echo
if [[ $REPLY =~ ^[YyOo]$ ]]
then
	echo
	echo "=== Copie des enregistrements du BBB distant"
	rsync -r $OLD_BBB_USER@$OLD_BBB_HOST:/var/bigbluebutton/published/ /var/bigbluebutton/published/ --info=progress2
	rsync -r $OLD_BBB_USER@$OLD_BBB_HOST:/var/bigbluebutton/unpublished/ /var/bigbluebutton/unpublished/ --info=progress2
	rsync -r $OLD_BBB_USER@$OLD_BBB_HOST:/var/bigbluebutton/recording/raw/ /var/bigbluebutton/recording/raw/ --info=progress2
	chown -R bigbluebutton: /var/bigbluebutton/published /var/bigbluebutton/unpublished /var/bigbluebutton/recording/raw

	echo
	echo "=== Applique le nouveau nom de domaine aux enregistrements"
	bbb-conf --setip $NEW_BBB_HOSTNAME

	echo
	echo "=== Arret et sauvegarde de l'actuel Greenlight"
	cd /root/greenlight && docker-compose down
	rm -rf /root/greenlightBK && mv /root/greenlight /root/greenlightBK

	echo
	echo "=== Copie du greenlight du BBB distant"
	rsync -r $OLD_BBB_USER@$OLD_BBB_HOST:/root/greenlight/ /root/greenlight/ --info=progress2

	echo
	echo "=== Applique le nouveau nom de domaine dans l'ancien conf Greenlight"
	sed -i "s/$OLD_BBB_HOST/$NEW_BBB_HOSTNAME/g" /root/greenlight/.env

	echo
	echo "=== Applique le nouveau secret BBB à la conf Greenlight"
	NEW_SECRET=$(bbb-conf --secret | sed -n "/Secret:/ s/    Secret: //p")
	sed  -i "s/\(^BIGBLUEBUTTON_SECRET=\).*/\1$NEW_SECRET/" /root/greenlight/.env

	echo
	echo "=== Redémarre Greenlight"
	cd /root/greenlight && docker-compose up -d
fi
