#!/bin/bash
set -euo pipefail

if [[ $EUID -ne 0 ]]; then
    echo "❌ Ошибка: этот скрипт должен быть запущен от root"
    exit 1
fi

echo "Установка Asterisk 20 LTS с русским языком..."

check_asterisk_installed() {
    if [ -f /usr/sbin/asterisk ] || systemctl is-active --quiet asterisk 2>/dev/null; then
        return 0
    else
        return 1
    fi
}

if check_asterisk_installed; then
    echo "⚠️  Asterisk уже установлен. Пропускаем установку."
    SKIP_ASTERISK_INSTALL=true
else
    SKIP_ASTERISK_INSTALL=false
fi

echo "Обновление системы..."
apt update && apt -y upgrade

echo "Установка зависимостей..."
apt -y install build-essential git wget subversion \
libxml2-dev libncurses5-dev uuid-dev libjansson-dev libssl-dev libsqlite3-dev \
libedit-dev libcurl4-openssl-dev libnewt-dev liblua5.2-dev unixodbc-dev

if ! id "asterisk" &>/dev/null; then
    echo "Создание пользователя asterisk..."
    adduser --quiet --system --group --home /var/lib/asterisk asterisk
fi

if [ "$SKIP_ASTERISK_INSTALL" = false ]; then
    echo "Скачивание и установка Asterisk..."
    cd /usr/src
    wget -q https://downloads.asterisk.org/pub/telephony/asterisk/asterisk-20-current.tar.gz
    tar xzf asterisk-20-current.tar.gz
    cd asterisk-20.*
    contrib/scripts/get_mp3_source.sh || true
    contrib/scripts/install_prereq install
    ./configure
    make menuselect.makeopts
    menuselect/menuselect --enable-category MENUSELECT_ADDONS --enable chan_pjsip
    make -j$(nproc)
    make install
    make samples
    make config
    ldconfig
fi

echo "Настройка прав и пользователя..."
mkdir -p /var/{lib,log,spool,run}/asterisk
chown -R asterisk:asterisk /etc/asterisk /var/{lib,log,spool,run}/asterisk /usr/lib/asterisk
chmod -R 750 /var/run/asterisk
echo 'AST_USER="asterisk"' > /etc/default/asterisk
echo 'AST_GROUP="asterisk"' >> /etc/default/asterisk

systemctl daemon-reload
systemctl enable asterisk

echo "Настройка modules.conf..."
cat > /etc/asterisk/modules.conf <<'EOF'
[modules]
autoload=yes
preload = res_pjsip_pubsub.so
preload = res_pjsip.so
preload = chan_pjsip.so
noload = chan_sip.so
EOF

# === Генерация пользователей для всех пар ===
echo "Настройка pjsip.conf для всех пар..."

PAIRS=(0 1 2 3 4 5 6 7 8 9)
INTERNAL=(0 1 2 3 4 5 6 7 8 9)

cat > /etc/asterisk/pjsip.conf <<'EOF'
[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0:5060
EOF

for pair in "${PAIRS[@]}"; do
    for num in "${INTERNAL[@]}"; do
        EXT="${pair}${num}0"
        PASS="${EXT}pass"
        cat >> /etc/asterisk/pjsip.conf <<EOL
; Пользователь $EXT
[$EXT]
type=endpoint
context=office
disallow=all
allow=ulaw,alaw,gsm
transport=transport-udp
auth=auth$EXT
aors=$EXT
callerid="User $EXT" <$EXT>
force_rport=yes
rewrite_contact=yes
rtp_symmetric=yes
direct_media=no
language=ru

[auth$EXT]
type=auth
auth_type=userpass
password=$PASS
username=$EXT

[$EXT]
type=aor
max_contacts=1

EOL
    done
done

# === RTP ===
echo "Настройка RTP..."
cat > /etc/asterisk/rtp.conf <<'EOF'
[general]
rtpstart=10000
rtpend=20000
EOF

# === Dialplan ===
echo "Настройка extensions.conf с русским языком..."
cat > /etc/asterisk/extensions.conf <<'EOF'
[general]
static=yes
writeprotect=no
clearglobalvars=no

[office]
exten => _XXX,1,NoOp(Вызов к ${EXTEN})
same => n,Dial(PJSIP/${EXTEN},20)
same => n,Hangup()

exten => 600,1,Answer()
same => n,Set(CHANNEL(language)=ru)
same => n,Echo()
same => n,Hangup()
EOF

echo "Создание директорий..."
mkdir -p /var/spool/asterisk
chown -R asterisk:asterisk /var/spool/asterisk

echo "Установка русских звуковых файлов..."
paths=/var/lib/asterisk/sounds
mkdir -p $paths/ru
cd /tmp
wget -c http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-ru-wav-current.tar.gz
cd $paths/ru
tar zxvf /tmp/asterisk-core-sounds-ru-wav-current.tar.gz
chown -R asterisk:asterisk $paths/ru

echo "Настройка системной локали для русского языка..."
if ! grep -q "ru_RU.UTF-8" /etc/locale.gen; then
    echo "ru_RU.UTF-8 UTF-8" >> /etc/locale.gen
    locale-gen
fi

echo "Перезапуск Asterisk..."
systemctl restart asterisk
sleep 5

echo "Проверка Asterisk..."
systemctl is-active --quiet asterisk && echo "✅ Asterisk запущен!" || echo "❌ Ошибка запуска!"

echo "=== Проверка пользователей ==="
for pair in "${PAIRS[@]}"; do
    for num in "${INTERNAL[@]}"; do
        EXT="${pair}${num}0"
        if asterisk -rx "pjsip show endpoint $EXT" | grep -q "Endpoint:"; then
            echo "✅ $EXT готов"
        else
            echo "❌ Проблема с $EXT"
        fi
    done
done

echo
echo "✅ Установка завершена!"
echo "Пример пользователей:"
for pair in "${PAIRS[@]}"; do
    for num in "${INTERNAL[@]}"; do
        EXT="${pair}${num}0"
        PASS="${EXT}pass"
        echo " $EXT | $PASS"
    done
done
echo
echo "Тест: позвоните между номерами внутри сети или используйте *600 для эхо-теста."
echo "------------------------------------------------"
