#!/bin/bash

[ -r env ] && . ./env
[ -r ../env ] && . ../env

# KCL_VERSION="0.11.2"
KCL_SOURCE="https://github.com/kcl-lang/cli/releases"
KCL_TAGS="https://github.com/kcl-lang/cli/tags"
KCL_SITE="https://kcl-lang.io"

export INSTALL_BIN_PATH=${INSTALL_BIN_PATH:-/usr/local/bin}

if [ -z "$KCL_VERSION" ] ; then 
   echo "KCL_VERSION not set in env"
   exit 1
fi
if [ "$1" == "check" ] ; then
  CHECK_ONLY="yes"
fi
OS="$(uname | tr '[:upper:]' '[:lower:]')"
ORG_OS=$(uname)
ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')"
ORG_ARCH="$(uname -m)"

has_kcl=$(type -P kcl)
num_version=0
[ -n "$has_kcl" ] && kcl_version=$(kcl -v | cut -f3 -d" " | sed 's/ //g') && num_version=${kcl_version//\./}
expected_version_num=${KCL_VERSION//\./}
[ -z "$num_version" ] && num_version=0
if [ -z "$CHECK_ONLY" ] && [ "$num_version" -lt "$expected_version_num" ] ; then
  curl -fsSLO "https://github.com/kcl-lang/cli/releases/download/v${KCL_VERSION}/kcl-v${KCL_VERSION}-${OS}-${ARCH}.tar.gz" &&
    tar -xzf "kcl-v${KCL_VERSION}-${OS}-${ARCH}.tar.gz" &&
    sudo mv kcl $INSTALL_BIN_PATH &&
    rm -f "kcl-v${KCL_VERSION}-${OS}-${ARCH}.tar.gz" &&
    printf "%s\t%s\n" "kcl" "installed $KCL_VERSION"
elif [ -n "$CHECK_ONLY" ] ; then
  printf "%s\t%s\t%s\n" "kcl" "$kcl_version" "expected $KCL_VERSION"
else
  printf "%s\t%s\n" "kcl" "already $KCL_VERSION"
fi
