#!/bin/bash

# Ensure the script is run as root
if [ "$(id -u)" -ne 0 ]; then
    echo "Please run this script as root"
    exit 1
fi

TARGET_DIR="/usr/local/bin"
# If the target directory does not exist
if [ ! -d "$TARGET_DIR" ]; then
    TARGET_DIR="/usr/bin"
fi

APP_NAME="viewturbocore"
BINARY_PATH="$TARGET_DIR/$APP_NAME"
ADDRESS="http://120.232.217.160:8888"

ARCHITECTURE=$(uname -m)

# Stop and remove existing binary if it exists
if test -e "$BINARY_PATH"; then
    "$BINARY_PATH" --stop
    rm -rf "$BINARY_PATH"
fi

# Download the appropriate binary based on system architecture using curl
if [ "$ARCHITECTURE" = "x86_64" ]; then
    curl "$ADDRESS/others/linux/ViewTurboCore-x86_64-unknown-linux-gnu" -kL >"$BINARY_PATH"
elif [ "$ARCHITECTURE" = "aarch64" ] || [ "$ARCHITECTURE" = "arm64" ]; then
    curl "$ADDRESS/others/linux/ViewTurboCore-aarch64-unknown-linux-gnu" -kL >"$BINARY_PATH"
elif [ "$ARCHITECTURE" = "armv7l" ]; then
    curl "$ADDRESS/others/linux/ViewTurboCore-arm-unknown-linux-gnueabi" -kL >"$BINARY_PATH"
elif [ "$ARCHITECTURE" = "mips" ]; then
    curl "$ADDRESS/others/linux/ViewTurboCore-linux-mips" -kL >"$BINARY_PATH"
elif [ "$ARCHITECTURE" = "mipsel" ]; then
    curl "$ADDRESS/others/linux/ViewTurboCore-linux-mipsle" -kL >"$BINARY_PATH"
elif [ "$ARCHITECTURE" = "mips64" ]; then
    curl "$ADDRESS/others/linux/ViewTurboCore-linux-mips64" -kL >"$BINARY_PATH"
elif [ "$ARCHITECTURE" = "mips64el" ]; then
    curl "$ADDRESS/others/linux/ViewTurboCore-linux-mips64le" -kL >"$BINARY_PATH"
else
    echo "The installation failed due to unsupported architecture: $ARCHITECTURE"
    exit 1
fi

if [ $? -ne 0 ]; then
    echo "Error: Failed to download the binary. Please check your network and URL."
    exit 1
fi

# Set executable permissions
chmod +x "$BINARY_PATH"

echo "Installation complete. Enter '$APP_NAME' to run the application"
