#!/bin/sh
set -u

# Downloads the OS-specific jfcm binary from releases.jfrog.io

CLI_OS="na"
IDENTIFIER="v1"
VERSION="[RELEASE]"
FILE_NAME="jfcm"

if [ $# -eq 1 ]; then
    VERSION=$1
    echo "Downloading version $VERSION of jfcm..."
else
    echo "Resolving latest version of jfcm..."
    VERSION=$(curl -fSL "https://releases.jfrog.io/artifactory/api/storage/jfcm/${IDENTIFIER}/" 2>/dev/null \
        | grep '"uri" : "/' \
        | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' \
        | sort -t. -k1,1n -k2,2n -k3,3n \
        | tail -1)
    if [ -z "$VERSION" ]; then
        echo "Error: Could not resolve latest version. Please specify a version explicitly: sh getCli.sh <version>"
        exit 1
    fi
    echo "Downloading version $VERSION of jfcm..."
fi

if uname -s | grep -q -E -i "(cygwin|mingw|msys|windows)"; then
    CLI_OS="windows"
    ARCH="amd64"
    FILE_NAME="${FILE_NAME}.exe"
elif uname -s | grep -q -i "darwin"; then
    CLI_OS="mac"
    if [ "$(uname -m)" = "arm64" ]; then
        ARCH="arm64"
    else
        ARCH="386"
    fi
else
    CLI_OS="linux"
    MACHINE_TYPE="$(uname -m)"
    case $MACHINE_TYPE in
        i386 | i486 | i586 | i686 | i786 | x86)
            ARCH="386" ;;
        amd64 | x86_64 | x64)
            ARCH="amd64" ;;
        arm | armv7l)
            ARCH="arm" ;;
        aarch64)
            ARCH="arm64" ;;
        s390x)
            ARCH="s390x" ;;
        ppc64)
            ARCH="ppc64" ;;
        ppc64le)
            ARCH="ppc64le" ;;
        *)
            echo "Unknown machine type: $MACHINE_TYPE"
            exit 1 ;;
    esac
fi

URL="https://releases.jfrog.io/artifactory/jfcm/${IDENTIFIER}/${VERSION}/jfcm-${CLI_OS}-${ARCH}/${FILE_NAME}"
echo "Downloading from: $URL"
curl -fSLg "$URL" -o "$FILE_NAME" || { echo "Error: Failed to download jfcm from $URL"; rm -f "$FILE_NAME"; exit 1; }
chmod +x "$FILE_NAME"
