#!/bin/bash
# Create SIP devices for VWP extensions 101-118
# This auto-generates the device-sip-registration-password for each user

DOMAIN="vwp.91912.service"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PY_WRAPPER="bash $SCRIPT_DIR/../../../.claude/scripts/py.sh"

EXTENSIONS=(101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118)

echo "[INFO] Creating SIP devices for 18 VWP extensions..."
echo ""

SUCCESS=0
FAILED=0

for ext in "${EXTENSIONS[@]}"; do
  echo "[INFO] Creating device for extension $ext"

  # Create device (device name = user extension)
  BODY="{\"device\":\"$ext\",\"user\":\"$ext\"}"
  RESULT=$($PY_WRAPPER "$SCRIPT_DIR/ns.py" create-device "$DOMAIN" "$ext" --body "$BODY" --confirm 2>&1)

  if echo "$RESULT" | grep -q "HTTP 400.*already exists"; then
    echo "  [SKIP] Device $ext already exists"
    ((SUCCESS++))
  elif echo "$RESULT" | grep -qE "HTTP [45]"; then
    echo "  [ERROR] Failed to create device $ext: $RESULT"
    ((FAILED++))
  else
    echo "  [OK] Created device $ext"
    ((SUCCESS++))
  fi
done

echo ""
echo "[SUMMARY] Devices: $SUCCESS created/existing, $FAILED failed"
echo ""
echo "[INFO] Fetching all device passwords..."
echo ""

# Get all passwords
for ext in "${EXTENSIONS[@]}"; do
  PASSWORD=$($PY_WRAPPER "$SCRIPT_DIR/ns.py" devices "$DOMAIN" "$ext" 2>/dev/null | grep -o '"device-sip-registration-password": "[^"]*"' | cut -d'"' -f4)
  if [ -n "$PASSWORD" ]; then
    echo "Extension $ext: $PASSWORD"
  else
    echo "Extension $ext: [ERROR - Could not retrieve password]"
  fi
done
