#!/bin/bash
# DevSweep installer
#   curl -fsSL https://devsweep.54.206.167.181.sslip.io/install.sh | bash
# Downloads the app, checks its SHA-256, installs it to /Applications and opens it.
set -euo pipefail

BASE="https://devsweep.54.206.167.181.sslip.io/downloads"
APP="DevSweep.app"

bold=$'\033[1m'; teal=$'\033[36m'; red=$'\033[31m'; dim=$'\033[2m'; off=$'\033[0m'
say()  { printf "%s▸%s %s\n" "$teal" "$off" "$1"; }
fail() { printf "%s✗ %s%s\n" "$red" "$1" "$off" >&2; exit 1; }

printf "\n%sDevSweep%s %s— free disk cleaner for Mac developers%s\n\n" "$bold" "$off" "$dim" "$off"

[[ "$(uname -s)" == "Darwin" ]] || fail "DevSweep only runs on macOS."
major=$(sw_vers -productVersion | cut -d. -f1)
(( major >= 14 )) || fail "DevSweep needs macOS 14 Sonoma or later (you have $(sw_vers -productVersion))."

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

say "Downloading DevSweep…"
curl -fL --progress-bar -o "$tmp/DevSweep.zip" "$BASE/DevSweep.zip" || fail "Download failed. Check your connection and try again."
expected=$(curl -fsSL "$BASE/DevSweep.zip.sha256" | awk '{print $1}') || fail "Couldn't fetch the checksum."

say "Verifying download…"
actual=$(shasum -a 256 "$tmp/DevSweep.zip" | awk '{print $1}')
[[ -n "$expected" && "$actual" == "$expected" ]] || fail "Checksum mismatch, the download may be corrupted. Nothing was installed."

ditto -x -k "$tmp/DevSweep.zip" "$tmp/out"
[[ -d "$tmp/out/$APP" ]] || fail "The download didn't contain $APP."

dest="/Applications"
if [[ ! -w "$dest" ]]; then
  dest="$HOME/Applications"
  mkdir -p "$dest"
fi

if pgrep -xq DevSweep; then
  say "Closing the running copy of DevSweep…"
  osascript -e 'quit app "DevSweep"' >/dev/null 2>&1 || true
  sleep 1
fi

if [[ -d "$dest/$APP" ]]; then
  say "Updating existing install in $dest…"
  rm -rf "$dest/$APP"
else
  say "Installing to $dest…"
fi
ditto "$tmp/out/$APP" "$dest/$APP"

say "Opening DevSweep…"
open "$dest/$APP"

printf "\n%s✓ DevSweep is installed.%s It's in %s and in your menu bar.\n" "$bold" "$off" "$dest"
printf "%s  Tip: grant Full Disk Access when the welcome tour asks, so it can see every cache.%s\n\n" "$dim" "$off"
