#!/bin/bash
# Jitsi.sh : a simple jitsi installer by Brain 0verride
# https://twitter.com/brain0verride
# https://www.christophe-casalegno.com

replacer='sed' 				# command used for replacement 
repoptions='-i' 			# options for the replacer
downloader='apt -y -f -d install'
installer='apt -y -f install' 

sources_list='/etc/apt/sources.list.d'
auto='debconf-set-selections'
export DEBIAN_FRONTEND=noninteractive

url=$1

needps='vim lsb-release apt-transport-https ca-certificates wget curl lynx dirmngr software-properties-common'

function checkfqdn()
{
result=$(echo "$1" | grep -P '(?=^.{1,254}$)(^(?>(?!\d+\.)[a-zA-Z0-9_\-]{1,63}\.?)+(?:[a-zA-Z]{2,})$)')

if [[ -z "$result" ]]
then
    echo -e "${RED} [ ERROR ]" "${NC}  $1 is not a valid FQDN"
    exit 0
else
    echo -e "${GREEN} [ OK ]" "${NC} $1 is a valid FQDN, install in progress..."
fi
}

function deploy()
{
  installer="$1"
  packs="$2"

  echo "Installing packages : $packages..."
  $downloader $packs
  $installer $packs
}

function sourcesupdate()
{
  apt-get update
}

sourcesupdate
apt -y upgrade

deploy "$installer" "$needps"

checkfqdn "$url"

wget -qO - https://download.jitsi.org/jitsi-key.gpg.key | apt-key add -
echo 'deb https://download.jitsi.org stable/' >> "$sources_list"/jitsi-stable.list

sourcesupdate

$auto <<< "jitsi-videobridge jitsi-videobridge/jvb-hostname $url"
deploy "$installer" "jitsi-meet"

$replacer $repoptions "s#DEB_CONF_RESULT=\`debconf-show jitsi-meet-web-config | grep jvb-hostname\`#DEB_CONF_RESULT=$1#g" /usr/share/jitsi-meet/scripts/install-letsencrypt-cert.sh

