#!/bin/sh
# Installs vlessio-rs, the VLESS.io terminal client.
#
#   curl -fsSL https://download.vless.io/vlessio-rs/install.sh | sh
#
# Environment:
#   VLESSIO_VERSION      Install this version (e.g. 0.2.0) instead of the latest.
#   VLESSIO_INSTALL_DIR  Install here instead of /usr/local/bin (or ~/.local/bin
#                        when /usr/local/bin is not writable and sudo is absent).
#   VLESSIO_STATIC=1     Use the static (musl) Linux build. Chosen automatically
#                        on musl systems such as Alpine.
#   VLESSIO_DOWNLOAD_BASE  Download origin. For mirrors and for testing.
#
# POSIX sh on purpose: it runs under dash, busybox ash and macOS /bin/sh, and
# needs only curl or wget plus a SHA-256 tool. The whole script is one function
# called on its last line, so a download cut off part-way runs nothing.

set -eu

BINARY=vlessio-rs

say() { printf '%s\n' "$*"; }
fail() {
    printf 'error: %s\n' "$*" >&2
    exit 1
}

have() { command -v "$1" >/dev/null 2>&1; }

# fetch <url> <destination file>
fetch() {
    if have curl; then
        curl -fsSL --proto '=https,file' -o "$2" "$1"
    elif have wget; then
        wget -q -O "$2" "$1"
    else
        fail "curl or wget is required"
    fi
}

sha256_of() {
    if have sha256sum; then
        sha256sum "$1" | cut -d ' ' -f 1
    elif have shasum; then
        shasum -a 256 "$1" | cut -d ' ' -f 1
    else
        fail "sha256sum or shasum is required to verify the download"
    fi
}

detect_asset() {
    case "$(uname -s)" in
        Linux) os=linux ;;
        Darwin) os=macos ;;
        *) fail "unsupported operating system: $(uname -s)" ;;
    esac
    case "$(uname -m)" in
        x86_64 | amd64) arch=x64 ;;
        aarch64 | arm64) arch=arm64 ;;
        *) fail "unsupported architecture: $(uname -m)" ;;
    esac
    variant=
    if [ "$os" = linux ]; then
        # The default build links glibc. musl systems need the static one.
        if [ "${VLESSIO_STATIC:-0}" = 1 ] || (ldd --version 2>&1 || true) | grep -qi musl; then
            variant=-static
        fi
    fi
    say "$BINARY-$os-$arch$variant"
}

# A release tag is used to build a URL, so only the two shapes the release
# pipeline produces are accepted.
valid_tag() {
    case "$1" in
        *[!A-Za-z0-9.-]* | '') return 1 ;;
        rust-cli-v[0-9]* | v[0-9]*) return 0 ;;
        *) return 1 ;;
    esac
}

choose_install_dir() {
    if [ -n "${VLESSIO_INSTALL_DIR:-}" ]; then
        say "$VLESSIO_INSTALL_DIR"
    elif [ "$(id -u)" = 0 ] || [ -w /usr/local/bin ] || have sudo; then
        say /usr/local/bin
    else
        say "$HOME/.local/bin"
    fi
}

# install_file <source> <directory>: as the current user where possible, with
# sudo only when the directory needs it.
install_file() {
    if mkdir -p "$2" 2>/dev/null && [ -w "$2" ]; then
        install -m 0755 "$1" "$2/$BINARY"
    elif have sudo; then
        say "Installing to $2 needs administrator rights."
        sudo mkdir -p "$2"
        sudo install -m 0755 "$1" "$2/$BINARY"
    else
        fail "cannot write to $2; set VLESSIO_INSTALL_DIR to a directory you own"
    fi
}

main() {
    base="${VLESSIO_DOWNLOAD_BASE:-https://download.vless.io}"
    asset="$(detect_asset)"

    work="$(mktemp -d)"
    trap 'rm -rf "$work"' EXIT INT TERM

    if [ -n "${VLESSIO_VERSION:-}" ]; then
        tag="rust-cli-v${VLESSIO_VERSION#v}"
    else
        fetch "$base/vlessio-rs/latest.txt" "$work/latest" ||
            fail "could not find the latest release at $base"
        tag="$(head -n 1 "$work/latest" | tr -d '[:space:]')"
    fi
    valid_tag "$tag" || fail "unexpected release name '$tag'"

    release="$base/$tag/rust-cli"
    fetch "$release/SHA256SUMS" "$work/sums" ||
        fail "release $tag has no checksum list; it may predate this installer"
    expected="$(awk -v name="$asset" '$2 == name { print $1 }' "$work/sums")"
    [ -n "$expected" ] || fail "release $tag has no build for this system ($asset)"

    say "Downloading $asset ($tag)..."
    fetch "$release/$asset" "$work/$BINARY" || fail "download failed"
    actual="$(sha256_of "$work/$BINARY")"
    [ "$actual" = "$expected" ] ||
        fail "checksum mismatch for $asset (expected $expected, got $actual)"

    directory="$(choose_install_dir)"
    install_file "$work/$BINARY" "$directory"

    installed="$("$directory/$BINARY" --version 2>/dev/null)" ||
        fail "$directory/$BINARY was installed but does not run on this system"
    say ""
    say "Installed $installed to $directory/$BINARY"
    case ":$PATH:" in
        *":$directory:"*) ;;
        *) say "Note: $directory is not on your PATH. Add it, or run the full path." ;;
    esac
    say ""
    say "Get started:"
    say "  $BINARY login          sign this device in"
    say "  $BINARY connect        SOCKS5 proxy on 127.0.0.1:1080"
    say "  sudo $BINARY connect -t   system-wide tunnel"
    say "  $BINARY tui            interactive interface"
    say "  $BINARY --help         everything else"
}

main "$@"
