#!/bin/sh
set -eu
umask 077
server="${1:-https://mcp.penrouz.com}"
case "$server" in https://*) ;; *) echo 'The download server must use HTTPS.' >&2; exit 1 ;; esac
server="${server%/}"
case "$(uname -s)-$(uname -m)" in
  Darwin-x86_64) file="MCPENROUZ-0.5.18-r1-macos-x64.zip"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-macos-x64.zip"; expected="d603463819ddcac1ccbb48af279866277c36d742bfe62c7592ad6c89d36b602f" ;;
  Darwin-amd64) file="MCPENROUZ-0.5.18-r1-macos-x64.zip"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-macos-x64.zip"; expected="d603463819ddcac1ccbb48af279866277c36d742bfe62c7592ad6c89d36b602f" ;;
  Darwin-arm64) file="MCPENROUZ-0.5.18-r1-macos-arm64.zip"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-macos-arm64.zip"; expected="e6ecb2fe905a30144985eebf6713ce64bb7f474e1a37f5a17910e64b21dc83f8" ;;
  Darwin-aarch64) file="MCPENROUZ-0.5.18-r1-macos-arm64.zip"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-macos-arm64.zip"; expected="e6ecb2fe905a30144985eebf6713ce64bb7f474e1a37f5a17910e64b21dc83f8" ;;
  Linux-x86_64) file="MCPENROUZ-0.5.18-r1-linux-x64.sh"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-linux-x64.sh"; expected="052ac98383ffb7d8bfa002f88ee920d3637d8760cae9a99774ade61b56fe5748" ;;
  Linux-amd64) file="MCPENROUZ-0.5.18-r1-linux-x64.sh"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-linux-x64.sh"; expected="052ac98383ffb7d8bfa002f88ee920d3637d8760cae9a99774ade61b56fe5748" ;;
  Linux-arm64) file="MCPENROUZ-0.5.18-r1-linux-arm64.sh"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-linux-arm64.sh"; expected="ff7c4afeed27fe5eb5ba5cf49a9435c3551a319020be77f3e6b9ef7bb1453f85" ;;
  Linux-aarch64) file="MCPENROUZ-0.5.18-r1-linux-arm64.sh"; route="/downloads/releases/0.5.18/MCPENROUZ-0.5.18-r1-linux-arm64.sh"; expected="ff7c4afeed27fe5eb5ba5cf49a9435c3551a319020be77f3e6b9ef7bb1453f85" ;;
  *) echo 'This OS or CPU is not supported by the current installer. See https://mcp.penrouz.com/setup' >&2; exit 1 ;;
esac
task_dir=$(mktemp -d "${TMPDIR:-/tmp}/mcpenrouz-download.XXXXXXXX")
trap 'rm -rf "$task_dir"' EXIT HUP INT TERM
if command -v curl >/dev/null 2>&1; then curl --fail --location --proto '=https' --tlsv1.2 "$server$route" -o "$task_dir/$file"; elif command -v wget >/dev/null 2>&1; then wget -O "$task_dir/$file" "$server$route"; else echo 'curl or wget is required to download the installer.' >&2; exit 1; fi
if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum "$task_dir/$file" | awk '{print $1}'); elif command -v shasum >/dev/null 2>&1; then actual=$(shasum -a 256 "$task_dir/$file" | awk '{print $1}'); else echo 'SHA-256 utility is required.' >&2; exit 1; fi
[ "$actual" = "$expected" ] || { echo 'Installer checksum verification failed.' >&2; exit 1; }
case "$file" in
  *.zip) unzip -q "$task_dir/$file" -d "$task_dir/unpacked"; sh "$task_dir/unpacked/MCPENROUZ/Install MCPENROUZ.command" ;;
  *.sh) sh "$task_dir/$file" ;;
esac
