#!/bin/bash
# Soha installer (rfc/Updates and installer.md):
#
#   curl -fsSL https://get.soha.tel | sudo bash
#   curl -fsSL https://get.soha.tel/beta | sudo bash        # the beta channel
#
# Options (after `bash -s --`):
#   --channel stable|beta
#   --domain NAME      the console's name, with a Let's Encrypt certificate (its DNS must point
#                      here and port 80 or 443 must be reachable); without it the console uses a
#                      self-signed certificate on this server's address
#   --email ADDRESS    for Let's Encrypt's expiry notices (optional)
#   --public-ip ADDR   what phones and providers send audio to (detected when left out)
#   --https-port PORT  the console (443); --http-port PORT sends browsers to it (80, 0 for none)
#   --admin-user NAME --admin-password-file FILE
#                      create the first admin account now, for unattended installs (the file's
#                      first line is the password, 12 characters or more). Without them the
#                      installer prints a one-time setup link and the account is made in the console.
#   --sip-allow LIST   networks desk phones and offices reach SIP from, comma-separated
#                      (default: the private ranges 10/8, 172.16/12, 192.168/16; "none" for none).
#                      Trunks are allowed by themselves; everyone else is dropped.
#   --no-sip-firewall  leave SIP (5060) open to everyone, for a server behind its own firewall
#
# On a fresh Debian 12/13, Ubuntu 22.04/24.04/26.04, or Rocky/Alma 9 server (amd64 or arm64):
# installs the packages, builds Asterisk 24 from Soha's offline bundle, creates the soha user and
# /etc/soha, /var/lib/soha, /opt/soha, and installs and starts the newest release with
# `soha update`. Running it again repairs an install and keeps its settings and secrets.
set -Eeuo pipefail

SOHA_CHANNEL_DEFAULT=stable
CHANNEL=${SOHA_CHANNEL:-$SOHA_CHANNEL_DEFAULT}
FEED=${SOHA_FEED:-https://get.soha.tel}
ASTERISK_VERSION=24.0.0
# Soha's offline bundle: the upstream source plus pjproject, libjwt and the default sounds
# (asterisk-24.0.0/SOHA-BUNDLE.txt inside says what and where from).
ASTERISK_SHA256=bfa89572f8e4d81845dd2bb07f6dff02fee251cbd616f9b8a4a92c32afda1162
PUBLIC_IP=${SOHA_PUBLIC_IP:-}
HTTPS_PORT=${SOHA_HTTPS_PORT:-443}
HTTP_PORT=${SOHA_HTTP_PORT:-80}
DOMAIN=${SOHA_DOMAIN:-}
EMAIL=${SOHA_EMAIL:-}
ADMIN_USER=${SOHA_ADMIN_USER:-admin}
ADMIN_PASSWORD_FILE=${SOHA_ADMIN_PASSWORD_FILE:-}
SIP_ALLOW=${SOHA_SIP_ALLOW:-}
SIP_FIREWALL=${SOHA_SIP_FIREWALL:-on}
# For testing an unreleased installer: a directory with Asterisk's base configuration, used
# instead of the one in the release.
ASTERISK_BASE=${SOHA_ASTERISK_BASE:-}

while [[ $# -gt 0 ]]; do
  case $1 in
    --channel) CHANNEL=$2; shift 2 ;;
    --beta) CHANNEL=beta; shift ;;
    --public-ip) PUBLIC_IP=$2; shift 2 ;;
    --domain) DOMAIN=$2; shift 2 ;;
    --email) EMAIL=$2; shift 2 ;;
    --https-port) HTTPS_PORT=$2; shift 2 ;;
    --admin-user) ADMIN_USER=$2; shift 2 ;;
    --admin-password-file) ADMIN_PASSWORD_FILE=$2; shift 2 ;;
    --http-port) HTTP_PORT=$2; shift 2 ;;
    --sip-allow) SIP_ALLOW=$2; shift 2 ;;
    --no-sip-firewall) SIP_FIREWALL=off; shift ;;
    -h|--help) sed -n '2,29p' "$0" 2>/dev/null | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "Unknown option $1" >&2; exit 2 ;;
  esac
done

say() { printf '\n\033[1m==> %s\033[0m\n' "$*"; }
die() { printf '\n\033[31mSoha installer: %s\033[0m\n' "$*" >&2; exit 1; }
trap 'die "failed at line $LINENO: $BASH_COMMAND"' ERR
# download URL FILE: curl's --retry skips a connection cut mid-file (a reset HTTP/2 stream),
# so try the whole download again on any failure.
download() {
  local try
  for try in 1 2 3 4 5; do
    curl -fL --connect-timeout 20 -o "$2" "$1" && return 0
    [[ $try -lt 5 ]] && { echo "Download failed; trying again ($((try + 1)) of 5)" >&2; sleep $((try * 3)); }
  done
  return 1
}

[[ $EUID -eq 0 ]] || die "run it as root: curl -fsSL $FEED | sudo bash"
[[ $CHANNEL == stable || $CHANNEL == beta ]] || die "--channel is stable or beta"
[[ $HTTPS_PORT =~ ^[0-9]+$ && $HTTPS_PORT -gt 0 ]] || die "--https-port is a number"
[[ $HTTP_PORT =~ ^[0-9]+$ ]] || die "--http-port is a number (0 for none)"
[[ $HTTP_PORT != "$HTTPS_PORT" ]] || die "--http-port and --https-port must differ"
DOMAIN=${DOMAIN,,}
[[ $ADMIN_USER =~ ^[A-Za-z0-9_.-]{3,32}$ ]] || die "--admin-user is 3-32 letters, digits, dots, dashes or underscores"
if [[ -n $ADMIN_PASSWORD_FILE ]]; then
  [[ -r $ADMIN_PASSWORD_FILE ]] || die "cannot read --admin-password-file $ADMIN_PASSWORD_FILE"
fi
[[ $SIP_FIREWALL == on || $SIP_FIREWALL == off ]] || die "SOHA_SIP_FIREWALL is on or off"
[[ $SIP_ALLOW =~ ^[0-9A-Fa-f.:/,\ ]*$ || $SIP_ALLOW == none ]] || die "--sip-allow is a comma-separated list of addresses and networks"
[[ -z $DOMAIN || $DOMAIN =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]] || die "--domain $DOMAIN is not a host name"

# ---- where we are ----
[[ -r /etc/os-release ]] || die "this system has no /etc/os-release"
. /etc/os-release
DISTRO="$ID ${VERSION_ID:-}"
case "$ID:${VERSION_ID%%.*}:${VERSION_ID:-}" in
  debian:12:*|debian:13:*) PKG=apt ;;
  ubuntu:*:22.04|ubuntu:*:24.04|ubuntu:*:26.04) PKG=apt ;;
  rocky:9:*|almalinux:9:*) PKG=dnf ;;
  *) die "$DISTRO is not supported (Debian 12/13, Ubuntu 22.04/24.04/26.04, Rocky or Alma 9)" ;;
esac
case $(uname -m) in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) die "$(uname -m) is not supported (amd64 or arm64)" ;;
esac
command -v systemctl >/dev/null && [[ -d /run/systemd/system ]] || die "Soha needs systemd"
say "Installing Soha ($CHANNEL) on $PRETTY_NAME, $ARCH"

# ---- packages ----
say "Installing packages"
if [[ $PKG == apt ]]; then
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -q
  apt-get install -y -q --no-install-recommends \
    ca-certificates curl sudo python3 ffmpeg sqlite3 tar bzip2 patch nftables \
    build-essential pkg-config libedit-dev libjansson-dev libxml2-dev uuid-dev libsqlite3-dev \
    libssl-dev libsrtp2-dev libcurl4-openssl-dev
else
  dnf -y -q install dnf-plugins-core epel-release
  dnf config-manager --set-enabled crb
  dnf -y -q install ca-certificates curl sudo python3 sqlite tar bzip2 patch nftables gcc gcc-c++ make \
    pkgconf-pkg-config libedit-devel jansson-devel libxml2-devel libuuid-devel sqlite-devel \
    openssl-devel libsrtp-devel libcurl-devel
  # ffmpeg (for converting uploaded prompts) is in RPM Fusion; without it uploads must be WAV.
  dnf -y -q install ffmpeg-free 2>/dev/null || echo "ffmpeg is not available here; prompts must be uploaded as 8/16 kHz WAV."
fi

# ---- users and folders ----
say "Creating the soha and asterisk users"
getent group asterisk >/dev/null || groupadd --system asterisk
id asterisk >/dev/null 2>&1 || useradd --system --gid asterisk --home-dir /var/lib/asterisk --shell /usr/sbin/nologin asterisk
getent group soha >/dev/null || groupadd --system soha
id soha >/dev/null 2>&1 || useradd --system --gid soha --home-dir /var/lib/soha --shell /usr/sbin/nologin soha
# soha writes Asterisk's generated configuration and reads its recordings and history.
usermod -aG asterisk soha
install -d -o root -g root -m 755 /opt/soha /opt/soha/releases
install -d -o root -g soha -m 755 /etc/soha
# 751: Asterisk (not in the soha group) has to pass through to /var/lib/soha/asterisk.
install -d -o soha -g soha -m 751 /var/lib/soha
install -d -o soha -g soha -m 750 /var/lib/soha/backups
install -d -o soha -g asterisk -m 2770 /var/lib/soha/asterisk
install -d -o root -g root -m 700 /var/lib/soha-helpers

# ---- Asterisk ----
have_asterisk=$( { /usr/sbin/asterisk -V 2>/dev/null || true; } | awk '{print $2}')
if [[ $have_asterisk == "$ASTERISK_VERSION" ]]; then
  say "Asterisk $ASTERISK_VERSION is already installed"
else
  say "Building Asterisk $ASTERISK_VERSION (this takes a while: about 10-20 minutes, longer on a small server)"
  build=$(mktemp -d /var/tmp/soha-asterisk.XXXXXX)
  download "$FEED/v1/downloads/asterisk/asterisk-$ASTERISK_VERSION.tar.gz" "$build/asterisk.tar.gz" || die "could not download Asterisk from $FEED"
  echo "$ASTERISK_SHA256  $build/asterisk.tar.gz" | sha256sum -c --quiet - || die "the Asterisk download does not match its checksum"
  tar -xzf "$build/asterisk.tar.gz" -C "$build"
  rm -f "$build/asterisk.tar.gz"
  (
    cd "$build/asterisk-$ASTERISK_VERSION"
    ./configure --quiet --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=/usr/lib \
      --with-pjproject-bundled --with-jansson \
      --with-download-cache="$PWD/soha-cache" --with-sounds-cache="$PWD/soha-sounds" >/dev/null
    make -s menuselect.makeopts
    menuselect/menuselect --disable BUILD_NATIVE --enable CORE-SOUNDS-EN-GSM --enable MOH-OPSOUND-WAV menuselect.makeopts
    # The bundled pjproject does not build reliably in parallel; build the third-party
    # libraries one job at a time, then Asterisk itself in parallel.
    make -j1 third-party >>"$build/build.log" 2>&1 || die "building Asterisk's libraries failed; the log is $build/build.log"
    make -j"$(nproc)" >>"$build/build.log" 2>&1 || die "building Asterisk failed; the log is $build/build.log"
    make install >>"$build/build.log" 2>&1 || die "installing Asterisk failed; the log is $build/build.log"
  )
  rm -rf "$build"
  ldconfig
fi
install -d -o asterisk -g asterisk -m 750 /var/lib/asterisk /var/spool/asterisk /var/log/asterisk
install -d -o asterisk -g asterisk -m 2770 /var/spool/asterisk/voicemail /var/spool/asterisk/recordings
cat > /etc/systemd/system/asterisk.service <<'EOF'
# Written by the Soha installer.
[Unit]
Description=Asterisk PBX (for Soha)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=asterisk
Group=asterisk
RuntimeDirectory=asterisk
ExecStart=/usr/sbin/asterisk -f -C /etc/asterisk/asterisk.conf
ExecReload=/usr/sbin/asterisk -rx 'core reload'
Restart=always
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

# ---- the release ----
say "Fetching the newest $CHANNEL release"
work=$(mktemp -d /var/tmp/soha-install.XXXXXX)
trap 'rm -rf "$work"' EXIT
curl -fsS --retry 3 "$FEED/v1/updates/$CHANNEL" -o "$work/envelope.json" || die "no $CHANNEL release is published yet"
read -r VERSION FILE SHA SIZE < <(python3 - "$work/envelope.json" "$ARCH" <<'EOF'
import base64, json, sys
env = json.load(open(sys.argv[1]))
m = json.loads(base64.b64decode(env["manifest"]))
for a in m["artifacts"]:
    if a["os"] == "linux" and a["arch"] == sys.argv[2]:
        print(m["version"], a["file"], a["sha256"], a["size"])
        break
else:
    sys.exit("no build for " + sys.argv[2])
EOF
)
[[ -n ${VERSION:-} && -n ${FILE:-} ]] || die "the $CHANNEL release has no build for $ARCH"
# The download is checked here against the manifest, and `soha update` below checks the
# manifest's signature with the key built into Soha before it installs anything.
download "$FEED/v1/downloads/$VERSION/$FILE" "$work/release.tar.gz" || die "could not download Soha $VERSION from $FEED"
echo "$SHA  $work/release.tar.gz" | sha256sum -c --quiet - || die "the release download does not match its checksum"
mkdir "$work/release"
tar -xzf "$work/release.tar.gz" -C "$work/release" --no-same-owner
[[ -n $ASTERISK_BASE ]] || ASTERISK_BASE="$work/release/asterisk-base"
[[ -d $ASTERISK_BASE ]] || die "release $VERSION has no Asterisk base configuration"

# ---- Asterisk configuration ----
say "Configuring Asterisk"
install -d -o asterisk -g asterisk -m 2750 /etc/asterisk
# Base files: the ones nothing edits follow the release; the ones Soha and its helpers edit
# (modules, music on hold, queues, ...) are written once.
for f in "$ASTERISK_BASE"/*.conf; do
  name=${f##*/}
  case $name in
    asterisk.conf|logger.conf|cdr.conf|cel.conf|cdr_sqlite3_custom.conf|cel_sqlite3_custom.conf|features.conf|indications.conf) ;;
    *) [[ -e /etc/asterisk/$name ]] && continue ;;
  esac
  sed -e 's#/var/lib/asterisk-call-dashboard#/var/lib/soha#g' \
      -e 's#/data/history/callcenter-history.db#/var/lib/asterisk/callcenter-history.db#g' \
      -e 's#/data/asterisk-db#/var/lib/asterisk#g' \
      -e 's#/usr/share/asterisk#/var/lib/asterisk#g' "$f" > "/etc/asterisk/$name"
done
for f in extensions-users.conf extensions-dids.conf pjsip-trunks.conf pjsip-users.conf voicemail-generated.conf pjsip-nat.conf rtp-nat.conf; do
  [[ -e /var/lib/soha/asterisk/$f ]] || install -o soha -g asterisk -m 640 /dev/null "/var/lib/soha/asterisk/$f"
done

PUBLIC_IP_FIXED=$([[ -n $PUBLIC_IP ]] && echo 1 || true)
if [[ -z $PUBLIC_IP ]]; then
  PUBLIC_IP=$(curl -fsS --max-time 5 https://license.soha.tel/v1/address 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin)["address"])' 2>/dev/null ||
    curl -fsS --max-time 5 https://api.ipify.org 2>/dev/null || true)
fi
LOCAL_IP=$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}' | head -1)
[[ -n $PUBLIC_IP ]] || PUBLIC_IP=$LOCAL_IP

[[ -e /etc/asterisk/pjsip-transport.conf ]] || cat > /etc/asterisk/pjsip-transport.conf <<EOF
; Written once by the Soha installer; edit freely. Soha Phone uses the WebSocket transport
; (through soha-server on 443), trunks and desk phones UDP. The public address comes from the
; console (Configurations > Network), which writes pjsip-nat.conf.
[transport-ws]
type = transport
protocol = ws
bind = 0.0.0.0
local_net = 10.0.0.0/8
local_net = 172.16.0.0/12
local_net = 192.168.0.0/16

[transport-udp-nat]
type = transport
protocol = udp
bind = 0.0.0.0:5060
local_net = 10.0.0.0/8
local_net = 172.16.0.0/12
local_net = 192.168.0.0/16

#include "/var/lib/soha/asterisk/pjsip-nat.conf"
EOF
[[ -e /etc/asterisk/rtp.conf ]] || cat > /etc/asterisk/rtp.conf <<EOF
; Written once by the Soha installer. Behind NAT, rtp-nat.conf (written by soha-server from
; Configurations > Network) offers WebRTC phones the public address too.
[general]
rtpstart = 10000
rtpend = 20000
icesupport = yes

#include "/var/lib/soha/asterisk/rtp-nat.conf"
EOF
# Installs made before 0.2.3 wrote the public address into these files once; the console's
# setting owns it now (rfc/Network security.md). Their fixed lines go, the includes come in.
if ! grep -q 'pjsip-nat.conf' /etc/asterisk/pjsip-transport.conf; then
  sed -i -E 's/^(external_(media|signaling)_address)/; moved to Configurations > Network: \1/' /etc/asterisk/pjsip-transport.conf
  printf '\n#include "/var/lib/soha/asterisk/pjsip-nat.conf"\n' >> /etc/asterisk/pjsip-transport.conf
fi
if ! grep -q 'rtp-nat.conf' /etc/asterisk/rtp.conf; then
  sed -i -e '/^; Behind NAT: offer the public address too (Soha installer)\./d' -e '/^\[ice_host_candidates\]$/d' \
    -e '/^[0-9.]* => [0-9.]*,include_local_address$/d' /etc/asterisk/rtp.conf
  printf '\n#include "/var/lib/soha/asterisk/rtp-nat.conf"\n' >> /etc/asterisk/rtp.conf
fi
[[ -e /etc/asterisk/http.conf ]] || cat > /etc/asterisk/http.conf <<EOF
; Written once by the Soha installer. Local only: Soha Phone and the console's listening reach
; it through soha-server's HTTPS (rfc/Network security.md).
[general]
enabled = yes
bindaddr = 127.0.0.1
bindport = 8088
EOF

# ---- Soha's settings (kept on a re-run) ----
say "Writing /etc/soha"
umask 077
if [[ ! -e /etc/soha/soha.env ]]; then
  AMI_SECRET=$(python3 -c 'import secrets; print(secrets.token_hex(24))')
  SESSION_KEY=$(python3 -c 'import secrets; print(secrets.token_hex(32))')
  # The first admin account: from --admin-password-file (hashed here; the password goes nowhere
  # else), or made in the console's setup page with the code soha-server prints.
  if [[ -n $ADMIN_PASSWORD_FILE ]]; then
    ADMIN_HASH=$(python3 -c '
import base64, hashlib, os, sys
pw = open(sys.argv[1], encoding="utf-8").readline().rstrip("\r\n")
if not 12 <= len(pw) <= 256:
    sys.exit(1)
salt = os.urandom(16)
d = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 310000, 32)
b = lambda x: base64.urlsafe_b64encode(x).rstrip(b"=").decode()
print("pbkdf2_sha256$310000$" + b(salt) + "$" + b(d))' "$ADMIN_PASSWORD_FILE") ||
      die "the password in $ADMIN_PASSWORD_FILE must be 12-256 characters"
    ADMIN_LINES="DASHBOARD_USER=$ADMIN_USER
DASHBOARD_PASSWORD_HASH='$ADMIN_HASH'"
  else
    ADMIN_LINES="# No account yet: the console's setup page makes the first one (sudo soha setup-code)."
  fi
  # The console's ports must be free (a re-run keeps soha.env and skips this).
  for port in "$HTTPS_PORT" "$HTTP_PORT"; do
    [[ $port == 0 ]] && continue
    if ss -Hltn "sport = :$port" 2>/dev/null | grep -q .; then
      die "port $port is in use ($(ss -Hltnp "sport = :$port" 2>/dev/null | grep -o 'users:(("[^"]*' | head -1 | cut -d'"' -f2)); choose another with --https-port or --http-port (0 for none)"
    fi
  done
  if [[ -n $DOMAIN ]]; then
    TLS_LINES="SOHA_TLS=letsencrypt
SOHA_TLS_DOMAINS=$DOMAIN${EMAIL:+
SOHA_TLS_EMAIL=$EMAIL}"
    CONSOLE_HOST=$DOMAIN
    ALIASES=$LOCAL_IP
  else
    TLS_LINES="SOHA_TLS=self-signed"
    CONSOLE_HOST=$LOCAL_IP
    ALIASES=$([[ $PUBLIC_IP != "$LOCAL_IP" ]] && echo "$PUBLIC_IP" || true)
  fi
  PORT_SUFFIX=$([[ $HTTPS_PORT != 443 ]] && echo ":$HTTPS_PORT" || true)
  cat > /etc/soha/soha.env <<EOF
# Soha's settings, written by the installer (systemd EnvironmentFile; soha-server.service).
DASHBOARD_BIND=0.0.0.0
DASHBOARD_PORT=$HTTPS_PORT
$TLS_LINES
$([[ $HTTP_PORT != 0 ]] && echo "SOHA_HTTP_PORT=$HTTP_PORT" || echo "# SOHA_HTTP_PORT=80 sends plain HTTP to HTTPS")
$ADMIN_LINES
DASHBOARD_SESSION_KEY=$SESSION_KEY
DASHBOARD_PUBLIC_URL=https://$CONSOLE_HOST$PORT_SUFFIX
SOHA_DOMAIN=$CONSOLE_HOST
SOHA_DOMAIN_ALIASES=$ALIASES
AMI_HOST=127.0.0.1
AMI_PORT=5038
AMI_USER=soha
AMI_SECRET=$AMI_SECRET
DASHBOARD_AUTH_DB=/var/lib/soha/auth.db
CALL_BLOCKLIST_DB=/var/lib/soha/blocklist.db
DASHBOARD_PBX_CONFIG_DIR=/var/lib/soha/asterisk
DASHBOARD_BACKUP_DIR=/var/lib/soha/backups
SOHA_MODULE_OVERRIDES=/var/lib/soha/modules-overrides.json
CALL_HISTORY_DB=/var/lib/asterisk/callcenter-history.db
SOHA_ASTERISK_HTTP_URL=http://127.0.0.1:8088
# Soha writes the base dialplan (recording-start, inbound-callerid, ivr-main) itself.
SOHA_GENERATE_BASE_CONTEXTS=1
# The public address phones and providers reach (Configurations > Network); detected at install.
SOHA_MANAGE_NAT=1
SOHA_PUBLIC_IP=$PUBLIC_IP
$([[ -n $PUBLIC_IP_FIXED ]] && echo "SOHA_PUBLIC_IP_FIXED=1" || echo "# SOHA_PUBLIC_IP_FIXED=1 keeps it from following detected changes")
# SIP (5060, 5061) only from the trunks and these networks (rfc/Network security.md).
SOHA_SIP_FIREWALL=$SIP_FIREWALL
$([[ -n $SIP_ALLOW ]] && echo "SOHA_SIP_ALLOW=$SIP_ALLOW" || echo "# SOHA_SIP_ALLOW=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16 (the default; none for none)")
EOF
fi
# Installs made before 0.2.3 lack these settings: calls failed in the recording step without the
# first, and the public address was fixed in Asterisk's files without the second.
grep -q '^SOHA_GENERATE_BASE_CONTEXTS=' /etc/soha/soha.env ||
  printf '# Soha writes the base dialplan (recording-start, inbound-callerid, ivr-main) itself.\nSOHA_GENERATE_BASE_CONTEXTS=1\n' >> /etc/soha/soha.env
grep -q '^SOHA_MANAGE_NAT=' /etc/soha/soha.env ||
  printf '# The public address phones and providers reach (Configurations > Network).\nSOHA_MANAGE_NAT=1\nSOHA_PUBLIC_IP=%s\n%s\n' "$PUBLIC_IP" "$([[ -n $PUBLIC_IP_FIXED ]] && echo 'SOHA_PUBLIC_IP_FIXED=1')" >> /etc/soha/soha.env
[[ -e /etc/soha/update.env ]] || cat > /etc/soha/update.env <<EOF
# soha update's settings. SOHA_UPDATE_AUTO=0 makes the daily timer only check.
SOHA_UPDATE_CHANNEL=$CHANNEL
SOHA_UPDATE_URL=$FEED
SOHA_UPDATE_AUTO=1
EOF
chown root:soha /etc/soha/soha.env /etc/soha/update.env
# soha.env holds secrets; update.env does not, and soha status reads it without root.
chmod 640 /etc/soha/soha.env
chmod 644 /etc/soha/update.env
rm -f /etc/soha/admin-password # an earlier installer's
AMI_SECRET=$(sed -n 's/^AMI_SECRET=//p' /etc/soha/soha.env)
cat > /etc/asterisk/manager.conf <<EOF
; Written by the Soha installer from /etc/soha/soha.env.
[general]
enabled = yes
bindaddr = 127.0.0.1
port = 5038

[soha]
secret = $AMI_SECRET
deny = 0.0.0.0/0.0.0.0
permit = 127.0.0.1/255.255.255.255
read = all
write = all
EOF
umask 022
chown -R asterisk:asterisk /etc/asterisk
chmod 640 /etc/asterisk/manager.conf
find /etc/asterisk -type d -exec chmod g+s {} +

# ---- start ----
say "Starting Asterisk"
systemctl daemon-reload
systemctl enable --now asterisk.service
for _ in $(seq 1 30); do
  (exec 3<>/dev/tcp/127.0.0.1/5038) 2>/dev/null && break
  sleep 1
done
# A re-run on a running Asterisk: load what files added since need (conference rooms came with
# confbridge.conf in 0.2.3); a restart would drop calls.
if [[ -e /etc/asterisk/confbridge.conf ]] && ! asterisk -rx "module show like app_confbridge" 2>/dev/null | grep -q Running; then
  asterisk -rx "module load app_confbridge.so" >/dev/null 2>&1 || true
fi

say "Installing Soha $VERSION"
"$work/release/soha-server" update --channel "$CHANNEL"
systemctl enable soha-server.service soha-update.timer
systemctl start soha-update.timer

say "Soha is running"
CONSOLE_URL=$(sed -n 's/^DASHBOARD_PUBLIC_URL=//p' /etc/soha/soha.env)
TLS_MODE=$(sed -n 's/^SOHA_TLS=//p' /etc/soha/soha.env)
case $TLS_MODE in
  self-signed)
    FINGERPRINT=$(python3 -c '
import base64, hashlib, sys
pem = open(sys.argv[1]).read().split("-----")[2]
d = hashlib.sha256(base64.b64decode(pem)).hexdigest().upper()
print(":".join(d[i:i+2] for i in range(0, len(d), 2)))' /var/lib/soha/tls/self-signed.crt 2>/dev/null || echo unknown)
    CERT_NOTE="  Certificate: self-signed; the browser warns once. Accept it if its SHA-256 is
               $FINGERPRINT
               (sudo soha domain NAME gives it a name and a Let's Encrypt one)" ;;
  letsencrypt)
    CERT_NOTE="  Certificate: Let's Encrypt, fetched on the first visit (DNS for $(sed -n 's/^SOHA_TLS_DOMAINS=//p' /etc/soha/soha.env) must point here)" ;;
  *) CERT_NOTE="" ;;
esac
SETUP_CODE=$(cat "$(sed -n 's/^SOHA_SETUP_CODE_FILE=//p' /etc/soha/soha.env | grep . || echo /var/lib/soha/setup-code)" 2>/dev/null || true)
if [[ -n $SETUP_CODE ]]; then
  ACCOUNT_NOTE="  Set up:    open $CONSOLE_URL/setup?code=$SETUP_CODE
             to create the admin account (setup code $SETUP_CODE; sudo soha setup-code shows it again)"
else
  # || true: a failed test inside $( ) would trip the ERR trap on a re-run (no new account).
  ACCOUNT_NOTE="  Sign in:   with the admin account$( [[ -n $ADMIN_PASSWORD_FILE ]] && echo " $ADMIN_USER" || true )"
fi
cat <<EOF

  Console:   $CONSOLE_URL
$CERT_NOTE
$ACCOUNT_NOTE
  Activate:  then the console shows a code; enter it at my.soha.tel to give this server
             its license (the free one included). It needs this once, over the internet.
  Channel:   $CHANNEL, updated daily (soha status, sudo soha update)

  Soha Phone: through the console's HTTPS ($CONSOLE_URL/sip)
  SIP:       $(grep -q '^SOHA_SIP_FIREWALL=on' /etc/soha/soha.env && echo "only from your trunks and $(sed -n 's/^SOHA_SIP_ALLOW=//p' /etc/soha/soha.env | grep . || echo "private networks"); everyone else is dropped (sudo soha status)" || echo "open to everyone (SOHA_SIP_FIREWALL=off)")
  Firewall:  if this server has another firewall, open TCP ${HTTPS_PORT}$( [[ $HTTP_PORT != 0 ]] && echo " and $HTTP_PORT" ) and UDP 10000-20000 (call audio).
EOF
