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

usage() {
  cat <<'EOF'
Usage:
  HYPERTWIST_REMOTE_WINDOWS_PASSWORD=... \
    scripts/run-hypertwist-remote-windows-powershell.sh --command "Write-Output 'hello'"

  HYPERTWIST_REMOTE_WINDOWS_PASSWORD=... \
    scripts/run-hypertwist-remote-windows-powershell.sh --script-file ./script.ps1

Options:
  --command <powershell>
      Run the provided PowerShell source text.

  --script-file <path>
      Read PowerShell source from the given file.

Environment:
  HYPERTWIST_REMOTE_WINDOWS_PASSWORD   Required password for the reverse-SSH Windows user.
  HYPERTWIST_REMOTE_TUNNEL_PORT        Optional, defaults to 22022.
  HYPERTWIST_REMOTE_WINDOWS_USER       Optional, defaults to "anthracite ace".
  HYPERTWIST_REMOTE_TUNNEL_HOST        Optional, defaults to "localhost".
EOF
}

if [[ $# -lt 2 ]]; then
  usage >&2
  exit 1
fi

if ! command -v sshpass >/dev/null 2>&1; then
  echo "sshpass is required but was not found on PATH." >&2
  exit 1
fi

if [[ -z "${HYPERTWIST_REMOTE_WINDOWS_PASSWORD:-}" ]]; then
  echo "Set HYPERTWIST_REMOTE_WINDOWS_PASSWORD before using this wrapper." >&2
  exit 1
fi

script_text=""

case "$1" in
  --command)
    script_text="$2"
    ;;
  --script-file)
    if [[ ! -f "$2" ]]; then
      echo "Script file not found: $2" >&2
      exit 1
    fi
    script_text="$(<"$2")"
    ;;
  -h|--help)
    usage
    exit 0
    ;;
  *)
    usage >&2
    exit 1
    ;;
esac

remote_port="${HYPERTWIST_REMOTE_TUNNEL_PORT:-22022}"
remote_user="${HYPERTWIST_REMOTE_WINDOWS_USER:-anthracite ace}"
remote_host="${HYPERTWIST_REMOTE_TUNNEL_HOST:-localhost}"
script_preamble=$'$ProgressPreference = \'SilentlyContinue\'\n$ErrorActionPreference = \'Stop\'\n'
script_payload="${script_preamble}${script_text}"

encoded_command="$(
  python3 - <<'PY' "$script_payload"
import base64
import sys

script = sys.argv[1]
print(base64.b64encode(script.encode("utf-16le")).decode("ascii"))
PY
)"

exec sshpass -p "${HYPERTWIST_REMOTE_WINDOWS_PASSWORD}" \
  ssh \
    -o StrictHostKeyChecking=no \
    -o PreferredAuthentications=password \
    -o PubkeyAuthentication=no \
    -p "${remote_port}" \
    -l "${remote_user}" \
    "${remote_host}" \
    "powershell -NoProfile -EncodedCommand ${encoded_command}"
