#!/bin/sh

set -e

DOWNLOAD_URL_PRE="https://fw0.koolcenter.com/binary/fastnet"
ARCH=$(uname -m)
case "$ARCH" in
    "x86_64")
        DOWNLOAD_URL=${DOWNLOAD_URL_PRE}"/FastNet.amd64"
        ;;
    "aarch64")
        DOWNLOAD_URL=${DOWNLOAD_URL_PRE}"/FastNet.arm64"
        ;;
    "armv7l")
        DOWNLOAD_URL=${DOWNLOAD_URL_PRE}"/FastNet.armv7"
        ;;
    *)
        echo "Unsupported architecture: $ARCH"
        exit 1
        ;;
esac

MAX_CACHE_MINS=10
if [ -d "/tmp" ]; then
  TEMP_DIR="/tmp"
else
  TEMP_DIR=$(mktemp -d 2>/dev/null || mktemp -d -t 'fastnet')
fi
CACHE_FILE="$TEMP_DIR/FastNet"
#CACHE_FILE="./FastNet"

cleanup() {
    rm -f "/tmp/fastnet-install.sh"
}
trap cleanup EXIT

check_local_version() {
    local binary_path=$1
    if [ ! -f "$binary_path" ]; then
        return 1
    fi

    echo "Binary exists: $binary_path"
    local last_modified=$(stat -c %Y "$binary_path" 2>/dev/null)
    local current_time=$(date +%s)
    local time_diff=$(( (current_time - last_modified) / 60 ))

    if [ $time_diff -ge $MAX_CACHE_MINS ]; then
        return 1
    fi

    if "$binary_path" version &>/dev/null; then
        return 0
    else
        return 1
    fi
}

if check_local_version "$CACHE_FILE"; then
    "$CACHE_FILE" version
else
    if type curl >/dev/null 2>&1; then
        echo "Download using curl"
        curl -L -o "$CACHE_FILE" "$DOWNLOAD_URL"
    elif type wget >/dev/null 2>&1; then
        echo "Download using wget"
        wget -O "$CACHE_FILE" "$DOWNLOAD_URL"
    else
        echo "Cannot download"
        exit 1
    fi

    chmod +x "$CACHE_FILE"
fi

"$CACHE_FILE"
