#!/bin/bash
#
# freepbx-setup - prepare a SUSE host and install FreePBX 17 from the
# upstream framework tarball. Afterwards FreePBX maintains its own modules
# (fwconsole ma ...), while zypper maintains the OS, Asterisk and drivers.
#
# See /usr/share/doc/packages/freepbx-host/README.SUSE

set -euo pipefail

TARBALL_URL=http://mirror.freepbx.org/modules/packages/freepbx/freepbx-17.0-latest.tgz
WEBROOT=/srv/www/freepbx
CGIBIN=/srv/www/cgi-bin
SRCDIR=/var/cache/freepbx-host
TEMPLATE=/usr/share/freepbx-host/freepbx-apache.conf.in
VHOST=/etc/apache2/vhosts.d/freepbx.conf
CDRDSN=MySQL-asteriskcdrdb
CDRDB=asteriskcdrdb
BACKUPDIR=/var/backups

tarball=
port=
yes=
modules=1

usage() {
	cat <<EOF
Usage: ${0##*/} [options]

Prepare this host for FreePBX 17 and run the FreePBX installer.

  --tarball FILE   use a local freepbx-17.0-*.tgz instead of downloading
                   $TARBALL_URL
  --port PORT      HTTP port for the FreePBX GUI (default: 80, or 8080 if
                   port 80 is already in use, e.g. by nginx)
  --no-modules     don't run 'fwconsole ma installlocal/upgradeall'
  --yes            don't ask for confirmation
  -h, --help       show this help

FreePBX takes over /etc/asterisk: it rewrites most files there from its
database. A backup of /etc/asterisk is stored in $BACKUPDIR first.
EOF
}

msg() { printf '>>> %s\n' "$*"; }
die() { printf 'freepbx-setup: %s\n' "$*" >&2; exit 1; }

while [ $# -gt 0 ]; do
	case "$1" in
	--tarball) tarball=${2:?}; shift;;
	--port) port=${2:?}; shift;;
	--no-modules) modules=;;
	--yes) yes=1;;
	-h|--help) usage; exit 0;;
	*) usage >&2; exit 1;;
	esac
	shift
done

[ "$(id -u)" = 0 ] || die "must be run as root"
[ -e /etc/freepbx.conf ] && die "FreePBX is already installed (/etc/freepbx.conf exists); use fwconsole to maintain it"
getent passwd asterisk >/dev/null || die "user asterisk missing (is asterisk installed?)"

port_in_use() {
	ss -ltnH "sport = :$1" | grep -q .
}

if [ -z "$port" ]; then
	if port_in_use 80 && ! ss -ltnpH 'sport = :80' | grep -q '"httpd'; then
		port=8080
	else
		port=80
	fi
fi
case "$port" in (*[!0-9]*|'') die "invalid port: $port";; esac

cat <<EOF

This will:
  - back up /etc/asterisk to $BACKUPDIR
  - enable and start mariadb, php-fpm, apache2 and asterisk
  - enable the Apache modules FreePBX needs, serve the GUI on port $port
  - register the MariaDB ODBC driver and the CDR DSN $CDRDSN
  - install FreePBX into $WEBROOT; FreePBX then takes over /etc/asterisk

EOF
if [ -z "$yes" ]; then
	read -r -p "Continue? [y/N] " answer
	case "$answer" in ([yY]*) ;; (*) exit 1;; esac
fi

# --- backup ----------------------------------------------------------------
backup=$BACKUPDIR/asterisk-etc-$(date +%Y%m%d-%H%M%S).tar.gz
msg "Backing up /etc/asterisk to $backup"
install -d -m 0700 "$BACKUPDIR"
tar -C /etc -czf "$backup" asterisk

# --- services --------------------------------------------------------------
msg "Enabling mariadb, php-fpm and asterisk"
systemctl enable --now mariadb.service php-fpm.service
systemctl enable --now asterisk.service
for i in $(seq 30); do
	asterisk -rx 'core show version' >/dev/null 2>&1 && break
	sleep 1
done
asterisk -rx 'core show version' >/dev/null 2>&1 || die "asterisk is not running"

# --- Apache ----------------------------------------------------------------
msg "Enabling Apache modules"
for m in rewrite proxy proxy_fcgi access_compat env setenvif headers expires; do
	a2enmod "$m" >/dev/null
done

if [ -e "$VHOST" ]; then
	msg "Keeping existing $VHOST"
else
	msg "Creating $VHOST (port $port)"
	listen=
	if [ "$port" != 80 ]; then
		listen="Listen $port"
		if grep -qE '^\s*Listen\s+80\s*$' /etc/apache2/listen.conf && port_in_use 80; then
			msg "Port 80 is in use: disabling 'Listen 80' in /etc/apache2/listen.conf"
			sed -i.freepbx-setup -E 's/^(\s*Listen\s+80\s*)$/#\1  # disabled by freepbx-setup, port 80 is in use/' /etc/apache2/listen.conf
		fi
	fi
	sed -e "s|@PORT@|$port|g" -e "s|@WEBROOT@|$WEBROOT|g" -e "s|@LISTEN@|$listen|" \
		"$TEMPLATE" > "$VHOST"
fi
install -d -o asterisk -g asterisk -m 0755 "$WEBROOT" "$CGIBIN"
systemctl enable apache2.service
systemctl restart apache2.service php-fpm.service

# --- ODBC --------------------------------------------------------------------
maodbc=$(rpm -ql mariadb-connector-odbc 2>/dev/null | grep -m1 '/libmaodbc\.so$' || true)
[ -n "$maodbc" ] || die "libmaodbc.so not found (install mariadb-connector-odbc)"
if ! odbcinst -q -d -n MariaDB >/dev/null 2>&1; then
	msg "Registering ODBC driver MariaDB ($maodbc)"
	odbcinst -i -d -r >/dev/null <<EOF
[MariaDB]
Description=MariaDB Connector/ODBC
Driver=$maodbc
EOF
fi
if ! grep -q "^\[$CDRDSN\]" /etc/odbc.ini 2>/dev/null; then
	msg "Adding ODBC DSN $CDRDSN to /etc/odbc.ini"
	cat >>/etc/odbc.ini <<EOF

[$CDRDSN]
Description=MariaDB connection to the FreePBX CDR database
Driver=MariaDB
Server=localhost
Database=$CDRDB
Port=3306
Socket=/run/mysql/mysql.sock
Option=3
Charset=utf8mb4
EOF
fi

# --- FreePBX -----------------------------------------------------------------
install -d -m 0755 "$SRCDIR"
if [ -z "$tarball" ]; then
	tarball=$SRCDIR/${TARBALL_URL##*/}
	msg "Downloading $TARBALL_URL"
	curl -fL --retry 3 -o "$tarball" "$TARBALL_URL"
fi
[ -r "$tarball" ] || die "cannot read $tarball"

rm -rf "$SRCDIR/freepbx"
tar -C "$SRCDIR" -xzf "$tarball"
[ -x "$SRCDIR/freepbx/install" ] || die "$tarball doesn't contain freepbx/install"

chown asterisk:asterisk /etc/asterisk
# FreePBX moves the AGI directory out of the RPM-owned /usr/share/asterisk
install -d -o asterisk -g asterisk -m 0755 /var/lib/asterisk/agi-bin

msg "Running the FreePBX installer"
cd "$SRCDIR/freepbx"
./install -n \
	--dbuser root \
	--user asterisk --group asterisk \
	--webroot "$WEBROOT" \
	--ampcgibin "$CGIBIN" \
	--astrundir /run/asterisk

if [ -n "$modules" ]; then
	msg "Installing local modules and upgrading all modules"
	fwconsole ma installlocal
	fwconsole ma upgradeall
fi
fwconsole chown
fwconsole reload

systemctl enable --now freepbx.service

cat <<EOF

FreePBX is installed. Next steps:
  - open http://$(hostname -f):$port/admin and create the admin user
  - /etc/asterisk backup: $backup
  - see /usr/share/doc/packages/freepbx-host/README.SUSE

EOF
