Files
cti/installer/install.sh
2026-10-14 23:05:02 +03:30

1203 lines
52 KiB
Bash
Executable File

#!/usr/bin/env bash
set -Eeuo pipefail
umask 022
export LANG=C LC_ALL=C LANGUAGE=C
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$SCRIPT_DIR/repo"
ASTERISK_IMAGE="andrius/asterisk:22"
APT_SOURCES_DIR=""
APT_ADOPTIUM_SOURCE=""
SEED_CONTAINER=""
APT_LOCK_TIMEOUT=600
APT_METADATA_READY=0
UI_TTY=0
[[ -t 1 && -t 2 ]] && UI_TTY=1
if ((UI_TTY)); then exec 3>/dev/tty; fi
UI_LOG_FILE=""
UI_MESSAGE="Preparing installer"
UI_TAIL_SOURCE=""
UI_NEEDS_CLEAR=1
UI_LAST_GEOMETRY=""
trap 'UI_NEEDS_CLEAR=1' WINCH
STAGE_NAMES=("System check" "System packages" "Java runtime" "Backup" "CTI package" "PostgreSQL" "Asterisk setup" "File ownership" "HTTPS setup" "Asterisk and service health")
STAGE_STATES=("WAIT" "WAIT" "WAIT" "WAIT" "WAIT" "WAIT" "WAIT" "WAIT" "WAIT" "WAIT")
CURRENT_STAGE=-1
INSTALL_APPROVED=0
PACKAGE_INSTALL_STARTED=0
STOPPED_CTI_SERVICES=()
JAVA_PRESTART_PID=""
for installer_arg in "$@"; do
case "$installer_arg" in
--yes) INSTALL_APPROVED=1 ;;
*) printf 'Unknown installer option: %s\n' "$installer_arg" >&2; exit 2 ;;
esac
done
LOG_DIR="$SCRIPT_DIR"
render_ui() {
((UI_TTY)) || return 0
{
local cols rows inner panel_width top left i status_color message_color line border separator geometry
local tail_count panel_height separator_width stage_count
cols="$(tput cols 2>/dev/null || printf '%s' "${COLUMNS:-80}")"
rows="$(tput lines 2>/dev/null || printf '%s' "${LINES:-24}")"
[[ "$cols" =~ ^[0-9]+$ ]] || cols=80
[[ "$rows" =~ ^[0-9]+$ ]] || rows=24
geometry="$cols:$rows"
if [[ "$geometry" != "$UI_LAST_GEOMETRY" ]]; then
UI_NEEDS_CLEAR=1
UI_LAST_GEOMETRY="$geometry"
fi
inner=120
if ((cols < inner + 4)); then inner=$((cols - 4)); fi
((inner < 1)) && inner=1
panel_width=$((inner + 2))
tail_count=5
stage_count=${#STAGE_NAMES[@]}
if ((rows < stage_count + 16)); then
tail_count=$((rows - stage_count - 11))
((tail_count < 1)) && tail_count=1
fi
((tail_count > 5)) && tail_count=5
panel_height=$((stage_count + 11 + tail_count))
top=$(((rows - panel_height) / 2 + 1)); ((top < 1)) && top=1
left=$(((cols - panel_width) / 2 + 1)); ((left < 1)) && left=1
local reset=$'\033[0m' blue_bg=$'\033[44m' cyan=$'\033[96;1m'
local white=$'\033[97m' green=$'\033[92;1m' yellow=$'\033[93;1m' red=$'\033[91m'
border="+$(printf '%*s' "$inner" '' | tr ' ' '-')+"
if ((UI_NEEDS_CLEAR)); then
printf '\033[0m\033[2J\033[H\033[?25l'
UI_NEEDS_CLEAR=0
else
printf '\033[?25l'
fi
printf '\033[%d;%dH%s%s%s' "$top" "$left" "$cyan" "$border" "$reset"
local panel_row=0
ui_panel_line() {
local text="$1" color="$2" text_len="$3" pl pr
((text_len > inner)) && text="${text:0:inner}" && text_len="$inner"
pl=$(((inner - text_len) / 2)); pr=$((inner - text_len - pl))
printf '\033[%d;%dH%s%s|%s%*s%s%s%s%s%*s%s%s|%s\033[K' \
"$((top + 1 + panel_row))" "$left" "$cyan" "$blue_bg" "$blue_bg" \
"$pl" '' "$color" "$text" "$reset" "$blue_bg" "$pr" '' "$cyan" "$blue_bg" "$reset"
((panel_row += 1))
}
ui_panel_line "" "$white" 0
ui_panel_line "RAYMAND CTI" "$cyan" 11
ui_panel_line "INSTALLER | VERSION 3.0.0" "$white" 28
separator_width=$((inner - 4)); ((separator_width < 1)) && separator_width=1
separator="$(printf '%*s' "$separator_width" '' | tr ' ' '-')"
ui_panel_line "$separator" "$cyan" "${#separator}"
for i in "${!STAGE_NAMES[@]}"; do
case "${STAGE_STATES[$i]}" in
DONE) status_color="$green" ;;
READY) status_color="$cyan" ;;
RUN) status_color="$yellow" ;;
FAIL) status_color="$red" ;;
*) status_color="$white" ;;
esac
local stage_label stage_state stage_gap
stage_label="$(printf '%02d/%02d %-24s' "$((i + 1))" "${#STAGE_NAMES[@]}" "${STAGE_NAMES[$i]}")"
stage_state="[$(printf '%-5s' "${STAGE_STATES[$i]}")]"
stage_gap=$((inner - 4 - ${#stage_label} - ${#stage_state}))
((stage_gap < 1)) && stage_gap=1
line="${stage_label}$(printf '%*s' "$stage_gap" '')${stage_state}"
ui_panel_line "$line" "$status_color" "${#line}"
done
ui_panel_line "$separator" "$cyan" "${#separator}"
if ((CURRENT_STAGE >= 0)); then
line="CURRENT: ${STAGE_NAMES[$CURRENT_STAGE]}"
else
line="CURRENT: Initializing"
fi
ui_panel_line "" "$white" 0
ui_panel_line "$line" "$white" "${#line}"
message_color="$yellow"
if ((CURRENT_STAGE >= 0)) && [[ "${STAGE_STATES[$CURRENT_STAGE]}" == FAIL ]]; then message_color="$red"; fi
line=" $UI_MESSAGE"
ui_panel_line "$line" "$message_color" "${#line}"
line="THIS INSTALL RUN (last 5 lines)"
ui_panel_line "$line" "$cyan" "${#line}"
local -a ui_tail_lines=()
if [[ -n "$UI_TAIL_SOURCE" && -r "$UI_TAIL_SOURCE" ]]; then
mapfile -t ui_tail_lines < <(
tail -n 50 "$UI_TAIL_SOURCE" 2>/dev/null \
| tr '\t' ' ' \
| sed -E 's/\x1B\[[0-?]*[ -/]*[@-~]//g; s/\r$//; s/ +/ /g; s/^ +//' \
| awk 'NF { lines[++count] = $0 } END {
first = count - 4
if (first < 1) first = 1
for (i = first; i <= count; i++) print lines[i]
}'
)
fi
for ((i = 0; i < tail_count; i++)); do
if ((i < ${#ui_tail_lines[@]})); then
line=" ${ui_tail_lines[$i]}"
if ((${#line} > inner - 4)); then
line="...${line: -$((inner - 7))}"
fi
ui_panel_line "$line" "$white" "${#line}"
else
ui_panel_line "" "$white" 0
fi
done
printf '\033[%d;%dH%s%s%s' "$((top + panel_height - 1))" "$left" "$cyan" "$border" "$reset"
printf '\033[%d;1H' "$rows"
} >&3
}
INSTALL_LOG=""
log_event() {
[[ -n "$INSTALL_LOG" ]] || return 0
printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S%z')" "$*" >&4
}
append_captured_output() {
local label="$1"
log_event "----- BEGIN OUTPUT: $label -----"
cat "$UI_LOG_FILE" >&4
log_event "----- END OUTPUT: $label -----"
}
log() {
if ((UI_TTY)); then log_event "INFO: $*"; UI_MESSAGE="$*"; render_ui
else printf '[Raymand CTI-install] %s\n' "$*"; fi
}
stage_begin() {
CURRENT_STAGE="$1"
STAGE_STATES[$CURRENT_STAGE]="RUN"
log_event "STAGE $((CURRENT_STAGE + 1))/${#STAGE_NAMES[@]} START: ${STAGE_NAMES[$CURRENT_STAGE]} — $2"
UI_MESSAGE="$2"
render_ui
}
stage_done() {
STAGE_STATES[$1]="DONE"
log_event "STAGE $(( $1 + 1 ))/${#STAGE_NAMES[@]} DONE: ${STAGE_NAMES[$1]}"
render_ui
}
stage_skip() {
STAGE_STATES[$1]="READY"
log_event "STAGE $(( $1 + 1 ))/${#STAGE_NAMES[@]} SKIP: ${STAGE_NAMES[$1]} — $2"
UI_MESSAGE="$2"
render_ui
}
fail() {
if ((CURRENT_STAGE >= 0)); then STAGE_STATES[$CURRENT_STAGE]="FAIL"; fi
log_event "ERROR: $* (full log: $LOG_DIR/latest.log)"
if ((UI_TTY)); then UI_MESSAGE="ERROR: $*"; render_ui
else printf '[Raymand CTI-install] ERROR: %s\nFull log: %s/latest.log\n' "$*" "$LOG_DIR" >&2; fi
exit 1
}
confirm_installation() {
local answer=""
if ((INSTALL_APPROVED)); then
log_event "INSTALLATION CONFIRMED: --yes option supplied; backup will still be mandatory"
return 0
fi
if [[ ! -r /dev/tty || ! -w /dev/tty ]]; then
fail "Interactive confirmation is required. Re-run with --yes only after reviewing the backup warning."
fi
log_event "WARNING: installation may update the CTI package, services and database schema"
if ((UI_TTY)); then printf '\033[0m\033[?25h' >&3; fi
{
printf '\nWARNING: This installation may update Raymand CTI and restart services.\n'
printf 'A backup of the current CTI application files and database will be created before package/database changes.\n'
printf 'Check that /var/backups has enough free space. The installer will not drop the database.\n'
printf 'Type Y or YES to continue, or anything else to cancel: '
} >/dev/tty
IFS= read -r answer </dev/tty || answer=""
answer="${answer,,}"
if [[ "$answer" != y && "$answer" != yes ]]; then
log_event "Installation cancelled by user before system changes"
printf 'Installation cancelled. No CTI package or database changes were made.\n' >/dev/tty
exit 0
fi
log_event "INSTALLATION CONFIRMED: user accepted the backup warning"
UI_NEEDS_CLEAR=1
}
postgres_command() {
# PostgreSQL tools must not inherit /root/installer as their working directory.
(cd /tmp && runuser -u postgres -- "$@")
}
quiet_command() {
if ((UI_TTY)); then
log_event "COMMAND: $*"
if "$@" >"$UI_LOG_FILE" 2>&1; then
append_captured_output "$*"
else
local rc=$?
append_captured_output "$* (exit $rc)"
((CURRENT_STAGE >= 0)) && STAGE_STATES[$CURRENT_STAGE]="FAIL"
UI_MESSAGE="Command failed: $(tail -n 1 "$UI_LOG_FILE" | tr -cd '[:print:]' | cut -c1-48)"
render_ui
return "$rc"
fi
else
"$@"
fi
}
if [[ "$EUID" -ne 0 ]]; then
if command -v sudo >/dev/null 2>&1; then
if [[ -n "${RAYMAND_CTI_BACKUP_DIR:-}" ]]; then
exec sudo env "RAYMAND_CTI_BACKUP_DIR=$RAYMAND_CTI_BACKUP_DIR" "$SCRIPT_DIR/install.sh" "$@"
fi
exec sudo "$SCRIPT_DIR/install.sh" "$@"
fi
fail "Run as root. On a minimal Debian install, use 'su -' first because sudo may not be installed yet."
fi
INSTALL_LOG="$LOG_DIR/installer-$(date '+%Y%m%d-%H%M%S')-$$.log"
exec 5>/run/lock/raymand-cti-installer.lock
flock -n 5 || fail "Another Raymand CTI installer is already running"
: >"$INSTALL_LOG"
chmod 0600 "$INSTALL_LOG"
ln -sfn "$(basename "$INSTALL_LOG")" "$LOG_DIR/latest.log"
UI_TAIL_SOURCE="$INSTALL_LOG"
if ((UI_TTY)); then
exec 4>>"$INSTALL_LOG"
exec > >(tee -a "$INSTALL_LOG" >/dev/null) 2>&1
else
exec 4>>"$INSTALL_LOG"
exec > >(tee -a "$INSTALL_LOG") 2>&1
fi
log_event "Installer started: user=root pid=$$ terminal=$UI_TTY arguments=$*"
trap 'rc=$?; log_event "Installer exiting with status $rc"' EXIT
[[ -r /etc/os-release ]] || fail "Cannot identify the operating system"
# shellcheck disable=SC1091
source /etc/os-release
[[ "${ID:-}" == debian ]] || fail "This installer supports Debian 11, 12 and 13 only (detected ${PRETTY_NAME:-unknown})"
DEBIAN_MAJOR="${VERSION_ID%%.*}"
[[ "$DEBIAN_MAJOR" == 11 || "$DEBIAN_MAJOR" == 12 || "$DEBIAN_MAJOR" == 13 ]] \
|| fail "This installer supports Debian 11, 12 and 13 only (detected ${VERSION_ID:-unknown})"
CODENAME="${VERSION_CODENAME:-}"
[[ -n "$CODENAME" ]] || fail "Debian VERSION_CODENAME is missing"
ARCH="$(dpkg --print-architecture)"
[[ "$ARCH" == amd64 ]] || fail "This installer supports amd64 only (detected $ARCH)"
stage_begin 0 "Checking Debian version, architecture and installer files"
PACKAGE_DEB="$REPO_DIR/raymand-cti-amd64.deb"
[[ -s "$PACKAGE_DEB" ]] || fail "Installer package not found: $PACKAGE_DEB"
[[ -s "$PACKAGE_DEB.sha256" ]] || fail "Package checksum not found: $PACKAGE_DEB.sha256"
if ((UI_TTY)); then
(cd "$REPO_DIR" && sha256sum -c raymand-cti-amd64.deb.sha256) >/dev/null \
|| fail "Package checksum validation failed"
else
(cd "$REPO_DIR" && sha256sum -c raymand-cti-amd64.deb.sha256) \
|| fail "Package checksum validation failed"
fi
PACKAGE_PROPERTIES="$(dpkg-deb --fsys-tarfile "$PACKAGE_DEB" | tar -xOf - ./opt/cti/application.properties)" \
|| fail "Cannot inspect the installer license policy"
grep -qx 'pline.license.enforce=true' <<<"$PACKAGE_PROPERTIES" \
|| fail "This package does not enforce license validation and cannot be installed"
PACKAGE_SERVICE="$(dpkg-deb --fsys-tarfile "$PACKAGE_DEB" | tar -xOf - ./etc/systemd/system/raymnad-cti.service)" \
|| fail "Cannot inspect the installer service license policy"
grep -Fq -- '--pline.license.enforce=true' <<<"$PACKAGE_SERVICE" \
|| fail "This package does not force license validation at service startup and cannot be installed"
stage_done 0
confirm_installation
cleanup() {
local rc=$?
if [[ -n "$JAVA_PRESTART_PID" ]] && kill -0 "$JAVA_PRESTART_PID" 2>/dev/null; then
kill -TERM -- "-$JAVA_PRESTART_PID" 2>/dev/null || true
fi
# A failed backup must not leave the customer's unchanged application stopped.
if ((rc != 0 && PACKAGE_INSTALL_STARTED == 0)); then
for stopped_service in "${STOPPED_CTI_SERVICES[@]}"; do
systemctl start "$stopped_service" || true
done
fi
if ((UI_TTY)); then printf '\033[0m\033[?25h' >&3; fi
if [[ -n "$SEED_CONTAINER" ]]; then
docker rm -f "$SEED_CONTAINER" >/dev/null 2>&1 || true
fi
if [[ -n "$APT_ADOPTIUM_SOURCE" ]]; then rm -f -- "$APT_ADOPTIUM_SOURCE"; fi
if [[ -n "$APT_SOURCES_DIR" ]]; then rm -rf -- "$APT_SOURCES_DIR"; fi
if [[ -n "$UI_LOG_FILE" ]]; then rm -f -- "$UI_LOG_FILE"; fi
log_event "Installer cleanup complete (status $rc)"
log_event "Installer exiting with status $rc"
}
trap cleanup EXIT
APT_SOURCES_DIR="$(mktemp -d "${TMPDIR:-/tmp}/raymand-cti-apt.XXXXXX")"
UI_LOG_FILE="$APT_SOURCES_DIR/installer.log"
chmod 0755 "$APT_SOURCES_DIR"
STAGED_PACKAGE="$APT_SOURCES_DIR/raymand-cti-amd64.deb"
install -m 0644 "$PACKAGE_DEB" "$STAGED_PACKAGE"
apt_cmd() {
local -a apt_options=(
-o Acquire::ForceIPv4=true
-o Acquire::Retries=1
-o Acquire::http::Timeout=30
-o Acquire::https::Timeout=30
-o Acquire::Languages=none
-o "DPkg::Lock::Timeout=$APT_LOCK_TIMEOUT"
-o Dpkg::Use-Pty=0
-o Dpkg::Progress-Fancy=0
)
log_event "COMMAND: apt-get $*"
if ((UI_TTY)); then
: >"$UI_LOG_FILE"
UI_TAIL_SOURCE="$UI_LOG_FILE"
UI_MESSAGE="Running APT: $*"
render_ui
apt-get "${apt_options[@]}" "$@" >"$UI_LOG_FILE" 2>&1 &
local apt_pid=$!
while kill -0 "$apt_pid" 2>/dev/null; do
render_ui
sleep 2 || true
done
if wait "$apt_pid"; then
UI_TAIL_SOURCE="$INSTALL_LOG"
append_captured_output "apt-get $*"
else
local rc=$?
UI_TAIL_SOURCE="$INSTALL_LOG"
append_captured_output "apt-get $* (exit $rc)"
((CURRENT_STAGE >= 0)) && STAGE_STATES[$CURRENT_STAGE]="FAIL"
UI_MESSAGE="APT failed: $(tail -n 1 "$UI_LOG_FILE" | tr -cd '[:print:]' | cut -c1-48)"
render_ui
return "$rc"
fi
else
apt-get "${apt_options[@]}" "$@"
fi
}
apt_policy() {
apt-cache policy "$@"
}
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l
APT_OPTIONS=(-y --no-install-recommends)
apt_update() {
log "Refreshing package metadata from the server's configured APT repositories"
apt_cmd update
APT_METADATA_READY=1
}
package_installed() { dpkg-query -W -f='${db:Status-Abbrev}' "$1" 2>/dev/null | grep -q '^ii'; }
stage_begin 1 "Checking required system packages"
APT_PACKAGES=(
adduser ca-certificates cifs-utils curl dmidecode ethtool ffmpeg ghostscript gnupg
htop iproute2 iputils-ping libsox-fmt-all libtiff-tools net-tools nfs-common openssl
nginx openssh-server postgresql postgresql-client python3-minimal sngrep sudo sox tcpdump tzdata
procps util-linux
)
if ! command -v docker >/dev/null 2>&1 || ! systemctl cat docker.service >/dev/null 2>&1; then
APT_PACKAGES+=(docker.io)
fi
# Debian 13 split the Docker client into its own package. Since this installer
# disables Recommends, install the CLI explicitly when the release provides it.
if ! docker compose version >/dev/null 2>&1 \
&& ! command -v docker-compose >/dev/null 2>&1; then
APT_PACKAGES+=(docker-compose)
fi
MISSING_APT_PACKAGES=()
for package in "${APT_PACKAGES[@]}"; do
package_installed "$package" || MISSING_APT_PACKAGES+=("$package")
done
if ((${#MISSING_APT_PACKAGES[@]})) || ! package_installed docker-cli; then
apt_update
fi
if ! package_installed docker-cli; then
if apt_policy docker-cli | awk '$1 == "Candidate:" && $2 != "(none)" { found = 1 } END { exit !found }'; then
MISSING_APT_PACKAGES+=(docker-cli)
fi
fi
if ((${#MISSING_APT_PACKAGES[@]})); then
log "Installing missing system runtime packages: ${MISSING_APT_PACKAGES[*]}"
apt_cmd install "${APT_OPTIONS[@]}" "${MISSING_APT_PACKAGES[@]}"
else
stage_skip 1 "Required packages are installed; skipping APT metadata refresh"
fi
command -v docker >/dev/null 2>&1 || fail "Docker CLI is missing after installing docker.io/docker-cli"
systemctl cat docker.service >/dev/null 2>&1 || fail "Docker service is missing after installing docker.io"
docker compose version >/dev/null 2>&1 || command -v docker-compose >/dev/null 2>&1 \
|| fail "Docker Compose is missing after installing docker-compose"
if [[ "${STAGE_STATES[1]}" == "RUN" ]]; then stage_done 1; fi
JAVA_RUNTIME=openjdk-25-jre-headless
JAVA_VERSION="$(java -XshowSettings:properties -version 2>&1 | awk -F'= ' '/java.specification.version/ { print $2; exit }' || true)"
stage_begin 2 "Checking active Java runtime"
if [[ "$JAVA_VERSION" == 25 ]]; then
stage_skip 2 "Java 25 is already active"
else
((APT_METADATA_READY)) || apt_update
if ! apt_policy "$JAVA_RUNTIME" | awk '$1 == "Candidate:" && $2 != "(none)" { found = 1 } END { exit !found }'; then
log "OpenJDK 25 is not in this Debian release; adding the Eclipse Adoptium repository"
ADOPTIUM_KEYRING="$APT_SOURCES_DIR/adoptium.gpg"
curl --fail --silent --show-error --location \
https://packages.adoptium.net/artifactory/api/gpg/key/public \
| gpg --dearmor --batch --yes --output "$ADOPTIUM_KEYRING" \
|| fail "Could not download and install the Adoptium repository signing key"
chmod 0644 "$ADOPTIUM_KEYRING"
APT_ADOPTIUM_SOURCE="${APT_ADOPTIUM_SOURCE:-/etc/apt/sources.list.d/raymand-cti-adoptium-$$.list}"
printf 'deb [signed-by=%s] https://packages.adoptium.net/artifactory/deb %s main\n' \
"$ADOPTIUM_KEYRING" "$CODENAME" >"$APT_ADOPTIUM_SOURCE"
apt_cmd update
APT_METADATA_READY=1
JAVA_RUNTIME=temurin-25-jdk
fi
log "Installing Java 25 runtime ($JAVA_RUNTIME)"
apt_cmd install "${APT_OPTIONS[@]}" "$JAVA_RUNTIME"
# Select Java 25 explicitly; --auto could select an existing Java 26 instead.
JAVA_25_BINARY=""
for java_candidate in /usr/lib/jvm/*/bin/java; do
[[ -x "$java_candidate" ]] || continue
candidate_version="$("$java_candidate" -XshowSettings:properties -version 2>&1 \
| awk -F'= ' '/java.specification.version/ { print $2; exit }' || true)"
if [[ "$candidate_version" == 25 ]]; then JAVA_25_BINARY="$java_candidate"; break; fi
done
[[ -n "$JAVA_25_BINARY" ]] || fail "Java 25 package installed but its executable was not found"
quiet_command update-alternatives --set java "$JAVA_25_BINARY"
JAVA_VERSION="$(java -XshowSettings:properties -version 2>&1 | awk -F'= ' '/java.specification.version/ { print $2; exit }')"
stage_done 2
fi
[[ "$JAVA_VERSION" == 25 ]] || fail "Java 25 is required, but the active java command reports ${JAVA_VERSION:-unknown}"
# Nginx must wait until the package and HTTPS configuration have been prepared.
stage_begin 3 "Preparing PostgreSQL for the pre-install backup"
for service in postgresql; do
if ! systemctl is-enabled --quiet "$service.service" 2>/dev/null \
|| ! systemctl is-active --quiet "$service.service"; then
quiet_command systemctl enable --now "$service.service"
fi
done
stage_begin 3 "Backing up existing CTI application files and database"
BACKUP_ROOT="${RAYMAND_CTI_BACKUP_DIR:-/var/backups/raymand-cti}"
[[ "$BACKUP_ROOT" == /* ]] || fail "Backup directory must be an absolute path: $BACKUP_ROOT"
install -d -m 0700 "$BACKUP_ROOT"
BACKUP_DIR="$BACKUP_ROOT/installer-$(date '+%Y%m%d-%H%M%S')-$$"
install -d -m 0700 "$BACKUP_DIR"
chmod 0700 "$BACKUP_DIR"
BACKUP_PATHS=()
BACKUP_BYTES=0
for backup_path in \
/opt/cti/raymandcti.jar \
/opt/cti/application.properties \
/opt/cti/license.lic \
/opt/cti/features.json \
/opt/cti/SipParameters.json \
/opt/cti/pjsip_parameters.json \
/opt/cti/ha-config.conf \
/opt/cti/resource \
/opt/cti/tools \
/opt/cti/scripts \
/opt/cti/base/etc/asterisk \
/opt/cti/voices-box \
/opt/cti/docker-compose.yml \
/opt/cti/nginx-management \
/etc/nginx \
/etc/ssl/raymand-cti \
/var/www/cti; do
if [[ -e "$backup_path" ]]; then
BACKUP_PATHS+=("${backup_path#/}")
path_bytes="$(du -sB1 -- "$backup_path" | awk '{print $1}')"
BACKUP_BYTES=$((BACKUP_BYTES + path_bytes))
fi
done
BACKUP_DB_NAME=""
BACKUP_DB_PORT=""
BACKUP_DB_BYTES=0
if [[ -r /opt/cti/application.properties ]]; then
BACKUP_DB_URL="$(awk 'index($0, "spring.datasource.url=") == 1 {sub(/^[^=]*=/, ""); sub(/\r$/, ""); print; exit}' /opt/cti/application.properties)"
if [[ "$BACKUP_DB_URL" =~ ^jdbc:postgresql://(127\.0\.0\.1|localhost):([0-9]+)/([A-Za-z0-9_-]+)(\?.*)?$ ]]; then
BACKUP_DB_PORT="${BASH_REMATCH[2]}"
BACKUP_DB_NAME="${BASH_REMATCH[3]}"
DB_EXISTS="$(postgres_command env PGPORT="$BACKUP_DB_PORT" \
psql -X -q -d postgres -Atqc "SELECT 1 FROM pg_database WHERE datname = '$BACKUP_DB_NAME'")" \
|| fail "Could not inspect the configured PostgreSQL database before backup"
if [[ "$DB_EXISTS" == 1 ]]; then
BACKUP_DB_BYTES="$(postgres_command env PGPORT="$BACKUP_DB_PORT" \
psql -X -q -d postgres -Atqc "SELECT pg_database_size('$BACKUP_DB_NAME')")" \
|| fail "Could not estimate the PostgreSQL backup size"
[[ "$BACKUP_DB_BYTES" =~ ^[0-9]+$ ]] || fail "PostgreSQL returned an invalid database size"
BACKUP_BYTES=$((BACKUP_BYTES + BACKUP_DB_BYTES))
else
log "The configured CTI database does not exist yet; database backup is not needed"
fi
else
fail "Cannot safely identify the configured local CTI database for backup"
fi
else
log "No existing CTI database configuration was found; database backup is not needed"
fi
if ((BACKUP_BYTES > 0)); then
BACKUP_REQUIRED_BYTES=$((BACKUP_BYTES + 67108864))
BACKUP_FREE_BYTES="$(df -PB1 "$BACKUP_ROOT" | awk 'NR == 2 {print $4}')"
[[ "$BACKUP_FREE_BYTES" =~ ^[0-9]+$ ]] || fail "Could not check free space for the backup"
((BACKUP_FREE_BYTES >= BACKUP_REQUIRED_BYTES)) \
|| fail "Not enough free space for a safe backup. Set RAYMAND_CTI_BACKUP_DIR to a mounted backup disk and retry."
fi
for cti_service in raymnad-cti.service pline.service raymandcti.service; do
if systemctl is-active --quiet "$cti_service"; then
log "Stopping $cti_service before backing up and replacing the application"
quiet_command systemctl stop "$cti_service"
STOPPED_CTI_SERVICES+=("$cti_service")
fi
done
if ((${#BACKUP_PATHS[@]})); then
log "Saving existing Java application, configuration and web interface to $BACKUP_DIR"
quiet_command tar -czf "$BACKUP_DIR/application-files.tar.gz" -C / "${BACKUP_PATHS[@]}"
chmod 0600 "$BACKUP_DIR/application-files.tar.gz"
else
log "No existing CTI application files were found; this appears to be a fresh install"
fi
if [[ -n "$BACKUP_DB_NAME" && "${DB_EXISTS:-}" == 1 ]]; then
log "Creating a PostgreSQL backup of database $BACKUP_DB_NAME"
log_event "COMMAND: pg_dump custom-format database=$BACKUP_DB_NAME"
if postgres_command env PGPORT="$BACKUP_DB_PORT" pg_dump --format=custom \
--dbname="$BACKUP_DB_NAME" >"$BACKUP_DIR/database.dump" 2>"$UI_LOG_FILE"; then
append_captured_output "PostgreSQL database backup ($BACKUP_DB_NAME)"
chmod 0600 "$BACKUP_DIR/database.dump"
postgres_command pg_restore --list <"$BACKUP_DIR/database.dump" >/dev/null \
|| fail "PostgreSQL backup archive could not be verified"
else
backup_rc=$?
append_captured_output "PostgreSQL database backup failed (exit $backup_rc)"
fail "PostgreSQL backup failed; CTI package and database changes were stopped"
fi
fi
{
printf 'Raymand CTI pre-install backup\n'
printf 'Created: %s\n' "$(date --iso-8601=seconds)"
printf 'Installer package version: %s\n' "$(dpkg-deb --field "$PACKAGE_DEB" Version)"
printf 'Installer package checksum: %s\n' "$(sha256sum "$PACKAGE_DEB" | awk '{print $1}')"
printf 'Application files: %s\n' "$([[ -f "$BACKUP_DIR/application-files.tar.gz" ]] && printf saved || printf none)"
printf 'Database: %s\n' "${BACKUP_DB_NAME:-none}"
printf 'Database dump: %s\n' "$([[ -s "$BACKUP_DIR/database.dump" ]] && printf saved || printf none)"
printf 'Restore only after reviewing the target paths/database and stopping Raymand CTI.\n'
} >"$BACKUP_DIR/README.txt"
chmod 0600 "$BACKUP_DIR/README.txt"
(
cd "$BACKUP_DIR"
for backup_file in README.txt application-files.tar.gz database.dump; do
[[ ! -s "$backup_file" ]] || sha256sum "$backup_file"
done
) >"$BACKUP_DIR/SHA256SUMS"
chmod 0600 "$BACKUP_DIR/SHA256SUMS"
log "Pre-install backup completed at $BACKUP_DIR"
stage_done 3
stage_begin 4 "Force reinstalling Raymand CTI package"
PACKAGE_VERSION="$(dpkg-deb --field "$PACKAGE_DEB" Version)"
PACKAGE_SHA="$(sha256sum "$PACKAGE_DEB" | awk '{print $1}')"
PACKAGE_MARKER=/opt/cti/.raymand-cti-package-sha256
log "Force reinstalling Raymand CTI package version $PACKAGE_VERSION"
PACKAGE_INSTALL_STARTED=1
apt_cmd install "${APT_OPTIONS[@]}" \
-o 'Dpkg::Options::=--force-confold' \
-o 'Dpkg::Options::=--force-overwrite' --reinstall "$STAGED_PACKAGE"
EXPECTED_JAR_SHA="$(dpkg-deb --fsys-tarfile "$STAGED_PACKAGE" \
| tar -xOf - ./opt/cti/raymandcti.jar | sha256sum | awk '{print $1}')" \
|| fail "Cannot read the application JAR checksum from the installer package"
INSTALLED_JAR_SHA="$(sha256sum /opt/cti/raymandcti.jar | awk '{print $1}')" \
|| fail "Cannot read the installed application JAR checksum"
[[ "$INSTALLED_JAR_SHA" == "$EXPECTED_JAR_SHA" ]] \
|| fail "Installed application JAR differs from the installer package; replacement was not verified"
log "Application JAR replacement verified (SHA256: $INSTALLED_JAR_SHA)"
install -d -m 0755 /opt/cti
printf '%s\n' "$PACKAGE_SHA" >/opt/cti/.raymand-cti-package-sha256
PACKAGE_CHANGED=1
stage_done 4
if ! getent passwd pline >/dev/null 2>&1; then
useradd --system --home-dir /opt/cti --no-create-home --shell /usr/sbin/nologin pline
fi
getent group docker >/dev/null 2>&1 || groupadd docker
if ! id -nG pline | tr ' ' '\n' | grep -qx docker; then usermod -aG docker pline; fi
PLINE_UID="$(id -u pline)"
PLINE_GID="$(id -g pline)"
read_property() {
local wanted="$1"
awk -v wanted="$wanted" 'index($0, wanted "=") == 1 {sub(/^[^=]*=/, ""); sub(/\r$/, ""); print; exit}' \
/opt/cti/application.properties
}
DB_URL="$(read_property spring.datasource.url)"
DB_USER="$(read_property spring.datasource.username)"
DB_PASSWORD="$(read_property spring.datasource.password)"
BACKEND_PORT="$(read_property server.port)"
BACKEND_PORT="${BACKEND_PORT:-8080}"
[[ "$BACKEND_PORT" =~ ^[0-9]{1,5}$ ]] && ((10#$BACKEND_PORT >= 1 && 10#$BACKEND_PORT <= 65535)) \
|| fail "Invalid server.port in application.properties"
BACKEND_READINESS_URL="http://127.0.0.1:$BACKEND_PORT/actuator/health/readiness"
[[ "$DB_URL" =~ ^jdbc:postgresql://(127\.0\.0\.1|localhost):([0-9]+)/([A-Za-z0-9_-]+)(\?.*)?$ ]] \
|| fail "Expected a local PostgreSQL URL in /opt/cti/application.properties"
DB_HOST="${BASH_REMATCH[1]}"
DB_PORT="${BASH_REMATCH[2]}"
DB_NAME="${BASH_REMATCH[3]}"
[[ "$DB_USER" =~ ^[A-Za-z_][A-Za-z0-9_-]*$ ]] || fail "Unsupported PostgreSQL user in application.properties"
[[ -n "$DB_PASSWORD" ]] || fail "PostgreSQL password is missing from application.properties"
stage_begin 5 "Checking PostgreSQL role and database"
postgres_command env PGPORT="$DB_PORT" psql -X -q -v ON_ERROR_STOP=1 \
--set=db_user="$DB_USER" --set=db_password="$DB_PASSWORD" --set=db_name="$DB_NAME" <<'SQL'
SELECT format('CREATE ROLE %I LOGIN PASSWORD %L', :'db_user', :'db_password')
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = :'db_user')
\gexec
SELECT format('CREATE DATABASE %I OWNER %I', :'db_name', :'db_user')
WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = :'db_name')
\gexec
SQL
if ! PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" \
-d "$DB_NAME" -X -v ON_ERROR_STOP=1 -Atqc 'SELECT 1' >/dev/null; then
fail "Cannot connect to the configured PostgreSQL database; check its existing credentials"
fi
# Older releases mapped several many-to-one relations as one-to-one. Find the
# application's tables by name across user schemas because postgres and the CTI
# database role can have different search_path values. Remove only conflicting
# single-column UNIQUE constraints; keep rows, foreign keys and other constraints.
log "Checking database relationship constraints"
postgres_command env PGPORT="$DB_PORT" psql -d "$DB_NAME" -X -v ON_ERROR_STOP=1 <<'SQL'
DO $$
DECLARE
target record;
table_row record;
constraint_row record;
BEGIN
FOR target IN
SELECT * FROM (VALUES
('tbl_sip_profile_details', 'sip_profile_id'),
('tbl_sip_users', 'sip_profile_id'),
('tbl_sip_users', 'sip_user_group_id'),
('tbl_sip_trunks', 'sip_profile_id'),
('tbl_call_access_list_members', 'tbl_call_access_list_id'),
('tbl_call_access_list_members', 'sip_user_id'),
('tbl_outbound_route_trunks', 'sip_trunk_id'),
('tbl_ringing_music_on_holds', 'internal_music_hold_id'),
('tbl_ringing_music_on_holds', 'external_music_hold_id')
) AS relations(table_name, column_name)
LOOP
FOR table_row IN
SELECT t.oid AS table_oid, n.nspname AS schema_name, t.relname AS table_name,
a.attnum AS column_number
FROM pg_class t
JOIN pg_namespace n ON n.oid = t.relnamespace
JOIN pg_attribute a ON a.attrelid = t.oid
WHERE t.relname = target.table_name
AND t.relkind IN ('r', 'p')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND n.nspname NOT LIKE 'pg_%'
AND a.attname = target.column_name
AND NOT a.attisdropped
LOOP
FOR constraint_row IN
SELECT c.conname
FROM pg_constraint c
WHERE c.conrelid = table_row.table_oid
AND c.contype = 'u'
AND c.conkey = ARRAY[table_row.column_number]::smallint[]
LOOP
RAISE NOTICE 'Removing obsolete UNIQUE constraint %.%.%',
table_row.schema_name, table_row.table_name, constraint_row.conname;
EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I',
table_row.schema_name, table_row.table_name, constraint_row.conname);
END LOOP;
END LOOP;
END LOOP;
END;
$$;
SQL
REMAINING_RELATION_UNIQUES="$(postgres_command env PGPORT="$DB_PORT" psql -d "$DB_NAME" -X -q -v ON_ERROR_STOP=1 -Atqc "
WITH targets(table_name, column_name) AS (VALUES
('tbl_sip_profile_details', 'sip_profile_id'),
('tbl_sip_users', 'sip_profile_id'),
('tbl_sip_users', 'sip_user_group_id'),
('tbl_sip_trunks', 'sip_profile_id'),
('tbl_call_access_list_members', 'tbl_call_access_list_id'),
('tbl_call_access_list_members', 'sip_user_id'),
('tbl_outbound_route_trunks', 'sip_trunk_id'),
('tbl_ringing_music_on_holds', 'internal_music_hold_id'),
('tbl_ringing_music_on_holds', 'external_music_hold_id')
)
SELECT string_agg(format('%I.%I.%I', n.nspname, t.relname, c.conname), ', ')
FROM targets x
JOIN pg_class t ON t.relname = x.table_name AND t.relkind IN ('r', 'p')
JOIN pg_namespace n ON n.oid = t.relnamespace
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attname = x.column_name AND NOT a.attisdropped
JOIN pg_constraint c ON c.conrelid = t.oid AND c.contype = 'u'
AND c.conkey = ARRAY[a.attnum]::smallint[]
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
AND n.nspname NOT LIKE 'pg_%'
")"
[[ -z "$REMAINING_RELATION_UNIQUES" ]] \
|| fail "Conflicting database relationship constraints remain: $REMAINING_RELATION_UNIQUES"
log "Database relationship constraints verified"
unset DB_PASSWORD
stage_done 5
set_property() {
local key="$1" value="$2" escaped
escaped="${key//./\\.}"
if awk -v key="$key" -v value="$value" '
index($0, key "=") == 1 { count++; if (substr($0, length(key) + 2) != value) bad = 1 }
END { exit !(count > 0 && !bad) }
' /opt/cti/application.properties; then return 0; fi
if grep -qE "^[[:space:]]*${escaped}=" /opt/cti/application.properties; then
sed -i -E "s|^[[:space:]]*${escaped}=.*|${key}=${value}|" /opt/cti/application.properties
else
printf '\n%s=%s\n' "$key" "$value" >>/opt/cti/application.properties
fi
}
# Keep a stable per-install token for trusted programs that call the loopback-only
# Asterisk command API. Never rotate it during an ordinary upgrade.
if ! grep -qE '^[[:space:]]*pline\.local-asterisk-api-token=[^[:space:]]+' /opt/cti/application.properties; then
LOCAL_ASTERISK_API_TOKEN="$(od -An -N32 -tx1 /dev/urandom | tr -d '[:space:]')"
[[ "$LOCAL_ASTERISK_API_TOKEN" =~ ^[0-9a-f]{64}$ ]] \
|| fail "Could not generate the local Asterisk API token"
set_property pline.local-asterisk-api-token "$LOCAL_ASTERISK_API_TOKEN"
unset LOCAL_ASTERISK_API_TOKEN
fi
# Keep Hibernate schema updates enabled on both fresh installs and upgrades.
# Existing databases are preserved; Hibernate applies compatible schema changes.
set_property spring.jpa.hibernate.ddl-auto update
set_property pline.version "$PACKAGE_VERSION"
set_property pline.app_name RaymandCTI
set_property management.endpoint.health.probes.enabled true
set_property asterisk.docker-mode true
set_property asterisk.container-name asterisk
set_property asterisk.container-puid "$PLINE_UID"
set_property asterisk.container-pgid "$PLINE_GID"
set_property asterisk.base-path /opt/cti
set_property asterisk.auto-start-docker true
ASTERISK_BASE=/opt/cti
stage_begin 6 "Checking Asterisk image and configuration"
quiet_command systemctl enable --now docker.service
for directory in \
"$ASTERISK_BASE/base/etc/asterisk" \
"$ASTERISK_BASE/base/var/lib/asterisk" \
"$ASTERISK_BASE/base/var/lib/asterisk/moh" \
"$ASTERISK_BASE/base/var/log/asterisk" \
"$ASTERISK_BASE/base/var/spool/asterisk" \
"$ASTERISK_BASE/base/fax" "$ASTERISK_BASE/base/sounds" \
"$ASTERISK_BASE/voices-box/sounds" \
"$ASTERISK_BASE/voices-box/music-on-holds" \
"$ASTERISK_BASE/log" "$ASTERISK_BASE/tmp" "$ASTERISK_BASE/download"
do
[[ -d "$directory" ]] || install -d -m 0775 "$directory"
done
ASTERISK_IMAGE_AVAILABLE=0
if docker image inspect "$ASTERISK_IMAGE" >/dev/null 2>&1; then
LOCAL_ASTERISK_ARCH="$(docker image inspect --format '{{.Architecture}}' "$ASTERISK_IMAGE")"
if [[ "$LOCAL_ASTERISK_ARCH" == "$ARCH" ]]; then
stage_skip 6 "Asterisk image for linux/$ARCH is already available"
ASTERISK_IMAGE_AVAILABLE=1
else
log "Local Asterisk image architecture is $LOCAL_ASTERISK_ARCH; loading bundled linux/$ARCH image"
fi
fi
if (( ! ASTERISK_IMAGE_AVAILABLE )); then
ASTERISK_IMAGE_ARCHIVE="/opt/cti/installer/images/asterisk-22-$ARCH.tar.gz"
[[ -s "$ASTERISK_IMAGE_ARCHIVE" && -s "$ASTERISK_IMAGE_ARCHIVE.sha256" ]] \
|| fail "The package has no Asterisk image for linux/$ARCH. Rebuild it with the matching saved image."
log "Loading bundled Asterisk image for linux/$ARCH (no Docker Hub pull)"
(cd "$(dirname "$ASTERISK_IMAGE_ARCHIVE")" && sha256sum -c "$(basename "$ASTERISK_IMAGE_ARCHIVE").sha256") \
|| fail "Bundled Asterisk image checksum validation failed"
quiet_command docker load --input "$ASTERISK_IMAGE_ARCHIVE"
docker image inspect "$ASTERISK_IMAGE" >/dev/null 2>&1 \
|| fail "Bundled image did not provide the expected tag $ASTERISK_IMAGE"
LOADED_ASTERISK_ARCH="$(docker image inspect --format '{{.Architecture}}' "$ASTERISK_IMAGE")"
[[ "$LOADED_ASTERISK_ARCH" == "$ARCH" ]] \
|| fail "Bundled Asterisk image architecture is $LOADED_ASTERISK_ARCH, expected $ARCH"
fi
NEED_SEED_CONFIG=0
[[ -n "$(find "$ASTERISK_BASE/base/etc/asterisk" -mindepth 1 -maxdepth 1 -print -quit)" ]] \
|| NEED_SEED_CONFIG=1
ASTERISK_DOCS_DIR="$ASTERISK_BASE/base/var/lib/asterisk/documentation"
NEED_SEED_DOCUMENTATION=0
[[ -s "$ASTERISK_DOCS_DIR/core-en_US.xml" ]] || NEED_SEED_DOCUMENTATION=1
DOCUMENTATION_SEEDED=0
if ((NEED_SEED_CONFIG || NEED_SEED_DOCUMENTATION)); then
SEED_CONTAINER="raymand-cti-asterisk-seed-$$"
docker create --name "$SEED_CONTAINER" "$ASTERISK_IMAGE" >/dev/null
if ((NEED_SEED_CONFIG)); then
quiet_command docker cp "$SEED_CONTAINER:/etc/asterisk/." "$ASTERISK_BASE/base/etc/asterisk/"
fi
if ((NEED_SEED_DOCUMENTATION)); then
[[ -d "$ASTERISK_DOCS_DIR" ]] || install -d -m 0775 "$ASTERISK_DOCS_DIR"
quiet_command docker cp "$SEED_CONTAINER:/var/lib/asterisk/documentation/." \
"$ASTERISK_DOCS_DIR/"
[[ -s "$ASTERISK_DOCS_DIR/core-en_US.xml" ]] \
|| fail "Asterisk image did not provide /var/lib/asterisk/documentation/core-en_US.xml"
DOCUMENTATION_SEEDED=1
fi
docker rm "$SEED_CONTAINER" >/dev/null
SEED_CONTAINER=""
fi
[[ -f "$ASTERISK_BASE/base/etc/asterisk/asterisk.conf" ]] \
|| fail "Asterisk image did not provide etc/asterisk/asterisk.conf"
DEFAULT_HOLD_MUSIC="$ASTERISK_BASE/base/var/lib/asterisk/moh/pline-hold.wav"
if [[ ! -e "$DEFAULT_HOLD_MUSIC" ]]; then
quiet_command install -m 0644 /opt/cti/resource/pline-hold.wav "$DEFAULT_HOLD_MUSIC"
fi
if [[ "${STAGE_STATES[6]}" == "RUN" ]]; then stage_done 6; fi
stage_begin 7 "Checking file ownership and permissions"
for path in /opt/cti; do
if find "$path" -xdev \( ! -user pline -o ! -group pline \) -print -quit | grep -q .; then
find "$path" -xdev \( ! -user pline -o ! -group pline \) -exec chown pline:pline {} +
fi
done
if [[ "$(stat -c '%a' /opt/cti/application.properties)" != 640 ]]; then chmod 0640 /opt/cti/application.properties; fi
find /opt/cti/tools -maxdepth 1 -type f ! -perm -u+x -exec chmod u+x {} + 2>/dev/null || true
stage_done 7
stage_begin 8 "Creating/checking the HTTPS certificate and Nginx TLS configuration"
quiet_command /usr/lib/raymand-cti/setup-https
disable_conflicting_web_servers() {
local service
# Keep installed packages and customer data, but prevent common web servers
# from competing with the CTI Nginx listener on ports 80/443.
for service in apache2 lighttpd caddy httpd haproxy; do
if systemctl cat "$service.service" >/dev/null 2>&1 \
&& { systemctl is-active --quiet "$service.service" \
|| systemctl is-enabled --quiet "$service.service" 2>/dev/null; }; then
log "Disabling conflicting web service $service.service"
systemctl disable --now "$service.service" \
|| fail "Could not stop and disable conflicting web service $service.service"
fi
done
}
disable_conflicting_web_servers
quiet_command /usr/sbin/nginx -t
quiet_command /usr/lib/raymand-cti/check-nginx-ports
quiet_command systemctl enable nginx.service
stage_done 8
if ((DOCUMENTATION_SEEDED)) && docker inspect asterisk >/dev/null 2>&1; then
log "Restarting the existing Asterisk container after restoring its XML documentation"
quiet_command docker restart asterisk || fail "Could not restart Asterisk after restoring its XML documentation"
fi
stage_begin 9 "Starting Asterisk before the CTI Java service"
if systemctl is-active --quiet raymnad-cti.service; then
log "Stopping the CTI Java service before starting Asterisk"
quiet_command systemctl stop raymnad-cti.service
fi
# Bootstrap the same core AMI user that PlineTools regenerates during Java startup.
# This lets the first Asterisk process load AMI configuration before Java connects.
AMI_BOOTSTRAP_DIR="$ASTERISK_BASE/base/etc/asterisk/manager.d"
AMI_BOOTSTRAP_CONFIG="$AMI_BOOTSTRAP_DIR/pline.conf"
install -d -o pline -g pline -m 0775 "$AMI_BOOTSTRAP_DIR"
if [[ ! -s "$AMI_BOOTSTRAP_CONFIG" ]]; then
install -o pline -g pline -m 0640 /dev/null "$AMI_BOOTSTRAP_CONFIG"
cat >"$AMI_BOOTSTRAP_CONFIG" <<'EOF'
[pline]
displaysystemname = yes
allowmultiplelogin = yes
secret = pline-core-password
deny = 0.0.0.0/0
permit = 127.0.0.0/8
read = all
write = all
EOF
fi
AMI_MANAGER_CONFIG="$ASTERISK_BASE/base/etc/asterisk/manager.conf"
if ((NEED_SEED_CONFIG)) || [[ ! -s "$AMI_MANAGER_CONFIG" ]]; then
install -o pline -g pline -m 0640 /dev/null "$AMI_MANAGER_CONFIG"
cat >"$AMI_MANAGER_CONFIG" <<'EOF'
[general]
enabled = yes
webenabled = yes
port = 2342
bindaddr = 0.0.0.0
#include "manager.d/*.conf"
EOF
elif ! grep -Eq '^[[:space:]]*#include[[:space:]]+"?manager.d/\*\.conf"?[[:space:]]*$' "$AMI_MANAGER_CONFIG"; then
printf '\n#include "manager.d/*.conf"\n' >>"$AMI_MANAGER_CONFIG"
fi
chown pline:pline "$AMI_MANAGER_CONFIG" "$AMI_BOOTSTRAP_CONFIG"
chmod 0640 "$AMI_MANAGER_CONFIG" "$AMI_BOOTSTRAP_CONFIG"
systemctl is-active --quiet docker.service || fail "Docker service is not active"
ASTERISK_COMPOSE_FILE="$ASTERISK_BASE/docker-compose.yml"
if [[ ! -f "$ASTERISK_COMPOSE_FILE" ]]; then
log "Creating the managed Asterisk Docker Compose file"
install -o pline -g pline -m 0644 /dev/null "$ASTERISK_COMPOSE_FILE"
cat >"$ASTERISK_COMPOSE_FILE" <<EOF
# Generated and managed by P-Line
version: "3.7"
services:
asterisk:
image: $ASTERISK_IMAGE
container_name: asterisk
restart: unless-stopped
environment:
TZ: Asia/Tehran
PUID: $PLINE_UID
PGID: $PLINE_GID
network_mode: host
volumes:
- $ASTERISK_BASE/base/etc/asterisk:/etc/asterisk
- $ASTERISK_BASE/base/var/lib/asterisk:/var/lib/asterisk
- $ASTERISK_BASE/base/var/log/asterisk:/var/log/asterisk
- $ASTERISK_BASE/base/var/spool/asterisk:/var/spool/asterisk
- $ASTERISK_BASE/base/fax:/var/spool/asterisk/fax
- $ASTERISK_BASE/base/sounds:/var/lib/asterisk/sounds
- $ASTERISK_BASE/voices-box/sounds:$ASTERISK_BASE/voices-box/sounds
- $ASTERISK_BASE/voices-box/music-on-holds:$ASTERISK_BASE/voices-box/music-on-holds
tty: true
stdin_open: true
EOF
fi
if docker compose version >/dev/null 2>&1; then
ASTERISK_COMPOSE=(docker compose)
else
ASTERISK_COMPOSE=(docker-compose)
fi
log "Starting Asterisk before the CTI Java service"
quiet_command "${ASTERISK_COMPOSE[@]}" -f "$ASTERISK_COMPOSE_FILE" up -d asterisk
ASTERISK_READY=0
ASTERISK_CLI_OUTPUT=""
for attempt in $(seq 1 60); do
if [[ "$(docker inspect --format '{{.State.Running}}' asterisk 2>/dev/null || true)" == true ]]; then
if ASTERISK_CLI_OUTPUT="$(docker exec asterisk asterisk -rx 'core show version' 2>&1)"; then
ASTERISK_READY=1
break
fi
fi
if ((UI_TTY)); then
docker logs --tail 5 asterisk >"$UI_LOG_FILE" 2>&1 || true
UI_TAIL_SOURCE="$UI_LOG_FILE"
UI_MESSAGE="Waiting for Asterisk before Java ($((attempt * 2))s / 120s)"
render_ui
fi
sleep 2
done
if (( ! ASTERISK_READY )); then
if ((UI_TTY)); then
{
printf 'Asterisk CLI readiness check: %s\n' "${ASTERISK_CLI_OUTPUT:-no response from container}"
docker logs --tail 100 asterisk 2>&1 || true
} >"$UI_LOG_FILE"
append_captured_output "Asterisk startup before Java"
else
printf 'Asterisk CLI readiness check: %s\n' "${ASTERISK_CLI_OUTPUT:-no response from container}" >&2
docker ps -a --filter name='^/asterisk$' >&2 || true
docker logs --tail 100 asterisk >&2 || true
fi
fail "Asterisk did not become ready; Java was not started"
fi
log "Asterisk is ready; continuing with Java startup"
JAVA_SERVICE_START_TIME="@$(date +%s)"
BACKEND_LISTENERS="$(ss -H -ltnp "sport = :$BACKEND_PORT")" \
|| fail "Cannot inspect backend port $BACKEND_PORT"
if [[ -n "$BACKEND_LISTENERS" ]]; then
printf '%s\n' "$BACKEND_LISTENERS" >"$UI_LOG_FILE"
append_captured_output "Backend port $BACKEND_PORT is already occupied"
fail "Backend port $BACKEND_PORT is in use; see the listening process in $INSTALL_LOG"
fi
if ((PACKAGE_CHANGED)); then quiet_command systemctl daemon-reload; fi
if systemctl is-active --quiet raymnad-cti.service && ((PACKAGE_CHANGED == 0)); then
log "Java pre-start check skipped because Raymand CTI is already running"
log_event "JAVA PRE-START CHECK SKIPPED: service already active; existing customer instance left running"
else
if systemctl is-active --quiet raymnad-cti.service; then
log "Stopping the running Raymand CTI service to validate the updated package"
quiet_command systemctl stop raymnad-cti.service
fi
log "Running Java once before systemd startup and recording its complete output"
JAVA_PRESTART_STAMP="$(date '+%Y%m%d-%H%M%S')"
JAVA_PRESTART_APP_LOG="/opt/cti/log/java-prestart-$JAVA_PRESTART_STAMP.log"
JAVA_PRESTART_OUTPUT="$APT_SOURCES_DIR/java-prestart-console.log"
UI_TAIL_SOURCE="$JAVA_PRESTART_OUTPUT"
install -o pline -g pline -m 0640 /dev/null "$JAVA_PRESTART_APP_LOG"
: >"$JAVA_PRESTART_OUTPUT"
log_event "JAVA PRE-START CHECK BEGIN: /usr/bin/java -jar /opt/cti/raymandcti.jar"
(
cd /opt/cti
exec setsid runuser -u pline -- env "LOGGING_FILE_NAME=$JAVA_PRESTART_APP_LOG" \
/usr/bin/java -jar /opt/cti/raymandcti.jar --pline.license.enforce=true
) >"$JAVA_PRESTART_OUTPUT" 2>&1 &
JAVA_PRESTART_PID=$!
JAVA_PRESTART_READY=0
JAVA_PRESTART_EXITED=0
for attempt in $(seq 1 120); do
if ! kill -0 "$JAVA_PRESTART_PID" 2>/dev/null; then
JAVA_PRESTART_EXITED=1
break
fi
JAVA_PRESTART_STATE="$(ps -o stat= -p "$JAVA_PRESTART_PID" 2>/dev/null | tr -d ' ' || true)"
if [[ "$JAVA_PRESTART_STATE" == Z* ]]; then
JAVA_PRESTART_EXITED=1
break
fi
if curl --connect-timeout 2 --max-time 5 --fail --silent "$BACKEND_READINESS_URL" 2>/dev/null \
| grep -Eq '"status"[[:space:]]*:[[:space:]]*"UP"'; then
JAVA_PRESTART_READY=1
break
fi
UI_MESSAGE="Checking backend startup (${attempt}s / 120s)"
render_ui
sleep 1
done
if (( ! JAVA_PRESTART_EXITED )); then
kill -TERM -- "-$JAVA_PRESTART_PID" 2>/dev/null || true
for attempt in $(seq 1 15); do
JAVA_PRESTART_STATE="$(ps -o stat= -p "$JAVA_PRESTART_PID" 2>/dev/null | tr -d ' ' || true)"
[[ -z "$JAVA_PRESTART_STATE" || "$JAVA_PRESTART_STATE" == Z* ]] && break
sleep 1
done
JAVA_PRESTART_STATE="$(ps -o stat= -p "$JAVA_PRESTART_PID" 2>/dev/null | tr -d ' ' || true)"
if [[ -n "$JAVA_PRESTART_STATE" && "$JAVA_PRESTART_STATE" != Z* ]]; then
kill -KILL -- "-$JAVA_PRESTART_PID" 2>/dev/null || true
fi
fi
if wait "$JAVA_PRESTART_PID"; then JAVA_PRESTART_RC=0; else JAVA_PRESTART_RC=$?; fi
JAVA_PRESTART_PID=""
log_event "JAVA PRE-START CHECK exit=$JAVA_PRESTART_RC health_up=$JAVA_PRESTART_READY"
log_event "----- BEGIN JAVA PRE-START CONSOLE OUTPUT -----"
cat "$JAVA_PRESTART_OUTPUT" >&4
log_event "----- END JAVA PRE-START CONSOLE OUTPUT -----"
if [[ -s "$JAVA_PRESTART_APP_LOG" ]]; then
log_event "----- BEGIN JAVA PRE-START APPLICATION LOG: $JAVA_PRESTART_APP_LOG -----"
cat "$JAVA_PRESTART_APP_LOG" >&4
log_event "----- END JAVA PRE-START APPLICATION LOG -----"
fi
if (( ! JAVA_PRESTART_READY )); then
JAVA_PRESTART_DIAGNOSTIC="$(grep -Eih 'Caused by:|APPLICATION FAILED|ERROR|FATAL' \
"$JAVA_PRESTART_OUTPUT" "$JAVA_PRESTART_APP_LOG" 2>/dev/null | tail -n 1 \
| sed -E 's/^.*(Caused by:|APPLICATION FAILED TO START|ERROR|FATAL)/\1/' \
| tr -cd '[:print:]' | cut -c1-180 || true)"
fail "Java pre-start failed: ${JAVA_PRESTART_DIAGNOSTIC:-health check did not become UP}. Full logs: $INSTALL_LOG"
fi
log "Java pre-start completed; checking the AMI configuration it generated"
fi
AMI_CONFIG="$ASTERISK_BASE/base/etc/asterisk/manager.d/pline.conf"
[[ -s "$AMI_CONFIG" ]] \
|| fail "Java did not generate the Asterisk AMI configuration at $AMI_CONFIG"
grep -Eq '^[[:space:]]*\[pline\][[:space:]]*$' "$AMI_CONFIG" \
|| fail "The generated Asterisk AMI configuration has no [pline] section"
grep -Eq '^[[:space:]]*secret[[:space:]]*=' "$AMI_CONFIG" \
|| fail "The generated Asterisk AMI configuration has no secret"
log "Restarting Asterisk to apply the AMI configuration generated by Java"
quiet_command docker restart asterisk
ASTERISK_READY=0
ASTERISK_CLI_OUTPUT=""
for attempt in $(seq 1 60); do
if [[ "$(docker inspect --format '{{.State.Running}}' asterisk 2>/dev/null || true)" == true ]]; then
if ASTERISK_CLI_OUTPUT="$(docker exec asterisk asterisk -rx 'core show version' 2>&1)"; then
ASTERISK_READY=1
break
fi
fi
if ((UI_TTY)); then
docker logs --tail 5 asterisk >"$UI_LOG_FILE" 2>&1 || true
UI_TAIL_SOURCE="$UI_LOG_FILE"
UI_MESSAGE="Waiting for Asterisk after AMI setup ($((attempt * 2))s / 120s)"
render_ui
fi
sleep 2
done
if (( ! ASTERISK_READY )); then
if ((UI_TTY)); then
{
printf 'Asterisk CLI readiness check: %s\n' "${ASTERISK_CLI_OUTPUT:-no response from container}"
docker logs --tail 100 asterisk 2>&1 || true
} >"$UI_LOG_FILE"
append_captured_output "Asterisk restart after AMI setup"
else
printf 'Asterisk CLI readiness check: %s\n' "${ASTERISK_CLI_OUTPUT:-no response from container}" >&2
docker ps -a --filter name='^/asterisk$' >&2 || true
docker logs --tail 100 asterisk >&2 || true
fi
fail "Asterisk did not become ready after AMI setup; Java was not started"
fi
log "AMI configuration is active; starting Java for its final Asterisk connection"
quiet_command systemctl enable raymnad-cti.service
log "Restarting Java after Asterisk has loaded the AMI configuration"
quiet_command systemctl restart raymnad-cti.service
if ! quiet_command systemctl restart nginx.service; then
{
/usr/sbin/nginx -t 2>&1 || true
ss -ltnp 2>&1 || true
journalctl -u nginx.service -n 40 --no-pager 2>&1 || true
} >"$UI_LOG_FILE"
append_captured_output "Nginx startup diagnostics and listening processes"
fail "Nginx could not start; check port conflicts and Nginx journal in $INSTALL_LOG"
fi
log "Waiting for the Raymand CTI backend to stay active"
BACKEND_READY=0
UI_TAIL_SOURCE="$UI_LOG_FILE"
for attempt in $(seq 1 60); do
journalctl -u raymnad-cti.service --since "$JAVA_SERVICE_START_TIME" --no-pager >"$UI_LOG_FILE" 2>&1 || true
if systemctl is-active --quiet raymnad-cti.service \
&& curl --connect-timeout 2 --max-time 5 --fail --silent --show-error "$BACKEND_READINESS_URL" 2>/dev/null \
| grep -Eq '"status"[[:space:]]*:[[:space:]]*"UP"'; then
BACKEND_READY=1
break
fi
UI_MESSAGE="Waiting for backend health ($((attempt * 2))s / 120s)"
render_ui
sleep 2
done
if (( ! BACKEND_READY )); then
if ((UI_TTY)); then
journalctl -u raymnad-cti.service --since "$JAVA_SERVICE_START_TIME" --no-pager >"$UI_LOG_FILE" 2>&1 || true
append_captured_output "raymnad-cti.service journal"
BACKEND_DIAGNOSTIC="$(grep -Ei 'Caused by:|APPLICATION FAILED|ERROR|FATAL' "$UI_LOG_FILE" \
| tail -n 1 | sed -E 's/^.*java\[[0-9]+\]: //' | tr -cd '[:print:]' || true)"
if [[ -n "$BACKEND_DIAGNOSTIC" ]]; then
fail "Backend failed: $BACKEND_DIAGNOSTIC"
fi
else
journalctl -u raymnad-cti.service -n 100 --no-pager >&2 || true
fi
fail "Raymand CTI backend did not become active"
fi
if ((UI_TTY)); then
journalctl -u raymnad-cti.service --since "$JAVA_SERVICE_START_TIME" --no-pager >"$UI_LOG_FILE" 2>&1 || true
append_captured_output "raymnad-cti.service startup journal"
else
journalctl -u raymnad-cti.service --since "$JAVA_SERVICE_START_TIME" --no-pager || true
fi
if [[ "$(docker inspect --format '{{.State.Running}}' asterisk 2>/dev/null || true)" != true ]] \
|| ! docker exec asterisk asterisk -rx 'core show version' >/dev/null 2>&1; then
fail "Asterisk stopped responding after Java startup"
fi
log "Online installation completed. Raymand CTI backend and web interface are running."
log "Asterisk is running in Docker."
log "Open https://<server-address>/ to use Raymand CTI. The default self-signed certificate will show a browser trust warning."
log "A valid CTI license is required to unlock Raymand CTI features. Activate it from the License page after installation."
log "Full installer log: $LOG_DIR/latest.log"
stage_done 9