#!/usr/bin/env bash
# run_teleop.sh — Launch GELLO blue teleop on the remote robot server.
#
# Usage:
#   ./scripts/run_teleop.sh <[user@]ngrok_host> <ngrok_port>
#
# Examples:
#   ./scripts/run_teleop.sh 4.tcp.us-cal-1.ngrok.io 12345
#   ./scripts/run_teleop.sh root@4.tcp.us-cal-1.ngrok.io 12345
#
# Starts tmux session (stays open on failure so you can see errors):
#   panda_teleop — runs calib + blue_gello_teleop on the remote machine

set -e

ARG_HOST="${1:?Usage: $0 <[user@]ngrok_host> <ngrok_port>}"
NGROK_PORT="${2:?Usage: $0 <[user@]ngrok_host> <ngrok_port>}"

# Handle both "host" and "user@host" formats
if [[ "$ARG_HOST" == *"@"* ]]; then
    REMOTE_USER="${ARG_HOST%%@*}"
    NGROK_HOST="${ARG_HOST##*@}"
else
    REMOTE_USER="root"
    NGROK_HOST="$ARG_HOST"
fi

REMOTE_PASS="elitesmasher99"
SSH_OPTS="-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/null"

echo "==> Connecting to ${REMOTE_USER}@${NGROK_HOST}:${NGROK_PORT}"

# Kill any existing session so re-runs start clean
tmux kill-session -t panda_teleop 2>/dev/null || true

echo "==> Starting GELLO teleop on remote..."
tmux new-session -d -s panda_teleop -x 220 -y 50 \
    "sshpass -p '${REMOTE_PASS}' ssh ${SSH_OPTS} ${REMOTE_USER}@${NGROK_HOST} -p ${NGROK_PORT} \
    'source /opt/ros/humble/setup.bash; source /root/franka_ws/install/setup.bash; cd /workspace/ros2; python3 scripts/calib.py --gello_name blue_gello; ./scripts/blue_gello_teleop.sh'; echo '--- teleop exited (code $?) ---'; read"

echo ""
echo "==> Teleop session launched. Attach with:"
echo "    tmux attach -t panda_teleop"
