#!/bin/sh
# v-Shell server helper. Read it before you run it; it changes nothing without asking.
#   curl -fsSL https://v-shell.pages.dev/setup.sh | sh
# Checks SSH and tmux, then prints a QR code / link to add this server in v-Shell.
set -u
say() { printf '%s\n' "$*"; }
ok() { printf '  \033[32m✓\033[0m %s\n' "$*"; }
warn() { printf '  \033[33m!\033[0m %s\n' "$*"; }

user=$(id -un)
os=$(uname -s)
say ">_ v-Shell server check ($os, user $user)"

# 1. SSH server
if [ "$os" = "Darwin" ]; then
  if (systemsetup -getremotelogin 2>/dev/null | grep -qi ': on') || nc -z 127.0.0.1 22 2>/dev/null; then
    ok "Remote Login (SSH) is on"
  else
    warn "Remote Login is off. Turn it on: System Settings > General > Sharing > Remote Login"
  fi
else
  if nc -z 127.0.0.1 22 2>/dev/null || ss -ltn 2>/dev/null | grep -q ':22 '; then ok "SSH server is listening on port 22"
  else warn "No SSH server on port 22. Install it: sudo apt install openssh-server (Debian/Ubuntu)"; fi
fi

# 2. tmux (sessions that survive disconnects)
PATH="$PATH:/opt/homebrew/bin:/usr/local/bin"
if command -v tmux >/dev/null 2>&1; then ok "tmux $(tmux -V | cut -d' ' -f2) installed (sessions survive)"
else
  warn "tmux not installed; sessions will end when the phone disconnects."
  if [ "$os" = "Darwin" ]; then say "    install: brew install tmux"; else say "    install: sudo apt install tmux   (or dnf/pacman)"; fi
fi

# 3. Best address: Tailscale first (works from anywhere), else LAN.
addr=""; kind=""
if command -v tailscale >/dev/null 2>&1; then
  addr=$(tailscale ip -4 2>/dev/null | head -n1); [ -n "$addr" ] && kind="Tailscale (works from anywhere)"
fi
if [ -z "$addr" ]; then
  if [ "$os" = "Darwin" ]; then addr=$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null)
  else addr=$(hostname -I 2>/dev/null | awk '{print $1}'); fi
  kind="home network only (install Tailscale to connect from anywhere)"
fi
[ -n "$addr" ] || { warn "Could not find an IP address."; exit 1; }
ok "address $addr, $kind"

name=$(hostname -s 2>/dev/null || hostname)
link="vshell://add?host=$addr&user=$user&port=22&name=$name"
say ""
say "In v-Shell: Add server > Scan QR (or Paste link):"
say "  $link"
if command -v qrencode >/dev/null 2>&1; then qrencode -t ANSIUTF8 "$link"
else say "  (install qrencode to show a QR code here: brew/apt install qrencode)"; fi
say ""
say "Then enter your password for '$user' once. v-Shell installs its own key and never stores the password."
