#!/bin/bash
# ============================================================
# Avigation Cloud — macOS Setup
#
# What this script does:
#   1. Downloads official Nextcloud 34.0.1 from nextcloud.com
#   2. Verifies SHA256 (shasum — built into macOS)
#   3. Installs with: sudo installer -pkg ... -target /
#   4. Launches Nextcloud against cloud.avigation.cloud
#
# No custom Nextcloud binary. Official Nextcloud + server address only.
# Source: support.avigation.cloud/packages/avigation/macos/Avigation-Cloud-Setup.command
# ============================================================

set -e

NC_VERSION="34.0.1"
NC_URL="https://download.nextcloud.com/desktop/releases/Mac/Installer/Nextcloud-34.0.1.pkg"
NC_SHA256="7ccc9ee2525a9080d9a67af111847eb0ec6fce540958f15fe405c359b353b804"
BRAND_URL="https://cloud.avigation.cloud"
BRAND_NAME="Avigation Cloud"
PKG_FILE="/tmp/Nextcloud-${NC_VERSION}.pkg"

# Gatekeeper note
cat <<'NOTE'

  ============================================================
  NOTE: Because this script was downloaded from the internet,
  macOS may require manual approval to run it.
  Go to: System Settings → Privacy & Security → Open Anyway
  ... if you see a "cannot be opened" message.
  ============================================================

NOTE

echo "  Avigation Cloud -- macOS Setup"
echo "  ================================"
echo "  Using official Nextcloud ${NC_VERSION} from nextcloud.com"
echo "  Server address: ${BRAND_URL}"
echo ""

# ---- 1. Download PKG ----
echo "  [1/4] Downloading Nextcloud ${NC_VERSION} (~141 MB)..."
curl -L --progress-bar --output "${PKG_FILE}" "${NC_URL}"
echo "  Download complete."

# ---- 2. Verify SHA256 ----
echo "  [2/4] Verifying SHA256..."
ACTUAL_HASH=$(shasum -a 256 "${PKG_FILE}" | awk '{print $1}')
if [ "${ACTUAL_HASH}" != "${NC_SHA256}" ]; then
    echo ""
    echo "  ERROR: SHA256 mismatch. The file may be corrupted or tampered with."
    echo "  Expected: ${NC_SHA256}"
    echo "  Actual:   ${ACTUAL_HASH}"
    rm -f "${PKG_FILE}"
    exit 1
fi
echo "  SHA256 OK."

# ---- 3. Install (requires sudo) ----
echo "  [3/4] Installing Nextcloud (sudo password may be requested)..."
sudo installer -pkg "${PKG_FILE}" -target /
rm -f "${PKG_FILE}"
echo "  Installation complete."

# ---- 4. Launch against Avigation Cloud ----
echo "  [4/4] Starting ${BRAND_NAME}..."
echo ""
echo "  Your browser will open for sign-in -- use your Avigation account."
echo ""

sleep 2

# NC 34.0.1 supports --overrideserverurl (pre-fills the server URL in the setup wizard)
open -a Nextcloud --args --overrideserverurl "${BRAND_URL}"

echo ""
echo "  ${BRAND_NAME} is ready for sign-in."
