#!/usr/bin/env bash
set -euo pipefail

template_dir="/config-template"
monitor_dir="/var/spool/asterisk/monitor/mvpcc"
primary_sounds_dir="/usr/share/asterisk/sounds"
legacy_sounds_dir="/var/lib/asterisk/sounds"
keys_dir="/etc/asterisk/keys"

password_1001="${ASTERISK_ENDPOINT_1001_PASSWORD:-${ASTERISK_AMI_SECRET:-ChangeMe-1001}}"
password_2001="${ASTERISK_ENDPOINT_2001_PASSWORD:-${ASTERISK_AMI_SECRET:-ChangeMe-2001}}"
password_2002="${ASTERISK_ENDPOINT_2002_PASSWORD:-${ASTERISK_AMI_SECRET:-ChangeMe-2002}}"
ami_secret="${ASTERISK_AMI_SECRET:-ChangeMe-AmiSecret}"
external_address="${ASTERISK_EXTERNAL_ADDRESS:-92.38.48.166}"

mkdir -p /etc/asterisk "$monitor_dir" "$primary_sounds_dir" "$legacy_sounds_dir" "$keys_dir"

for file in extensions.conf pjsip.conf manager.conf http.conf rtp.conf; do
  cp "${template_dir}/${file}" "/etc/asterisk/${file}"
done

export ASTERISK_PASSWORD_1001="$password_1001"
export ASTERISK_PASSWORD_2001="$password_2001"
export ASTERISK_PASSWORD_2002="$password_2002"
export ASTERISK_MANAGER_SECRET="$ami_secret"
export ASTERISK_EXTERNAL_ADDRESS_VALUE="$external_address"

python3 - <<'PY'
from pathlib import Path
import os

replacements = {
    "ChangeMe-1001": os.environ["ASTERISK_PASSWORD_1001"],
    "ChangeMe-2001": os.environ["ASTERISK_PASSWORD_2001"],
    "ChangeMe-2002": os.environ["ASTERISK_PASSWORD_2002"],
    "ChangeMe-AmiSecret": os.environ["ASTERISK_MANAGER_SECRET"],
    "92.38.48.166": os.environ["ASTERISK_EXTERNAL_ADDRESS_VALUE"],
}

for path in (
    Path("/etc/asterisk/pjsip.conf"),
    Path("/etc/asterisk/manager.conf"),
):
    text = path.read_text(encoding="utf-8")
    for old, new in replacements.items():
        text = text.replace(old, new)
    path.write_text(text, encoding="utf-8")

modules_path = Path("/etc/asterisk/modules.conf")
if modules_path.exists():
    text = modules_path.read_text(encoding="utf-8")
    if "noload => chan_sip.so" not in text:
        stanza = (
            "; MVPCC uses PJSIP/WebRTC for browser softphones.\n"
            "noload => chan_sip.so\n\n"
        )
        if "[global]" in text:
            text = text.replace("[global]", f"{stanza}[global]", 1)
        elif "[modules]" in text:
            text = text.rstrip() + "\n\n" + stanza
        else:
            text = "[modules]\nautoload=yes\n\n" + stanza + text
        modules_path.write_text(text, encoding="utf-8")
PY

if [ ! -f "${keys_dir}/asterisk.pem" ] || [ ! -f "${keys_dir}/asterisk.key" ]; then
  openssl req \
    -x509 \
    -nodes \
    -newkey rsa:2048 \
    -keyout "${keys_dir}/asterisk.key" \
    -out "${keys_dir}/asterisk.pem" \
    -days 3650 \
    -subj "/CN=${external_address}"
fi

if [ -f /assets/mvpcc_ivr_prompt.wav ]; then
  for sounds_dir in "$primary_sounds_dir" "$legacy_sounds_dir"; do
    cp /assets/mvpcc_ivr_prompt.wav "${sounds_dir}/mvpcc_ivr_prompt.wav"
    mkdir -p "${sounds_dir}/en" "${sounds_dir}/ru" "${sounds_dir}/ru_RU"
    cp /assets/mvpcc_ivr_prompt.wav "${sounds_dir}/en/mvpcc_ivr_prompt.wav"
    cp /assets/mvpcc_ivr_prompt.wav "${sounds_dir}/ru/mvpcc_ivr_prompt.wav"
    cp /assets/mvpcc_ivr_prompt.wav "${sounds_dir}/ru_RU/mvpcc_ivr_prompt.wav"
  done
fi

if [ -d /assets/ivr ]; then
  for sounds_dir in "$primary_sounds_dir" "$legacy_sounds_dir"; do
    mkdir -p "${sounds_dir}/ivr"
    cp -a /assets/ivr/. "${sounds_dir}/ivr/"
  done
fi

chown -R asterisk:asterisk /etc/asterisk "$keys_dir" /var/spool/asterisk/monitor

for sounds_dir in "$primary_sounds_dir" "$legacy_sounds_dir"; do
  if [ -w "$sounds_dir" ]; then
    chown -R asterisk:asterisk "$sounds_dir"
  fi
done

chmod 0755 /var/spool/asterisk /var/spool/asterisk/monitor "$monitor_dir"

exec /usr/sbin/asterisk -f -U asterisk -G asterisk -vvv
