#!/bin/bash
# Mini Producer one-line installer. Run: curl -fsSL https://miniproducer.gregspero.com/install.sh | bash
set -euo pipefail
PKG_NAME="Mini-Producer-Setup-2026.10.31-7-arm64.pkg"
PKG_URL="https://trc-campaign-media.fly.storage.tigris.dev/mini-producer/Mini-Producer-Setup-2026.10.31-7-arm64.pkg"
PKG_SHA256="10daebb68d0cbcbe4f78e8d677ebfcac92f044c5895d140f3907ca56a447042f"
PKG_BYTES=1208480407
APP="/Applications/Mini Producer.app"
DEST_DIR="${MP_DOWNLOAD_DIR:-$HOME/Downloads}"
DEST="$DEST_DIR/$PKG_NAME"

b=$'\033[1m'; g=$'\033[32m'; r=$'\033[31m'; n=$'\033[0m'
step() { printf '\n%s==> %s%s\n' "$b" "$*" "$n"; }
stop() { printf '\n%sStopped: %s%s\n' "$r" "$*" "$n" >&2; exit 1; }

step "Checking this Mac"
[ "$(uname -s)" = "Darwin" ] || stop "this installer is for a Mac."
[ "$(uname -m)" = "arm64" ] || stop "Mini Producer needs an Apple silicon Mac (M1 or newer)."
os="$(sw_vers -productVersion)"; major="${os%%.*}"; rest="${os#*.}"; minor="${rest%%.*}"; [ "$rest" = "$os" ] && minor=0
if [ "$major" -lt 26 ] || { [ "$major" -eq 26 ] && [ "$minor" -lt 2 ]; }; then
  stop "macOS $os is too old. Update to macOS 26.2 or newer in System Settings, General, Software Update."
fi
mkdir -p "$DEST_DIR"
free_kb="$(df -Pk "$DEST_DIR" | awk 'NR==2{print $4}')"
[ "$free_kb" -gt 5500000 ] || stop "free up at least 6 GB of disk space, then run this again."
if ls -d /Applications/Ableton\ Live\ 12*.app >/dev/null 2>&1; then
  echo "${g}Ableton Live 12 found.${n}"
else
  echo "Ableton Live 12 is not installed yet. Mini Producer installs anyway and its setup links you to Ableton."
fi
echo "macOS $os, $(uname -m). OK."

have_good_file() { [ -f "$DEST" ] && [ "$(shasum -a 256 "$DEST" | awk '{print $1}')" = "$PKG_SHA256" ]; }

step "Downloading Mini Producer (1.2 GB)"
if have_good_file; then
  echo "Already downloaded and checked."
else
  curl -fL --retry 5 --retry-delay 3 -C - --progress-bar -o "$DEST.part" "$PKG_URL" || \
    stop "the download did not finish. Check the internet connection and run the same line again. It picks up where it left off."
  mv -f "$DEST.part" "$DEST"
fi

step "Checking the download"
got="$(shasum -a 256 "$DEST" | awk '{print $1}')"
if [ "$got" != "$PKG_SHA256" ]; then
  rm -f "$DEST"
  stop "the file came down damaged (checksum mismatch). Run the same line again."
fi
echo "${g}Checksum matches.${n}"

step "Installing"
echo "Type your Mac login password and press Return. The letters stay hidden while you type."
if [ "${MP_NO_INSTALL:-0}" = "1" ]; then
  echo "MP_NO_INSTALL=1: stopping before the admin step (test mode)."; exit 0
fi
sudo /usr/sbin/installer -pkg "$DEST" -target / || stop "the install did not finish. Run the same line again; the download is kept."
[ -d "$APP" ] || stop "the install ran but $APP is missing."

step "Opening Mini Producer"
open "$APP" || true
printf '\n%sInstalled.%s Mini Producer setup is opening. Follow it on screen.\n' "$g" "$n"
printf 'Installer file kept at %s (you can delete it).\n' "$DEST"
