#!/data/data/com.termux/files/usr/bin/bash
#
# grest-tunnel.sh — turn this phone into a residential exit node for the
# Grest test server, so the server's emulator can load grest.in (which blocks
# datacenter IPs via Blockify) through your phone's mobile/Wi-Fi connection.
#
# Run on your Samsung phone in Termux:
#   curl -fsSL https://files.winds-os.com/grest-tunnel.sh | bash
#
# Keep Termux OPEN while testing. Ctrl-C to stop the tunnel.

set -e

SERVER_USER="usr1"
SERVER_HOST="82.25.86.78"
SERVER_PORT="22"
SOCKS_PORT="1081"

echo "=================================================="
echo "  Grest residential tunnel  (phone -> server)"
echo "=================================================="

# 1) Make sure we're in Termux
if [ ! -d "/data/data/com.termux" ]; then
  echo "!! This must be run inside the Termux app on Android."
  echo "   Install Termux from F-Droid, then run this again."
  exit 1
fi

# 2) Install dependencies (openssh = ssh client, microsocks = SOCKS5 server)
echo "[1/4] Installing ssh + socks proxy (one-time)..."
pkg update -y >/dev/null 2>&1 || true
pkg install -y openssh microsocks >/dev/null 2>&1 || pkg install -y openssh microsocks

# 3) Start a SOCKS5 proxy on the phone (this is the exit node)
echo "[2/4] Starting SOCKS5 proxy on phone port ${SOCKS_PORT}..."
pkill -f "microsocks -p ${SOCKS_PORT}" 2>/dev/null || true
microsocks -p "${SOCKS_PORT}" >/dev/null 2>&1 &
sleep 1
echo "      phone SOCKS proxy is up."

# 4) Show the phone's current public IP so you can confirm it's residential
echo "[3/4] Your phone's public IP (what grest.in will see):"
MYIP=$(curl -s --max-time 8 https://api.ipify.org || echo "unknown")
echo "      >>> ${MYIP} <<<"

# 5) Open the encrypted reverse tunnel into the server.
#    Server's 127.0.0.1:${SOCKS_PORT} -> this phone's SOCKS -> internet.
echo "[4/4] Connecting encrypted tunnel to ${SERVER_USER}@${SERVER_HOST}..."
echo "      (enter the SERVER password when asked; then LEAVE THIS RUNNING)"
echo "--------------------------------------------------"
exec ssh -N \
  -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
  -o ExitOnForwardFailure=yes \
  -p "${SERVER_PORT}" \
  -R "127.0.0.1:${SOCKS_PORT}:127.0.0.1:${SOCKS_PORT}" \
  "${SERVER_USER}@${SERVER_HOST}"
