#!/bin/sh
# Netbine box: a Raspberry Pi, a mini PC or an OpenWrt router that bonds the home's internet
# lines and sends every device on the home network (consoles and TVs too) through Netbine.
# Run as root on the box:
#
#   curl -fsSL https://panel.netbine.com/box.sh | sh
#   wget -qO- https://panel.netbine.com/box.sh | sh        (OpenWrt)
#
# It installs netbine-client, signs the box in with a code you approve on your phone, and starts
# it as a service. Options (after `sh -s --`):
#   --lan <interface>   the home network the box shares with (OpenWrt: br-lan; else detected)
#   --no-lan            don't share: the box only tunnels itself
#   --keep-dns          leave the home network's DNS to the box's own resolver
#   --name <name>       how the account's device list shows the box (default: Netbine box)
#   --version <x.y.z>   install a specific release instead of the latest
#   --uninstall         stop the box and remove what this installed
#
# Running it again updates netbine-client and keeps the box signed in. Stopping the service
# undoes the box's network changes; the home network then uses its internet directly.
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
LAN=""
NO_LAN=0
KEEP_DNS=0
NAME="Netbine box"
UNINSTALL=0
while [ $# -gt 0 ]; do
    case "$1" in
        --lan) LAN="$2"; shift 2 ;;
        --no-lan) NO_LAN=1; shift ;;
        --keep-dns) KEEP_DNS=1; shift ;;
        --name) NAME="$2"; shift 2 ;;
        --version) VERSION="$2"; shift 2 ;;
        --uninstall) UNINSTALL=1; shift ;;
        *) echo "unknown option: $1"; exit 1 ;;
    esac
done

[ "$(id -u)" -eq 0 ] || { echo "Run as root."; exit 1; }
CONF_DIR=/etc/netbine
CONFIG="$CONF_DIR/box.toml"
BIN=/usr/bin/netbine-client
OPENWRT=0
[ -f /etc/openwrt_release ] && OPENWRT=1

stop_service() {
    if [ -x /etc/init.d/netbine-box ]; then
        /etc/init.d/netbine-box stop 2>/dev/null || true
        /etc/init.d/netbine-box disable 2>/dev/null || true
    fi
    if command -v systemctl >/dev/null 2>&1; then
        systemctl disable --now netbine-box.service 2>/dev/null || true
    fi
}

if [ "$UNINSTALL" = 1 ]; then
    stop_service
    rm -f /etc/init.d/netbine-box /etc/systemd/system/netbine-box.service "$BIN"
    command -v systemctl >/dev/null 2>&1 && systemctl daemon-reload 2>/dev/null || true
    rm -rf "$CONF_DIR"
    echo "Netbine box removed. To free its place on the account, remove \"$NAME\" from your devices in the app or on the website."
    exit 0
fi

case "$(uname -m)" in
    x86_64 | amd64) ARCH=x86_64 ;;
    aarch64 | arm64) ARCH=aarch64 ;;
    armv7l | armv7 | armv8l) ARCH=armv7 ;;
    *) echo "Unsupported CPU: $(uname -m). The Netbine box runs on x86_64, ARM64 and ARMv7."; 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
}

# The tunnel needs the kernel's TUN device.
if [ ! -e /dev/net/tun ]; then
    modprobe tun 2>/dev/null || true
    if [ ! -e /dev/net/tun ] && [ "$OPENWRT" = 1 ]; then
        echo "Installing the TUN driver (kmod-tun)..."
        opkg update >/dev/null && opkg install kmod-tun >/dev/null
    fi
    [ -e /dev/net/tun ] || { echo "This system has no TUN device (/dev/net/tun); the box can't run here."; exit 1; }
fi

if [ "$VERSION" = latest ]; then
    VERSION=$(fetch "$PANEL/api/releases/latest?part=box" - | sed -n 's/.*"version":"\([0-9.]*\)".*/\1/p')
    [ -n "$VERSION" ] || { echo "Can't find the latest Netbine box release on $PANEL."; exit 1; }
fi
BASE="$PANEL/downloads/v${VERSION#v}"

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
echo "Downloading Netbine box $VERSION ($ARCH)..."
FILE="netbine-box-linux-$ARCH"
fetch "$BASE/$FILE" "$TMP/$FILE"
fetch "$BASE/SHA256SUMS" "$TMP/SHA256SUMS"
(cd "$TMP" && grep -E " $FILE\$" SHA256SUMS | sha256sum -c - >/dev/null) || { echo "Checksum verification failed; not installing."; exit 1; }
chmod 755 "$TMP/$FILE"
stop_service
mv -f "$TMP/$FILE" "$BIN"
mkdir -p "$CONF_DIR"
chmod 700 "$CONF_DIR"

# Signing in: once, with a code approved from a phone. Updates keep the sign-in.
if [ ! -f "$CONFIG" ]; then
    "$BIN" link --config "$CONFIG" --panel "$PANEL" --name "$NAME"
fi

# The home network to share with: OpenWrt's LAN bridge, or the interface with a private address
# that isn't the way to the internet.
if [ "$NO_LAN" = 0 ] && [ -z "$LAN" ]; then
    if [ -d /sys/class/net/br-lan ]; then
        LAN=br-lan
    else
        WAN=$(ip -4 route show default 2>/dev/null | sed -n 's/.* dev \([^ ]*\).*/\1/p' | head -n 1)
        LAN=$(ip -4 -o addr show 2>/dev/null | awk '{print $2, $4}' \
            | grep -E ' (10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)' \
            | awk -v wan="$WAN" '$1 != wan && $1 != "lo" && $1 !~ /^(netbine|docker|veth|virbr|tun|wg)/ {print $1}' | head -n 1)
    fi
    if [ -z "$LAN" ]; then
        echo "No home network found to share with: the box tunnels only itself. Run again with --lan <interface> to share."
    fi
fi
ARGS="run --config $CONFIG --no-status"
[ -n "$LAN" ] && ARGS="$ARGS --gateway $LAN"
[ "$KEEP_DNS" = 1 ] && ARGS="$ARGS --keep-dns"

if [ "$OPENWRT" = 1 ] || { [ -f /etc/rc.common ] && ! command -v systemctl >/dev/null 2>&1; }; then
    cat > /etc/init.d/netbine-box <<EOF
#!/bin/sh /etc/rc.common
# Netbine box (installed by box.sh). Stopping it undoes its network changes.
START=99
STOP=10
USE_PROCD=1

start_service() {
    procd_open_instance
    procd_set_param command $BIN $ARGS
    procd_set_param respawn 3600 15 0
    procd_set_param stdout 1
    procd_set_param stderr 1
    procd_set_param term_timeout 10
    procd_close_instance
}
EOF
    chmod 755 /etc/init.d/netbine-box
    /etc/init.d/netbine-box enable
    /etc/init.d/netbine-box start
elif command -v systemctl >/dev/null 2>&1; then
    cat > /etc/systemd/system/netbine-box.service <<EOF
# Netbine box (installed by box.sh). Stopping it undoes its network changes.
[Unit]
Description=Netbine box
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=$BIN $ARGS
Restart=always
RestartSec=15
# 2: the box was removed from the account; it waits to be signed in again (box.sh).
RestartPreventExitStatus=2
TimeoutStopSec=15

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable --now netbine-box.service
else
    echo "No service manager found; start it yourself with:  $BIN $ARGS"
    exit 0
fi

echo
if [ -n "$LAN" ]; then
    echo "Netbine box is running and shares with the home network on $LAN."
    echo "Devices that use this box as their router (or get their address from it) now go through Netbine."
else
    echo "Netbine box is running."
fi
echo "Logs: $( [ "$OPENWRT" = 1 ] && echo 'logread -e netbine' || echo 'journalctl -u netbine-box -f' )"
