#!/bin/sh
set -e

echo "Installing ohshell CLI..."

OS=$(uname -s)
ARCH=$(uname -m)
case "$OS" in
  Linux)   PLATFORM="linux" ;;
  Darwin)  PLATFORM="darwin" ;;
  *)       echo "Unsupported OS: $OS"; exit 1 ;;
esac

case "$ARCH" in
  x86_64) ARCH="amd64" ;;
  arm64|aarch64) ARCH="arm64" ;;
  *)      echo "Unsupported architecture: $ARCH"; exit 1 ;;
esac

OHSHELL_FILE="ohsh-${PLATFORM}-${ARCH}"
OHSHELL_URL="https://github.com/ohshell/cli/releases/latest/download/${OHSHELL_FILE}.tar.gz"
CHECKSUMS_URL="https://github.com/ohshell/cli/releases/latest/download/checksums.txt"
INSTALL_PATH="/usr/local/bin/ohsh"
TMPFILE="$(mktemp)"
TMPCHECKSUMS="$(mktemp)"

# Download binary and checksums
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "${OHSHELL_URL}" -o "${TMPFILE}"
  curl -fsSL "${CHECKSUMS_URL}" -o "${TMPCHECKSUMS}"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "${TMPFILE}" "${OHSHELL_URL}" || { echo "Download failed"; exit 1; }
  wget -qO "${TMPCHECKSUMS}" "${CHECKSUMS_URL}" || { echo "Checksum download failed"; exit 1; }
else
  echo "Error: curl or wget is required to install ohshell." >&2
  exit 1
fi

# Check for Not Found or empty file
if ! [ -s "${TMPFILE}" ]; then
  echo "Download failed or file is empty."
  exit 1
fi
if grep -q "Not Found" "${TMPFILE}"; then
  echo "Download failed: file not found at ${OHSHELL_URL}"
  exit 1
fi

# Validate checksum
EXPECTED_SUM=$(grep "${OHSHELL_FILE}" "${TMPCHECKSUMS}" | awk '{print $1}')
if [ -z "${EXPECTED_SUM}" ]; then
  echo "Could not find checksum for ${OHSHELL_FILE}"
  exit 1
fi
if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL_SUM=$(sha256sum "${TMPFILE}" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
  ACTUAL_SUM=$(shasum -a 256 "${TMPFILE}" | awk '{print $1}')
else
  echo "No SHA256 checksum tool found (sha256sum or shasum required)" >&2
  exit 1
fi
if [ "${EXPECTED_SUM}" != "${ACTUAL_SUM}" ]; then
  echo "Checksum validation failed!"
  exit 1
fi

# Extract the binary from the tar.gz
TARDIR="$(mktemp -d)"
tar -xzf "${TMPFILE}" -C "${TARDIR}"
BIN_PATH="${TARDIR}/ohsh"
chmod +x "${BIN_PATH}"

# Move to install path
if [ -w "$(dirname "${INSTALL_PATH}")" ]; then
  mv "${BIN_PATH}" "${INSTALL_PATH}"
else
  sudo mv "${BIN_PATH}" "${INSTALL_PATH}"
fi

# Clean up
rm -rf "${TARDIR}" "${TMPFILE}" "${TMPCHECKSUMS}"

echo "ohshell CLI installed at ${INSTALL_PATH}"
echo "Run 'ohsh --help' to get started."
