#!/usr/bin/env bash
# Installs the free WhatsApp server (WAHA, the open-source WhatsApp HTTP API) on this VPS with Docker,
# keeps it reachable only from this machine, and saves its address and key in the billing panel.
#   sudo bash bin/install_whatsapp_server.sh
# Re-running is safe: it keeps your key and linked phone. To remove: cd /opt/waha && docker compose down
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "Run with sudo:  sudo bash $0"; exit 1; }
APP="$(cd "$(dirname "$0")/.." && pwd)"
DIR=/opt/waha; BIND=127.0.0.1
mkdir -p "$DIR"
# Port: keep the one chosen on a previous run, else WAHA_PORT=NNNN, else the first free one from 3100 (3000 is often taken by other apps)
if [ -f "$DIR/.port" ]; then PORT="$(cat "$DIR/.port")"
else
  PORT="${WAHA_PORT:-}"
  if [ -z "$PORT" ]; then for p in $(seq 3100 3199); do ss -ltn 2>/dev/null | awk '{print $4}' | grep -Eq "[:.]$p$" || { PORT=$p; break; }; done; fi
  [ -n "$PORT" ] || { echo "No free port found; run with WAHA_PORT=NNNN"; exit 1; }
  echo "$PORT" > "$DIR/.port"
fi

if ! command -v docker >/dev/null 2>&1; then
  echo "Installing Docker..."
  apt-get update -qq && apt-get install -y -qq ca-certificates curl >/dev/null
  curl -fsSL https://get.docker.com | sh
fi
docker compose version >/dev/null 2>&1 || apt-get install -y -qq docker-compose-plugin >/dev/null

# Where the server posts customer messages (the panel's Inbox + keyword bot). Empty when the panel is not installed yet: Messages -> Replies has a button for it.
HOOK=""
if [ -f "$APP/config/config.php" ]; then HOOK="$(sudo -u "$(stat -c %U "$APP/config/config.php")" php "$APP/bin/wa_setup.php" --hook-url 2>/dev/null | head -1 || true)"; fi
HOOK_YML=""; case "$HOOK" in https://*|http://*) HOOK_YML="      WHATSAPP_HOOK_URL: \"$HOOK\"
      WHATSAPP_HOOK_EVENTS: \"message\"" ;; esac

mkdir -p "$DIR/sessions" && cd "$DIR"
if [ -f .env ] && grep -q '^WHATSAPP_API_KEY=' .env; then KEY="$(grep '^WHATSAPP_API_KEY=' .env | cut -d= -f2)"; else
  KEY="$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')"; printf 'WHATSAPP_API_KEY=%s\n' "$KEY" > .env; chmod 600 .env; fi

cat > docker-compose.yml <<YML
services:
  waha:
    image: devlikeapro/waha
    container_name: waha
    restart: always
    ports:
      - "${BIND}:${PORT}:3000"          # this server only; the billing panel talks to it locally, the internet cannot
    env_file: .env
    environment:
      WHATSAPP_START_SESSION: default
      WHATSAPP_RESTART_ALL_SESSIONS: "True"
      WAHA_DASHBOARD_ENABLED: "False"
      WHATSAPP_SWAGGER_ENABLED: "False"
${HOOK_YML}
    volumes:
      - ./sessions:/app/.sessions       # keeps the phone linked after restarts and updates
YML
echo "Starting the WhatsApp server..."
docker compose pull -q && docker compose up -d --remove-orphans
for i in $(seq 1 30); do curl -fs -H "X-Api-Key: $KEY" "http://${BIND}:${PORT}/api/sessions" >/dev/null 2>&1 && break; sleep 2; done
curl -fs -H "X-Api-Key: $KEY" "http://${BIND}:${PORT}/api/sessions" >/dev/null 2>&1 || { echo "The server did not answer yet. Check:  docker logs waha"; }

if [ -f "$APP/config/config.php" ]; then
  U="$(stat -c %U "$APP/config/config.php")"
  sudo -u "$U" php "$APP/bin/wa_setup.php" "http://${BIND}:${PORT}" "$KEY" default || echo "Could not save the settings; enter them by hand (address http://${BIND}:${PORT}, key below)."
fi
cat <<MSG

Done.
  Server address : http://${BIND}:${PORT}
  API key        : ${KEY}
Next: in the billing panel open Messages → Gateway, choose "WhatsApp (free, own server)", press
"Check connection", scan the QR with the spare phone (WhatsApp → Linked devices), then Save and send a test.
Logs: docker logs -f waha     Update: cd $DIR && docker compose pull && docker compose up -d
MSG
