#!/bin/bash

set -x  # Enable debugging mode to print each command before executing

INSTALL_DIR="/usr/local/bin"
BINARY_NAME="go-compose-exporter"
BASE_URL="https://git.nixc.us/Nixius/go-compose-exporter/raw/branch/main/dist"

# Supported architectures
ARCHITECTURES=("linux/amd64" "linux/arm64" "linux/arm/v7" "darwin/amd64" "darwin/arm64")

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

case $ARCH in
    x86_64) ARCH="amd64" ;;
    arm64 | aarch64) ARCH="arm64" ;;
    arm*) ARCH="arm/v7" ;;
    *) echo "Unsupported architecture: $ARCH"; exit 1 ;;
esac

BINARY_URL="${BASE_URL}/${BINARY_NAME}_${OS}_${ARCH}"

echo "Downloading and installing $BINARY_NAME from $BINARY_URL..."

# Check if we have write permission to the install directory
if [ -w "${INSTALL_DIR}" ]; then
    curl -sSL --fail "$BINARY_URL" -o "${INSTALL_DIR}/${BINARY_NAME}"
    chmod +x "${INSTALL_DIR}/${BINARY_NAME}"
else
    sudo curl -sSL --fail "$BINARY_URL" -o "${INSTALL_DIR}/${BINARY_NAME}"
    sudo chmod +x "${INSTALL_DIR}/${BINARY_NAME}"
fi

# Verify the binary is executable
if [[ ! -x "${INSTALL_DIR}/${BINARY_NAME}" ]]; then
    echo "Failed to download or install the binary properly. Please check the URL or your internet connection."
    exit 1
fi

echo "Installed $BINARY_NAME to $INSTALL_DIR"

set +x  # Disable debugging mode
