#! /bin/sh

set -eu

FLUX_VERSION=${FLUX_VERSION:-latest}

if [ ! -x "$(command -v curl)" ]; then
    echo "curl not found"
    exit 1
fi

if [ "$(uname -s)" = "Darwin" ]; then
  filename=fluxctl_darwin_amd64
else
  filename=fluxctl_linux_amd64
fi

tmp=$(mktemp -d /tmp/fluxcd.XXXXXX)
url="https://github.com/fluxcd/flux/releases/${FLUX_VERSION}/download/${filename}"
(
  cd "$tmp"
  echo "Downloading ${filename}..."
  curl -LO "${url}"
  echo ""
  echo "Download complete!"
)

(
  cd "$HOME"
  mkdir -p ".fluxcd/bin"
  mv "${tmp}/${filename}" ".fluxcd/bin/fluxctl"
  chmod +x ".fluxcd/bin/fluxctl"
)

rm -r "$tmp"

echo ""
echo "Add fluxctl to your path with:"
echo ""
echo "  export PATH=\$PATH:\$HOME/.fluxcd/bin"
echo ""
echo "Get started with Flux https://docs.fluxcd.io/en/stable/tutorials/get-started.html"
echo ""
