#!/bin/sh
# envo installer — version 0.9.1
set -e

OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
  Darwin) PLATFORM="darwin" ;;
  Linux) PLATFORM="linux" ;;
  *) echo "envo: unsupported OS: $OS (supported: macOS, Linux)" >&2; exit 1 ;;
esac

case "$ARCH" in
  arm64|aarch64) TARGET="$PLATFORM-arm64" ;;
  x86_64|amd64) TARGET="$PLATFORM-x64" ;;
  *) echo "envo: unsupported architecture: $ARCH" >&2; exit 1 ;;
esac

if [ "$TARGET" = "darwin-x64" ]; then
  echo "envo: darwin-x64 build not published yet; use an Apple Silicon Mac or Linux" >&2
  exit 1
fi

URL="https://tj5cc1aywcknxvx1.public.blob.vercel-storage.com/cli/v0.9.1/envo-$TARGET"
case "$TARGET" in
  darwin-arm64) EXPECTED_SHA="4e29ee3bf0562fa49aff7cf71e04621c041e997df5eb3a6b4dca191395b414cd" ;;
  linux-arm64) EXPECTED_SHA="fc3673873b71af8b5450be919e0599cf03cf6e4fe44692d016db2f2e19b6bc10" ;;
  linux-x64) EXPECTED_SHA="b6a2db0d19d3d9759051df25433be9489494981ca6046c3b9df1c5426a11461c" ;;
  *) EXPECTED_SHA="" ;;
esac
INSTALL_DIR="${ENVO_INSTALL_DIR:-/usr/local/bin}"
[ -n "${ENVO_INSTALL_DIR:-}" ] && mkdir -p "$INSTALL_DIR" 2>/dev/null
if [ ! -w "$INSTALL_DIR" ]; then
  INSTALL_DIR="$HOME/.local/bin"
  mkdir -p "$INSTALL_DIR"
fi

echo "Downloading envo ($TARGET)..."
curl -fSL --progress-bar "$URL" -o "$INSTALL_DIR/envo.download"

if [ -n "$EXPECTED_SHA" ]; then
  if command -v sha256sum >/dev/null 2>&1; then
    ACTUAL_SHA="$(sha256sum "$INSTALL_DIR/envo.download" | cut -d' ' -f1)"
  elif command -v shasum >/dev/null 2>&1; then
    ACTUAL_SHA="$(shasum -a 256 "$INSTALL_DIR/envo.download" | cut -d' ' -f1)"
  else
    ACTUAL_SHA=""
  fi
  if [ -n "$ACTUAL_SHA" ] && [ "$ACTUAL_SHA" != "$EXPECTED_SHA" ]; then
    echo "envo: checksum mismatch (expected $EXPECTED_SHA, got $ACTUAL_SHA) — aborting" >&2
    rm -f "$INSTALL_DIR/envo.download"
    exit 1
  fi
  [ -n "$ACTUAL_SHA" ] && echo "Checksum verified."
fi

mv "$INSTALL_DIR/envo.download" "$INSTALL_DIR/envo"
chmod +x "$INSTALL_DIR/envo"

echo ""
echo "envo installed to $INSTALL_DIR/envo"
case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *) echo "Add it to your PATH:  export PATH=\"$INSTALL_DIR:\$PATH\"" ;;
esac
echo ""
echo "Get started:"
echo "  envo login             # opens your browser to pair this machine"
echo "  envo up <project>/<environment>"
