#!/bin/bash

set -e

# Default channel is "stable"
CHANNEL=stable

for arg in "$@"; do
    if [ "$arg" = "--staging" ]; then
        CHANNEL=staging
    fi
    if [ "$arg" = "--dev" ]; then
        CHANNEL=dev
    fi
done    

install_binary() {
    local VERSION=$(curl -s https://verity-binaries.s3.us-east-1.amazonaws.com/version-$CHANNEL)
    local ARCH=$(uname -m)
    local OS=$(uname -s | tr '[:upper:]' '[:lower:]')

    local ARCH_NAME=""
    local OS_NAME=""
    local TEMP_DIR="/tmp/verity"

    # Determine the architecture
    if [[ "$ARCH" == "x86_64" ]]; then
        ARCH_NAME="x86_64"
    elif [[ "$ARCH" == "aarch64" || "$ARCH" == "arm64" ]]; then
        ARCH_NAME="aarch64"
    else
        echo "Unsupported architecture: $ARCH"
        exit 1
    fi

    # Determine the operating system
    if [[ "$OS" == "linux" ]]; then
        OS_NAME="unknown-linux-gnu"
    elif [[ "$OS" == "darwin" ]]; then
        OS_NAME="apple-darwin"
    else
        echo "Unsupported operating system: $OS"
        exit 1
    fi
    # Set the URL for the binary
    ASSET_NAME="verity-${VERSION}-${ARCH_NAME}-${OS_NAME}.tar.gz"
    URL="https://verity-binaries.s3.us-east-1.amazonaws.com/${VERSION}/${ASSET_NAME}"

    echo "Detected platform: ${OS_NAME}-${ARCH_NAME} for ${OS} ${ARCH}"
    echo "Downloading binary from $URL..."

    mkdir -p ${TEMP_DIR}

    curl -o "${TEMP_DIR}/verity.tar.gz" $URL

    # Check if the downloaded file is a valid tar.gz archive
    if file "${TEMP_DIR}/verity.tar.gz" | grep -q 'gzip compressed data'; then
        echo "Successfully downloaded binary"
    else
        echo "Failed to download binary."
        rm -rf "${TEMP_DIR}"
        exit 1
    fi

    tar -xzf "${TEMP_DIR}/verity.tar.gz" -C "${TEMP_DIR}" "verity"

    if [[ $? -eq 0 ]]; then
        install "${TEMP_DIR}/verity" /usr/local/bin/ &&
        rm -rf "${TEMP_DIR}"

        echo "Successfully installed Verity CLI"
    else
        echo "Failed to install Verity CLI"
        exit 1
    fi
}

install_binary
