#!/usr/bin/env bash
# =============================================================================
#  install.sh — MMBARS 1-Liner Quick Installer for macOS
# =============================================================================
#  Usage:
#    curl -fsSL https://mmbars.remarkablepc.com/install.sh | bash
# =============================================================================

set -e

BOLD="\033[1m"
CYN="\033[1;36m"
GRN="\033[1;32m"
YEL="\033[1;33m"
RED="\033[1;31m"
RST="\033[0m"

DEPLOY_ROOT="/Users/Shared/Tools/MMBARS"
ZIP_URLS=(
  "https://macpc.remarkablepc.com/mmbars/MMBARS.zip"
  "https://mmbars.remarkablepc.com/MMBARS.zip"
)
TMP_ZIP="/tmp/MMBARS_installer.zip"
TMP_DIR="/tmp/mmbars_extracted"

echo -e "${CYN}${BOLD}=============================================================================${RST}"
echo -e "  ${BOLD}💾 MMBARS — Mac Backup Assistance & Recovery Suite${RST}"
echo -e "  Autonomous macOS Scam Sentry, RAT Watchdog & Diagnostic Suite"
echo -e "  Shop Brand: ${BOLD}MacPCMarket${RST} (423-339-5579 — Call or Text)"
echo -e "${CYN}${BOLD}=============================================================================${RST}"
echo ""

echo -e "  ${CYN}▶ [1/5] Downloading MMBARS Universal2 distribution...${RST}"
downloaded=false
for url in "${ZIP_URLS[@]}"; do
  if curl --resolve macpc.remarkablepc.com:443:213.109.149.181 --resolve mmbars.remarkablepc.com:443:213.109.149.181 -fsSL --connect-timeout 10 -o "$TMP_ZIP" "$url" 2>/dev/null; then
    downloaded=true
    echo -e "    ${GRN}✓ Downloaded successfully from:${RST} ${url}"
    break
  fi
done

if [[ "$downloaded" != "true" ]]; then
  echo -e "  ${RED}✗ Failed to download MMBARS package from mirrors.${RST}"
  exit 1
fi

echo -e "  ${CYN}▶ [2/5] Staging payload into ${DEPLOY_ROOT}...${RST}"
rm -rf "$TMP_DIR"
mkdir -p "$TMP_DIR"
if command -v ditto >/dev/null 2>&1; then
  ditto -x -k "$TMP_ZIP" "$TMP_DIR"
else
  unzip -q -o "$TMP_ZIP" -d "$TMP_DIR" || true
fi

mkdir -p "$DEPLOY_ROOT"
cp -rf "$TMP_DIR"/* "$DEPLOY_ROOT"/ 2>/dev/null || true
rm -rf "$TMP_DIR" "$TMP_ZIP"

echo -e "  ${CYN}▶ [3/5] Setting executable permissions & clearing quarantine...${RST}"
chmod +x "${DEPLOY_ROOT}/bin/"* 2>/dev/null || true
chmod +x "${DEPLOY_ROOT}/"*.command 2>/dev/null || true
xattr -dr com.apple.quarantine "$DEPLOY_ROOT" 2>/dev/null || true

echo -e "  ${CYN}▶ [4/5] Arming background ScamBuster & RAT sentry...${RST}"
if [[ -x "${DEPLOY_ROOT}/bin/mmbars" ]]; then
  "${DEPLOY_ROOT}/bin/mmbars" --autostart enable >/dev/null 2>&1 || true
elif [[ -x "${DEPLOY_ROOT}/bin/mmbars.sh" ]]; then
  /bin/bash "${DEPLOY_ROOT}/bin/mmbars.sh" --install >/dev/null 2>&1 || true
fi

# Register Quick Action Service & Emergency Hotkey
SERVICE_NAME="MMBARS Panic Defuser"
SERVICE_WORKFLOW="${HOME}/Library/Services/${SERVICE_NAME}.workflow"
mkdir -p "${SERVICE_WORKFLOW}/Contents" 2>/dev/null || true

cat <<'EOF' > "${SERVICE_WORKFLOW}/Contents/Info.plist"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSIconPath</key>
    <string>AutomatorApplet.icns</string>
    <key>NSServices</key>
    <array>
        <dict>
            <key>NSBackgroundColorName</key>
            <string>background</string>
            <key>NSBackgroundStrokeColorName</key>
            <string>line</string>
            <key>NSIconName</key>
            <string>AutomatorApplet</string>
            <key>NSMenuItem</key>
            <dict>
                <key>default</key>
                <string>MMBARS Panic Defuser</string>
            </dict>
            <key>NSMessage</key>
            <string>runWorkflowAsService</string>
            <key>NSReturnTypes</key>
            <array/>
            <key>NSSendTypes</key>
            <array/>
        </dict>
    </array>
</dict>
</plist>
EOF

cat <<'EOF' > "${SERVICE_WORKFLOW}/Contents/document.wflow"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>AMApplicationBuild</key>
    <string>521.1</string>
    <key>AMApplicationVersion</key>
    <string>2.10</string>
    <key>AMDocumentVersion</key>
    <string>2</string>
    <key>actions</key>
    <array>
        <dict>
            <key>action</key>
            <dict>
                <key>AMAccepts</key>
                <dict>
                    <key>Container</key>
                    <string>List</string>
                    <key>Types</key>
                    <array>
                        <string>com.apple.cocoa.string</string>
                    </array>
                </dict>
                <key>AMActionVersion</key>
                <string>2.0.3</string>
                <key>AMApplication</key>
                <array>
                    <string>Automator</string>
                </array>
                <key>AMCategory</key>
                <string>AMCategoryUtilities</string>
                <key>ActionBundlePath</key>
                <string>/System/Library/Automator/Run Shell Script.action</string>
                <key>ActionName</key>
                <string>Run Shell Script</string>
                <key>ActionParameters</key>
                <dict>
                    <key>COMMAND_STRING</key>
                    <string>if [[ -x /Users/Shared/Tools/MMBARS/bin/mmbars ]]; then /Users/Shared/Tools/MMBARS/bin/mmbars --panic; else /bin/bash /Users/Shared/Tools/MMBARS/bin/mmscambuster.sh --panic; fi</string>
                    <key>CheckedForUserDefaultShell</key>
                    <true/>
                    <key>inputMethod</key>
                    <integer>0</integer>
                    <key>shell</key>
                    <string>/bin/bash</string>
                    <key>source</key>
                    <string></string>
                </dict>
                <key>BundleIdentifier</key>
                <string>com.apple.RunShellScript</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>
EOF

defaults write pbs NSServicesStatus -dict-add "(null) - ${SERVICE_NAME} - runWorkflowAsService" '{ "key_equivalent" = "@^b"; }' 2>/dev/null || true
defaults write pbs NSServicesStatus -dict-add "com.apple.Automator.${SERVICE_NAME} - runWorkflowAsService" '{ "key_equivalent" = "@^b"; }' 2>/dev/null || true
/System/Library/CoreServices/pbs -flush 2>/dev/null || true

# Transmit initial check-in diagnostic beacon (WINFleet bridge)
if [[ -x "${DEPLOY_ROOT}/bin/mmtelemetry" && -f "${DEPLOY_ROOT}/config/brand.json" ]]; then
  "${DEPLOY_ROOT}/bin/mmtelemetry" -config "${DEPLOY_ROOT}/config/brand.json" -event "InstallCheckIn" -alert "MMBARS Initial Check-In from Mac" >/dev/null 2>&1 || true
fi

# Create Desktop Emergency Defusal Button
DESKTOP_BTN="${HOME}/Desktop/Emergency-Defusal.command"
cat <<'EOF' > "$DESKTOP_BTN"
#!/usr/bin/env bash
if [[ -x "/Users/Shared/Tools/MMBARS/bin/mmbars" ]]; then
  exec "/Users/Shared/Tools/MMBARS/bin/mmbars" --panic
else
  exec /bin/bash "/Users/Shared/Tools/MMBARS/bin/mmscambuster.sh" --panic
fi
EOF
chmod 755 "$DESKTOP_BTN"

# Create Desktop Educational Demo Button
DESKTOP_DEMO="${HOME}/Desktop/MMBARS-Demo.command"
cat <<'EOF' > "$DESKTOP_DEMO"
#!/usr/bin/env bash
DEMO="/Users/Shared/Tools/MMBARS/demo/scambuster-demo.html"
if [[ -f "$DEMO" ]]; then
  open "$DEMO"
fi
EOF
chmod 755 "$DESKTOP_DEMO"

echo -e "  ${CYN}▶ [5/5] Installation verified successfully!${RST}"
echo ""
echo -e "  ${GRN}✓ MMBARS is now active and protecting this Mac.${RST}"
echo -e "    • Installation Root : ${BOLD}${DEPLOY_ROOT}${RST}"
echo -e "    • Emergency Hotkey  : ${BOLD}Control + Command + B${RST}"
echo -e "    • Emergency Button  : ${BOLD}${DESKTOP_BTN}${RST}"
echo -e "    • Educational Demo  : ${BOLD}${DESKTOP_DEMO}${RST}"
echo -e "    • Support Hotline   : ${BOLD}MacPCMarket (423-339-5579)${RST}"
echo ""
echo -e "${CYN}${BOLD}=============================================================================${RST}"
