#!/bin/sh
# Install the Composal CLI (com2).
#
#   curl -fsSL https://get.composal.com/install.sh | sh
#
# Environment:
#   COM2_VERSION      version to install, e.g. v0.1.0 (default: latest)
#   COM2_INSTALL_DIR  where to put com2 (default: $HOME/.local/bin)
#   COM2_BASE_URL     download host (default: https://get.composal.com)
set -eu

BASE_URL="${COM2_BASE_URL:-https://get.composal.com}"
INSTALL_DIR="${COM2_INSTALL_DIR:-$HOME/.local/bin}"
VERSION="${COM2_VERSION:-}"

say() { printf '%s\n' "$*"; }
fail() { printf 'com2 install: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

if have curl; then
  fetch() { curl -fsSL --proto '=https' --tlsv1.2 "$1"; }
  fetch_to() { curl -fsSL --proto '=https' --tlsv1.2 -o "$2" "$1"; }
elif have wget; then
  fetch() { wget -qO- "$1"; }
  fetch_to() { wget -qO "$2" "$1"; }
else
  fail "needs curl or wget"
fi

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  MINGW*|MSYS*|CYGWIN*) fail "on Windows, download com2_<version>_windows_amd64.zip from $BASE_URL/com2/" ;;
  *) fail "unsupported OS: $(uname -s)" ;;
esac

case "$(uname -m)" in
  x86_64|amd64) arch=amd64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) fail "unsupported CPU: $(uname -m)" ;;
esac

if [ -z "$VERSION" ]; then
  VERSION="$(fetch "$BASE_URL/com2/LATEST" | tr -d ' \r\n')" || fail "could not read the latest version"
fi
case "$VERSION" in v*) ;; *) VERSION="v$VERSION" ;; esac

archive="com2_${VERSION}_${os}_${arch}.tar.gz"
url="$BASE_URL/com2/$VERSION/$archive"

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT INT TERM

say "Downloading com2 $VERSION for $os/$arch"
fetch_to "$url" "$tmp/$archive" || fail "download failed: $url"
fetch_to "$BASE_URL/com2/$VERSION/SHA256SUMS" "$tmp/SHA256SUMS" || fail "could not download checksums"

expected="$(awk -v f="$archive" '$2 == f || $2 == "*"f { print $1 }' "$tmp/SHA256SUMS")"
[ -n "$expected" ] || fail "no checksum listed for $archive"
if have sha256sum; then
  actual="$(sha256sum "$tmp/$archive" | awk '{print $1}')"
elif have shasum; then
  actual="$(shasum -a 256 "$tmp/$archive" | awk '{print $1}')"
else
  fail "needs sha256sum or shasum to verify the download"
fi
[ "$expected" = "$actual" ] || fail "checksum mismatch for $archive"

tar -xzf "$tmp/$archive" -C "$tmp" com2
mkdir -p "$INSTALL_DIR"
if [ -w "$INSTALL_DIR" ]; then
  install -m 0755 "$tmp/com2" "$INSTALL_DIR/com2" 2>/dev/null || { cp "$tmp/com2" "$INSTALL_DIR/com2"; chmod 0755 "$INSTALL_DIR/com2"; }
else
  say "Installing to $INSTALL_DIR needs sudo"
  sudo install -m 0755 "$tmp/com2" "$INSTALL_DIR/com2"
fi

say "Installed com2 $VERSION to $INSTALL_DIR/com2"
case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *) say ""; say "Add it to your PATH:"; say "  export PATH=\"$INSTALL_DIR:\$PATH\"" ;;
esac
say ""
say "Next: com2 login --web"
