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

cc=RU
account_id=
timezone=Europe/Moscow
output=capsula-setup.wav

usage() {
  echo "Usage: $0 [--cc RU] [--account-id ID] [--timezone ZONE] [--output FILE] <vk-token-or-redirect-url> <ssid> [password]" >&2
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --cc)
      [[ $# -ge 2 ]] || { usage; exit 2; }
      cc=$2
      shift 2
      ;;
    --account-id)
      [[ $# -ge 2 ]] || { usage; exit 2; }
      account_id=$2
      shift 2
      ;;
    --timezone)
      [[ $# -ge 2 ]] || { usage; exit 2; }
      timezone=$2
      shift 2
      ;;
    --output|-o)
      [[ $# -ge 2 ]] || { usage; exit 2; }
      output=$2
      shift 2
      ;;
    --)
      shift
      break
      ;;
    -*)
      usage
      exit 2
      ;;
    *)
      break
      ;;
  esac
done

[[ $# -ge 2 && $# -le 3 ]] || { usage; exit 2; }
vk_token=$1
ssid=$2
psk=${3:-}
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
node_cmd=${CAPSULA_NODE:-node}
command -v "$node_cmd" >/dev/null 2>&1 || { echo "Node.js 18+ is required; set CAPSULA_NODE to its executable" >&2; exit 1; }
encoder=$script_dir/capsula-setup.mjs
if [[ $node_cmd == *.exe ]]; then
  command -v wslpath >/dev/null 2>&1 || { echo "wslpath is required with a Windows Node.js executable" >&2; exit 1; }
  encoder=$(wslpath -w "$encoder")
  output=$(wslpath -w "$(readlink -f "$output")")
fi

CAPSULA_VK_TOKEN="$vk_token" \
CAPSULA_SSID="$ssid" \
CAPSULA_PSK="$psk" \
CAPSULA_COUNTRY="$cc" \
CAPSULA_ACCOUNT_ID="$account_id" \
CAPSULA_TIMEZONE="$timezone" \
"$node_cmd" "$encoder" --output "$output"
