#!/bin/bash
# =============================================================================
# BG Remover - Beta Installer
# =============================================================================
#
# Usage (users run this one-liner from Terminal):
#   curl -fsSL https://bgremover.realbrain.cc/install-mac.sh | bash
#
# What it does:
#   1. Downloads the latest BG Remover DMG
#   2. Mounts the DMG
#   3. Copies the app to /Applications
#   4. Removes quarantine flag (bypasses "unidentified developer" warning)
#   5. Cleans up
#
# =============================================================================

set -euo pipefail

# =============================================================================
# CONFIGURATION - Update these for your setup
# =============================================================================
APP_NAME="BG Remover"
DMG_URL="https://github.com/developersharif/bgremover-app/releases/download/v4.0.1/BG_Remover-4.0.1.dmg"
DMG_NAME="BG_Remover-4.0.1.dmg"
EXPECTED_SHA256="c25754029d56330bb2531aef33a51c2939d8d35f7231e356e5e96ba6a8f45f2a"

# =============================================================================
# OUTPUT HELPERS
# =============================================================================
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

info()  { echo -e "${BLUE}==>${NC} $1"; }
ok()    { echo -e "${GREEN}==>${NC} $1"; }
warn()  { echo -e "${YELLOW}==>${NC} $1"; }
fail()  { echo -e "${RED}==>${NC} $1"; exit 1; }

# =============================================================================
# PRE-FLIGHT
# =============================================================================
echo ""
echo -e "${BOLD}========================================${NC}"
echo -e "${BOLD}  $APP_NAME - Beta Installer${NC}"
echo -e "${BOLD}========================================${NC}"
echo ""

# Check macOS
if [[ "$(uname)" != "Darwin" ]]; then
   fail "This installer is for macOS only."
fi

# Check architecture
ARCH=$(uname -m)
if [[ "$ARCH" != "arm64" ]]; then
   warn "This build is optimized for Apple Silicon (M1/M2/M3/M4)."
   warn "Your Mac is $ARCH - the app may run via Rosetta or may not work."
   echo ""
   read -rp "Continue anyway? [y/N] " REPLY
   [[ "$REPLY" =~ ^[Yy]$ ]] || exit 0
fi

# Check if already installed
if [ -d "/Applications/$APP_NAME.app" ]; then
   warn "$APP_NAME is already installed."
   read -rp "Replace existing installation? [y/N] " REPLY
   [[ "$REPLY" =~ ^[Yy]$ ]] || exit 0
fi

# =============================================================================
# STEP 1: DOWNLOAD
# =============================================================================
TMPDIR_INSTALL=$(mktemp -d)
trap 'rm -rf "$TMPDIR_INSTALL"' EXIT

DMG_PATH="$TMPDIR_INSTALL/$DMG_NAME"

info "Downloading $APP_NAME..."
if command -v curl &>/dev/null; then
   curl -fSL --progress-bar -o "$DMG_PATH" "$DMG_URL"
elif command -v wget &>/dev/null; then
   wget -q --show-progress -O "$DMG_PATH" "$DMG_URL"
else
   fail "Neither curl nor wget found. Please install one and retry."
fi

if [ ! -f "$DMG_PATH" ]; then
   fail "Download failed."
fi

DOWNLOAD_SIZE=$(du -sh "$DMG_PATH" | cut -f1)
ok "Downloaded ($DOWNLOAD_SIZE)"

# =============================================================================
# STEP 2: VERIFY INTEGRITY (if checksum is set)
# =============================================================================
if [ -n "$EXPECTED_SHA256" ]; then
   info "Verifying download integrity..."
   ACTUAL_SHA256=$(shasum -a 256 "$DMG_PATH" | awk '{print $1}')
   if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then
       fail "Checksum mismatch! The download may be corrupted or tampered with.\n    Expected: $EXPECTED_SHA256\n    Got:      $ACTUAL_SHA256"
   fi
   ok "Integrity verified (SHA-256 match)"
fi

# =============================================================================
# STEP 3: MOUNT DMG & COPY APP
# =============================================================================
info "Installing $APP_NAME..."

# Mount the DMG (suppress license agreement if any)
MOUNT_POINT=$(hdiutil attach -nobrowse -noautoopen -noverify "$DMG_PATH" 2>/dev/null | grep '/Volumes/' | awk -F'\t' '{print $NF}' | head -1)

if [ -z "$MOUNT_POINT" ] || [ ! -d "$MOUNT_POINT" ]; then
   fail "Failed to mount DMG."
fi

# Find the .app in the mounted volume
APP_SOURCE="$MOUNT_POINT/$APP_NAME.app"
if [ ! -d "$APP_SOURCE" ]; then
   hdiutil detach "$MOUNT_POINT" -quiet 2>/dev/null || true
   fail "$APP_NAME.app not found in DMG."
fi

# Remove old installation if present
if [ -d "/Applications/$APP_NAME.app" ]; then
   rm -rf "/Applications/$APP_NAME.app"
fi

# Copy to Applications
cp -R "$APP_SOURCE" "/Applications/"

# Unmount DMG
hdiutil detach "$MOUNT_POINT" -quiet 2>/dev/null || true

ok "Installed to /Applications/$APP_NAME.app"

# =============================================================================
# STEP 4: REMOVE QUARANTINE (bypass Gatekeeper for unnotarized app)
# =============================================================================
info "Removing quarantine flag..."
xattr -cr "/Applications/$APP_NAME.app" 2>/dev/null || true
ok "Quarantine removed - app will open without warnings"

# =============================================================================
# DONE
# =============================================================================
echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Installation Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "  Open from Spotlight or run:"
echo -e "  ${BLUE}open '/Applications/$APP_NAME.app'${NC}"
echo ""

# Ask to launch
read -rp "Launch $APP_NAME now? [Y/n] " REPLY
if [[ ! "$REPLY" =~ ^[Nn]$ ]]; then
   open "/Applications/$APP_NAME.app"
fi
