RELEASE="v2.5.9"
URL="https://github.com/argoproj/argo-cd/releases/download/${RELEASE}/argocd-linux-amd64"
DESIRED_SHA="d1168eac812d939ba29c7723f56163b824f40548"

if [[ "$(shasum $(realpath argocd-linux-amd64) | awk '{print $1}')" == "$DESIRED_SHA" ]] ; then
  echo "argocd CLI already up to date"
  exit 0
else
  echo "Downloading argocd cli tool"
  curl -sSL -o argocd-linux-amd64.new ${URL}
fi

ARGO=$(realpath argocd-linux-amd64.new)
CLI=${HOME}/monorepo/tools/bin/argocd

SHASUM=$(shasum ${ARGO} | awk '{print $1}')

if [[ "$SHASUM" == "$DESIRED_SHA" ]]; then
  echo "binary 'argocd-linux-amd64.new' matches desired sha"
  echo "  wanted: $DESIRED_SHA"
  echo "    have: $SHASUM"
  mv $ARGO ${ARGO%.*}
  ARGO=$(realpath argocd-linux-amd64)
else
  echo "binary 'argocd-linux-amd64.new' does not match desired sha"
  echo "  wanted: $DESIRED_SHA"
  echo "    have: $SHASUM"
  exit 1
fi

if test -L "$CLI"; then
  echo "Symlink exists at ${CLI}"
else
  echo "Creating symlink at ${CLI}"
  ln -s ${ARGO} ${CLI}
fi

if test -x ${ARGO} ; then
  echo "${ARGO} is already executable"
else
  echo "Marking ${ARGO} executable"
  chmod +x ${ARGO}
fi