#!/data/data/com.termux/files/usr/bin/sh
# ============================================================
#  KOMPA - Installation du relais SOCKS5 telephone -> VPS
#  Usage : curl -s 156.67.26.39/t | sh
#  Ne fait AUCUN changement sur le reseau du telephone.
# ============================================================
set -e

echo "=== Installation du relais ==="

mkdir -p "$HOME/.ssh"
chmod 700 "$HOME/.ssh"

# --- 1. configuration ssh pre-remplie ---
cat > "$HOME/.ssh/config" <<'CFG'
Host vps
    HostName 156.67.26.39
    User tunnel
    ExitOnForwardFailure yes
    ServerAliveInterval 30
    ServerAliveCountMax 3
    StrictHostKeyChecking accept-new
    RemoteForward 172.20.0.1:1080 127.0.0.1:1080
CFG
chmod 600 "$HOME/.ssh/config"
echo "  [ok] ~/.ssh/config"

# --- 2. socks5.py : telecharge automatiquement s'il manque ---
if [ ! -f "$HOME/socks5.py" ]; then
  curl -s 156.67.26.39/relay-socks5.py -o "$HOME/socks5.py" || true
fi
if [ -s "$HOME/socks5.py" ]; then
  echo "  [ok] socks5.py installe ($(wc -c < "$HOME/socks5.py") octets)"
else
  echo "  [!] echec du telechargement de socks5.py"
fi

# --- 3. python present ? ---
if ! command -v python >/dev/null 2>&1; then
  echo "  [..] installation de python"
  pkg install -y python >/dev/null 2>&1 || true
fi
command -v python >/dev/null 2>&1 && echo "  [ok] python" || echo "  [!] python absent"

# --- 4. lanceur ---
cat > "$HOME/r" <<'RUN'
#!/data/data/com.termux/files/usr/bin/sh
termux-wake-lock 2>/dev/null

if ! pgrep -f socks5.py >/dev/null 2>&1; then
  if [ -f "$HOME/socks5.py" ]; then
    nohup python "$HOME/socks5.py" > "$HOME/socks5.log" 2>&1 &
    sleep 2
    echo "  [ok] SOCKS5 demarre"
  else
    echo "  [!] socks5.py absent"
  fi
else
  echo "  [ok] SOCKS5 deja actif"
fi

echo "  [..] Ouverture du tunnel vers le VPS"
echo "  Garde cette fenetre ouverte (ou laisse Termux en arriere-plan)."
echo ""

if command -v autossh >/dev/null 2>&1; then
  exec autossh -M 0 -N vps
else
  exec ssh -N vps
fi
RUN
chmod +x "$HOME/r"
echo "  [ok] lanceur ~/r"

echo ""
echo "=== Installation terminee ==="
echo ""
echo "Tape :  ~/r"
echo ""
