#!/bin/bash
# VirtuaMesh Linux Installer
# Usage: curl -fsSL https://www.virtuamesh.com/install/linux.sh | sh
#
# 安装包自 2026-11 起托管在对象存储，地址由官网下载页数据接口
# /client/download/releases 给出（绝对 URL，与下载页卡片完全一致）。
# 旧脚本拼 /api/v1/updates/download?...&file=xxx：该接口在新布局下 404，
# 且 ARMv7 的 arch 标签（客户端上报 arm / 版本元数据里是 armv7）对不上。
set -e
BASE_URL="https://www.virtuamesh.com"
# 下载页数据接口在 API 主机上（www 只代理 /api/*）
RELEASES_URL="https://api.virtuamesh.com/client/download/releases"

echo "=== VirtuaMesh Installer ==="

ARCH=$(uname -m)
case "$ARCH" in
    x86_64)        ARCH="x64" ;;
    aarch64|arm64) ARCH="arm64" ;;
    armv7l|armv6l) ARCH="arm" ;;   # 32-bit ARM (Raspberry Pi OS 32-bit)
    *) echo "Error: Unsupported architecture: $ARCH"; exit 1 ;;
esac

# 32-bit ARM: 安装包后缀是 armhf
DEB_ARCH="$ARCH"
[ "$ARCH" = "arm" ] && DEB_ARCH="armhf"

echo "Fetching release info ..."
RELEASE=$(curl -fsSL "$RELEASES_URL")
VERSION=$(printf '%s' "$RELEASE" | grep -o '"version":"[^"]*"' | head -1 | cut -d'"' -f4)
echo "Latest version: $VERSION"

# 从下载页数据里按文件名后缀挑绝对地址（COS），拿不到再回退到更新接口
pick_url() {
    printf '%s' "$RELEASE" \
        | tr ',' '\n' \
        | grep -o '"filePath":"[^"]*"' \
        | cut -d'"' -f4 \
        | grep -E "$1" | head -1
}

fetch_ok() { curl -fsIL --max-time 30 "$1" >/dev/null 2>&1; }

TAR_FILE="virtuamesh-linux-$ARCH.tar.gz"
DEB_FILE="virtuamesh-linux-$DEB_ARCH.deb"

DEB_URL=$(pick_url "/$DEB_FILE\$" || true)
TAR_URL=$(pick_url "/$TAR_FILE\$" || true)

if [ -z "$DEB_URL" ] && [ -z "$TAR_URL" ]; then
    # 回退：更新接口给的 downloadUrl（只在它是绝对地址时可用）
    FALLBACK=$(curl -fsSL "$BASE_URL/api/v1/updates/latest?platform=linux&arch=$ARCH" \
        | grep -o '"downloadUrl":"[^"]*"' | head -1 | cut -d'"' -f4 | sed 's#\\/#/#g')
    case "$FALLBACK" in
        http*) TAR_URL="$FALLBACK" ;;
    esac
fi

if command -v dpkg >/dev/null 2>&1 && [ -n "$DEB_URL" ] && fetch_ok "$DEB_URL"; then
    echo "Downloading $DEB_FILE ..."
    curl -fsSL --retry 3 -o "/tmp/$DEB_FILE" "$DEB_URL"
    echo "Installing ..."
    sudo dpkg -i "/tmp/$DEB_FILE"
    rm -f "/tmp/$DEB_FILE"
elif [ -n "$TAR_URL" ] && fetch_ok "$TAR_URL"; then
    echo "Downloading $TAR_FILE ..."
    curl -fsSL --retry 3 -o "/tmp/$TAR_FILE" "$TAR_URL"
    echo "Installing ..."
    sudo mkdir -p /opt/virtuamesh
    sudo tar -xzf "/tmp/$TAR_FILE" -C /opt/virtuamesh
    sudo chmod +x /opt/virtuamesh/virtuamesh 2>/dev/null || true
    sudo ln -sf /opt/virtuamesh/virtuamesh /usr/local/bin/virtuamesh 2>/dev/null || true
    rm -f "/tmp/$TAR_FILE"
else
    echo "Error: no package found for linux/$ARCH (version $VERSION)" >&2
    echo "请到 https://www.virtuamesh.com/download 手动下载" >&2
    exit 1
fi

echo ""
echo "VirtuaMesh installation complete! Run 'virtuamesh' to get started."
