#!/bin/sh
# Netbine relay installer and updater. Run on a Linux VPS (Debian/Ubuntu) as root:
#
#   curl -fsSL https://panel.netbine.com/install.sh | sudo sh
#
# Options (pass after `sh -s --`):
#   --name <name>          display name in the app, e.g. the city (default: hostname)
#   --client-key <key>     allow this PC right away (key shown in the app)
#   --client-name <name>   name for that PC on the relay (default: pc)
#   --version <x.y.z>      install a specific release instead of the latest
#   --sudo-user <user>     let this login user run netbine-admin through sudo without a password
#
# With NETBINE_PANEL_URL and NETBINE_PANEL_TOKEN set (the panel's Add server page prints the
# whole command), the relay also joins that panel as one of its servers.
#
# Running it again updates the relay and keeps its keys and allowed PCs.
set -eu

# Everything comes from the Netbine panel (our own domain), never a third party.
PANEL="${NETBINE_PANEL_URL:-https://panel.netbine.com}"
PANEL="${PANEL%/}"
VERSION=latest
NAME=""
CLIENT_KEY=""
CLIENT_NAME="pc"
SUDO_USER_NAME=""
while [ $# -gt 0 ]; do
    case "$1" in
        --name) NAME="$2"; shift 2 ;;
        --client-key) CLIENT_KEY="$2"; shift 2 ;;
        --client-name) CLIENT_NAME="$2"; shift 2 ;;
        --version) VERSION="$2"; shift 2 ;;
        --sudo-user) SUDO_USER_NAME="$2"; shift 2 ;;
        *) echo "unknown option: $1"; exit 1 ;;
    esac
done

[ "$(id -u)" -eq 0 ] || { echo "Run as root: ... | sudo sh"; exit 1; }
case "$(uname -m)" in
    x86_64 | amd64) ARCH=x86_64 ;;
    *) echo "Unsupported CPU architecture: $(uname -m) (x86_64 only for now)"; exit 1 ;;
esac

fetch() {
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL --retry 3 -o "$2" "$1"
    else
        wget -q -O "$2" "$1"
    fi
}

if [ -n "${NETBINE_BASE_URL:-}" ]; then
    BASE="$NETBINE_BASE_URL"
else
    if [ "$VERSION" = latest ]; then
        # The newest relay release, which can be older than the newest app release: the relay and
        # its checksums then come from that one release.
        VERSION=$(fetch "$PANEL/api/releases/latest?part=relay" - | sed -n 's/.*"version":"\([0-9.]*\)".*/\1/p')
        [ -n "$VERSION" ] || { echo "Can't find the latest relay release on $PANEL."; exit 1; }
    fi
    BASE="$PANEL/downloads/v${VERSION#v}"
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
echo "Downloading Netbine relay ($VERSION, $ARCH)..."
fetch "$BASE/netbine-relay-linux-$ARCH" "$TMP/netbine-relay-linux-$ARCH"
fetch "$BASE/install-tunnel.sh" "$TMP/install-tunnel.sh"
fetch "$BASE/SHA256SUMS" "$TMP/SHA256SUMS"
(cd "$TMP" && grep -E " (netbine-relay-linux-$ARCH|install-tunnel.sh)\$" SHA256SUMS | sha256sum -c -) \
    || { echo "Checksum verification failed; not installing."; exit 1; }

mv "$TMP/netbine-relay-linux-$ARCH" "$TMP/netbine-relay"
chmod +x "$TMP/netbine-relay"
NETBINE_NAME="$NAME" NETBINE_CLIENT_KEY="$CLIENT_KEY" NETBINE_CLIENT_NAME="$CLIENT_NAME" sh "$TMP/install-tunnel.sh"

# Maintenance entry point for the Netbine app. Replaced atomically (mv) because an update runs
# this installer from inside the old copy.
UPDATE_BASE="$PANEL/downloads/latest"
cat > "$TMP/netbine-admin" <<ADMIN
#!/bin/sh
# Maintenance commands used by the Netbine app: update | restart | logs | status | invite | clients |
# remove-client KEY | filter | set-filter LISTS CUSTOM MBIT
set -eu
BASE="$UPDATE_BASE"
ADMIN
cat >> "$TMP/netbine-admin" <<'ADMIN'
case "${1:-}" in
    update)
        tmp="$(mktemp)"
        trap 'rm -f "$tmp"' EXIT
        if command -v curl >/dev/null 2>&1; then curl -fsSL --retry 3 -o "$tmp" "$BASE/install.sh"; else wget -q -O "$tmp" "$BASE/install.sh"; fi
        NETBINE_BASE_URL="$BASE" sh "$tmp"
        ;;
    restart)
        systemctl restart netbine-tunnel
        sleep 1
        systemctl is-active netbine-tunnel
        ;;
    logs) journalctl -u netbine-tunnel -n 150 --no-pager ;;
    invite)
        netbine-relay invite --config /etc/netbine/tunnel.toml --hours 168 --uses 1 | grep "^NETBINE_INVITE="
        ;;
    clients) netbine-relay clients --config /etc/netbine/tunnel.toml ;;
    filter) netbine-relay filter --config /etc/netbine/tunnel.toml ;;
    set-filter)
        netbine-relay set-filter --config /etc/netbine/tunnel.toml --lists "${2:-}" --custom "${3:-}" --match-download-mbit "${4:-0}"
        ;;
    remove-client)
        netbine-relay remove-client --config /etc/netbine/tunnel.toml --public-key "${2:-}"
        netbine-relay clients --config /etc/netbine/tunnel.toml
        ;;
    status)
        echo "NETBINE_RELAY_VERSION=$(netbine-relay --version | awk '{print $2}')"
        echo "service: $(systemctl is-active netbine-tunnel || true)"
        echo "UDP ports: $(netbine-relay ports --config /etc/netbine/tunnel.toml)"
        echo "allowed PCs: $(grep -c "^\[\[clients\]\]" /etc/netbine/tunnel.toml || true)"
        if command -v ufw >/dev/null; then ufw status | head -1; fi
        echo "recent handshakes:"
        journalctl -u netbine-tunnel -n 300 --no-pager 2>/dev/null | grep -E "session|unknown client|invite|joined" | tail -6 || true
        uptime
        free -m | head -2
        df -h / | tail -1
        ;;
    *) echo "usage: netbine-admin update|restart|logs|status|invite|clients|remove-client KEY|filter|set-filter LISTS CUSTOM MBIT"; exit 1 ;;
esac
ADMIN
chmod 755 "$TMP/netbine-admin"
chown root:root "$TMP/netbine-admin"
mv -f "$TMP/netbine-admin" /usr/local/sbin/netbine-admin

if [ -n "$SUDO_USER_NAME" ] && [ "$SUDO_USER_NAME" != root ]; then
    if printf '%s' "$SUDO_USER_NAME" | grep -Eq '^[a-z_][a-z0-9_-]{0,31}$' && id "$SUDO_USER_NAME" >/dev/null 2>&1; then
        echo "$SUDO_USER_NAME ALL=(root) NOPASSWD: /usr/local/sbin/netbine-admin" > "$TMP/sudoers"
        chmod 440 "$TMP/sudoers"
        if ! command -v visudo >/dev/null 2>&1 || visudo -cf "$TMP/sudoers" >/dev/null; then
            mv -f "$TMP/sudoers" /etc/sudoers.d/netbine
            echo "$SUDO_USER_NAME can now run netbine-admin without a password."
        fi
    else
        echo "Skipping sudo access: unknown user $SUDO_USER_NAME"
    fi
fi
