#!/bin/bash
# osmo-dit installer: curl -fsSL osmo.inc/dit/install.sh | bash
# The command line tool for Mac (signed, notarized, universal) and Linux (static, x86_64 and arm64), checked against
# the published SHA-256 list. Puts it in /usr/local/bin, or ~/.osmo/bin if that isn't writable. Run again to update.
# The app (Mac, Windows, Linux) is at osmo.inc/tools/dit.
set -euo pipefail
BASE="${OSMO_DIT_BASE:-https://osmo.inc/dit}"
o=$'\033[38;5;208m'; b=$'\033[1m'; x=$'\033[0m'
case "$(uname -s)/$(uname -m)" in
  Darwin/*) file=osmo-dit ;;
  Linux/x86_64|Linux/amd64) file=osmo-dit-linux-x86_64 ;;
  Linux/aarch64|Linux/arm64) file=osmo-dit-linux-arm64 ;;
  *) echo "osmo-dit is for macOS and Linux here. For Windows, get the app at osmo.inc/tools/dit."; exit 1 ;;
esac
t=$(mktemp -d); trap 'rm -rf "$t"' EXIT
echo "${o}${b}osmo-dit${x} installing ..."
curl -fsSL --retry 3 -o "$t/osmo-dit" "$BASE/$file"
curl -fsSL --retry 3 -o "$t/SHA256SUMS" "$BASE/SHA256SUMS"
want=$(awk -v f="$file" '$2==f{print $1}' "$t/SHA256SUMS")
if command -v shasum >/dev/null; then got=$(shasum -a 256 "$t/osmo-dit" | awk '{print $1}'); else got=$(sha256sum "$t/osmo-dit" | awk '{print $1}'); fi
[ -n "$want" ] && [ "$want" = "$got" ] || { echo "download didn't match its checksum. Try again."; exit 1; }
if [ "$(uname -s)" = Darwin ]; then
  codesign --verify --strict "$t/osmo-dit" 2>/dev/null || { echo "the download isn't signed by Osmo. Not installing."; exit 1; }
fi
chmod +x "$t/osmo-dit"
if [ -w /usr/local/bin ] || { [ ! -e /usr/local/bin ] && [ -w /usr/local ]; }; then
  mkdir -p /usr/local/bin; dest=/usr/local/bin
else
  dest="$HOME/.osmo/bin"; mkdir -p "$dest"
  case ":$PATH:" in *":$dest:"*) ;; *)
    for rc in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile"; do
      [ -f "$rc" ] || [ "$rc" = "$HOME/.zshrc" -a "$(uname -s)" = Darwin ] || continue
      grep -qs '.osmo/bin' "$rc" || printf '\nexport PATH="$HOME/.osmo/bin:$PATH"\n' >> "$rc"
    done
    echo "added ~/.osmo/bin to your PATH (open a new terminal to use it)";;
  esac
fi
mv -f "$t/osmo-dit" "$dest/osmo-dit"
echo "${o}installed${x} $("$dest/osmo-dit" version) at $dest/osmo-dit"
echo
echo "  osmo-dit offload <card> --dest <drive> --dest <drive> --project <SHOW> --roll A001"
echo "  osmo-dit            (everything else)"
