#!/bin/bash
# ClearBar installer. It's short, so please read it before running it.
# Usage: curl -fsSL https://<site>/install.sh | bash
set -euo pipefail

BASE="https://github.com/Vishrut19/clearbar-releases/releases/latest/download"
APP="/Applications/ClearBar.app"

if [ "$(id -u)" -eq 0 ]; then
  echo "Please don't run this with sudo. It installs to /Applications as you." >&2
  exit 1
fi

cat <<EOF
This script will:
  1. Download ClearBar.zip and SHA256SUMS from GitHub Releases
  2. Check the zip's SHA-256 checksum, and stop if it doesn't match
  3. Quit ClearBar if it's running
  4. Install it to $APP, replacing any old version
  5. Remove the quarantine flag and open ClearBar

EOF

# Work in a temporary folder that's deleted when the script exits.
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
cd "$tmp"

# --proto =https: refuse anything that isn't HTTPS, including redirects.
curl -fsSL --proto '=https' -o ClearBar.zip "$BASE/ClearBar.zip"
curl -fsSL --proto '=https' -o SHA256SUMS "$BASE/SHA256SUMS"

if ! grep ' ClearBar.zip$' SHA256SUMS | shasum -a 256 -c - >/dev/null; then
  echo "Checksum mismatch. Nothing was installed." >&2
  exit 1
fi
echo "Checksum OK."

ditto -x -k ClearBar.zip .

# Quit a running ClearBar and wait up to 5 seconds for it to exit.
pkill -x ClearBar || true
for _ in 1 2 3 4 5 6 7 8 9 10; do
  pgrep -x ClearBar >/dev/null || break
  sleep 0.5
done

rm -rf "$APP"
ditto ClearBar.app "$APP"

# curl doesn't add the quarantine flag, so this is just in case.
xattr -dr com.apple.quarantine "$APP" 2>/dev/null || true

open "$APP"
echo "Done. ClearBar is in your menu bar."
