#!/usr/bin/env bash
set -Eeuo pipefail
# В tls_domain указываем на что фейкуем.

NODES=(
   remn-fin
  #remn-sweden
  #remn-nl-02
  #remn-msk
  #remn-riga
  #remn-nl-01
  #remn-paris
)

REMOTE_DIR="/opt/telemt"

CONFIG_TOML='[general]
prefer_ipv6 = false
fast_mode = true
use_middle_proxy = false

[network]
ipv4 = true
ipv6 = true
prefer = 4
multipath = false

[general.modes]
classic = false
secure = false
tls = true

[server]
port = 443
listen_addr_ipv4 = "0.0.0.0"
listen_addr_ipv6 = "::"

[[server.listeners]]
ip = "0.0.0.0"

[[server.listeners]]
ip = "::"

[general.links]
show = "*"

[timeouts]
client_handshake = 15
tg_connect = 10
client_keepalive = 60
client_ack = 300

[censorship]
tls_domain = "max.ru"
mask = true
mask_port = 443
fake_cert_len = 2048

[access]
replay_check_len = 65536
ignore_time_skew = false

[access.users]
SECRET_PLACEHOLDER

[[upstreams]]
type = "direct"
enabled = true
weight = 10'

DOCKER_COMPOSE='services:
  telemt:
    image: ghcr.io/telemt/telemt:latest
    restart: unless-stopped
    ports:
      - "8443:443"
    volumes:
      - ./config.toml:/app/config.toml:ro
    environment:
      - RUST_LOG=info
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
    ulimits:
      nofile:
        soft: 65536
        hard: 65536'

for node in "${NODES[@]}"; do
  echo "=== Installing telemt on ${node} ==="

  # Создаем секрет
  SECRET=$(openssl rand -hex 16)
  FINAL_CONFIG="${CONFIG_TOML/SECRET_PLACEHOLDER/main = \"${SECRET}\"}"

  # Костыль чтобы в output дать внешний IP, а не IP docker подсети
  PUBLIC_IP=$(ssh "$node" "ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'")

  if ssh "$node" "sudo mkdir -p ${REMOTE_DIR}"; then
    #config.toml and docker-compose.yml
    echo "$FINAL_CONFIG"   | ssh "$node" "sudo tee ${REMOTE_DIR}/config.toml > /dev/null"
    echo "$DOCKER_COMPOSE" | ssh "$node" "sudo tee ${REMOTE_DIR}/docker-compose.yml > /dev/null"

    if ssh "$node" "cd ${REMOTE_DIR} && sudo docker compose pull && sudo docker compose up -d"; then
      # Крафтим линку tg:// URL manually
      SECRET_HEX="ee${SECRET}"
      TLS_DOMAIN_HEX=$(echo -n "max.ru" | xxd -p)
      FULL_SECRET="${SECRET_HEX}${TLS_DOMAIN_HEX}"

      echo "=== ${node}: OK ==="
      echo "    Node IP  : ${PUBLIC_IP}"
      echo "    Port     : 8443"
      echo "    Secret   : ${FULL_SECRET}"
      echo "    MTProto  : tg://proxy?server=${PUBLIC_IP}&port=8443&secret=${FULL_SECRET}"
    else
      echo "=== ${node}: FAILED (docker compose) ==="
    fi
  else
    echo "=== ${node}: FAILED (ssh/mkdir) ==="
  fi

  echo
done