#!/bin/bash
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#   OrganicAI — macOS Force-Install (Enterprise Policy)
#   Installs the extension via Chrome's ExtensionInstallForcelist policy.
#   The user gets ONE sudo password prompt, then the extension installs
#   silently in Chrome on next launch and cannot be disabled by the user.
#
#   Behind the scenes:
#     - Writes to /Library/Managed Preferences/com.google.Chrome.plist
#     - Adds our extension to the ExtensionInstallForcelist array
#     - Flushes cfprefsd cache so Chrome sees the change immediately
#     - Opens chrome://extensions
#
#   To uninstall: run this script with the -u flag
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

set -e

EXTENSION_ID="dlgmbhohnfahmjdfjghdhhnfpocggoah"
UPDATE_URL="https://organicai-web.pages.dev/update.xml"
POLICY_FILE="/Library/Managed Preferences/com.google.Chrome.plist"
POLICY_VALUE="${EXTENSION_ID};${UPDATE_URL}"

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

UNINSTALL=0
if [ "$1" = "-u" ] || [ "$1" = "--uninstall" ]; then UNINSTALL=1; fi

clear
echo ""
echo -e "${CYAN}  ╔════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}  ║                                                    ║${NC}"
echo -e "${CYAN}  ║       OrganicAI — Force-Install (macOS)            ║${NC}"
echo -e "${CYAN}  ║       התקנה אוטומטית דרך מדיניות Chrome             ║${NC}"
echo -e "${CYAN}  ║                                                    ║${NC}"
echo -e "${CYAN}  ╚════════════════════════════════════════════════════╝${NC}"
echo ""

# ─── Uninstall branch ─────────────────────────────────────────
if [ $UNINSTALL -eq 1 ]; then
  echo -e "  ${YELLOW}🗑  מסיר את התוסף...${NC}"
  echo ""
  echo "  Sudo password required to modify managed preferences:"

  # Remove the extension entry from ExtensionInstallForcelist
  # If the array becomes empty, delete the key entirely
  if [ -f "$POLICY_FILE" ]; then
    # Read current array, filter out our entry, write back
    sudo /usr/libexec/PlistBuddy -c "Print :ExtensionInstallForcelist" "$POLICY_FILE" 2>/dev/null | grep -v "$EXTENSION_ID" > /tmp/organicai-policy-tmp || true

    # Remove our specific entry. If no more entries left, delete the key.
    sudo /usr/libexec/PlistBuddy -c "Delete :ExtensionInstallForcelist" "$POLICY_FILE" 2>/dev/null || true

    # Rebuild the array from filtered lines (skip array boundaries)
    REMAINING=$(grep -v "Array" /tmp/organicai-policy-tmp | grep -v "^{" | grep -v "^}" | grep -v "^$" || true)
    if [ -n "$REMAINING" ]; then
      sudo /usr/libexec/PlistBuddy -c "Add :ExtensionInstallForcelist array" "$POLICY_FILE"
      echo "$REMAINING" | while read line; do
        clean=$(echo "$line" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
        if [ -n "$clean" ]; then
          sudo /usr/libexec/PlistBuddy -c "Add :ExtensionInstallForcelist: string $clean" "$POLICY_FILE"
        fi
      done
    fi
    rm -f /tmp/organicai-policy-tmp

    # Flush prefs cache
    sudo killall cfprefsd 2>/dev/null || true
    echo -e "       ${GREEN}✓ ערך הוסר מהמדיניות${NC}"
  else
    echo -e "       ${YELLOW}⚠ אין קובץ מדיניות — התוסף לא היה מותקן בכפייה${NC}"
  fi

  echo ""
  echo -e "  ${GREEN}✅ התוסף יוסר מ-Chrome בפתיחה הבאה של הדפדפן.${NC}"
  echo "     סגור את כל חלונות Chrome ופתח אותו מחדש."
  echo ""
  read -n 1 -s -r -p "  Press any key to close..."
  echo ""
  exit 0
fi

# ─── Install branch ───────────────────────────────────────────
echo -e "  ${BOLD}1/4  בודק שהדפדפן Chrome מותקן...${NC}"
CHROME_FOUND=0
for path in \
  "/Applications/Google Chrome.app" \
  "/Applications/Google Chrome Beta.app" \
  "/Applications/Google Chrome Canary.app" \
  "/Applications/Chromium.app"; do
  if [ -d "$path" ]; then
    CHROME_FOUND=1
    CHROME_APP="$path"
    break
  fi
done

if [ $CHROME_FOUND -eq 0 ]; then
  echo -e "       ${YELLOW}⚠ Chrome לא נמצא — ההתקנה תתבצע, אבל תצטרך להתקין Chrome${NC}"
else
  echo -e "       ${GREEN}✓ נמצא: ${CHROME_APP}${NC}"
fi
echo ""

# ─── Sudo prompt ──────────────────────────────────────────────
echo -e "  ${BOLD}2/4  דרושה הרשאת מנהל לכתיבה ל-Managed Preferences...${NC}"
echo "       הסיסמה שלך תוצרך פעם אחת בלבד."
echo ""

# This is the sudo trigger — will prompt for password
sudo -v
if [ $? -ne 0 ]; then
  echo -e "  ${RED}❌ סירוב הרשאה — לא ניתן להמשיך${NC}"
  exit 1
fi
echo -e "       ${GREEN}✓ הרשאה ניתנה${NC}"
echo ""

# ─── Write policy ─────────────────────────────────────────────
echo -e "  ${BOLD}3/4  כותב מדיניות התקנה...${NC}"
echo "       מיקום: $POLICY_FILE"

# Ensure the Managed Preferences folder exists
sudo mkdir -p "/Library/Managed Preferences"

# Check if our value is already in the list — if so, skip
if [ -f "$POLICY_FILE" ]; then
  EXISTING=$(sudo /usr/libexec/PlistBuddy -c "Print :ExtensionInstallForcelist" "$POLICY_FILE" 2>/dev/null | grep "$EXTENSION_ID" || true)
  if [ -n "$EXISTING" ]; then
    echo -e "       ${YELLOW}⚠ כבר רשום — מדלג${NC}"
    echo ""
  else
    # Append to existing array
    sudo /usr/libexec/PlistBuddy -c "Add :ExtensionInstallForcelist: string $POLICY_VALUE" "$POLICY_FILE"
    echo -e "       ${GREEN}✓ נוסף לרשימה הקיימת${NC}"
    echo ""
  fi
else
  # Create the file with our entry
  sudo /usr/libexec/PlistBuddy -c "Add :ExtensionInstallForcelist array" "$POLICY_FILE"
  sudo /usr/libexec/PlistBuddy -c "Add :ExtensionInstallForcelist: string $POLICY_VALUE" "$POLICY_FILE"
  echo -e "       ${GREEN}✓ קובץ מדיניות נוצר${NC}"
  echo ""
fi

# Flush the prefs cache so Chrome sees the change on next launch
sudo killall cfprefsd 2>/dev/null || true

# ─── Open Chrome ──────────────────────────────────────────────
echo -e "  ${BOLD}4/4  פותח את Chrome...${NC}"
if [ $CHROME_FOUND -eq 1 ]; then
  open -a "$CHROME_APP" "chrome://extensions/"
  echo -e "       ${GREEN}✓ Chrome נפתח${NC}"
else
  echo -e "       ${YELLOW}⚠ פתח את Chrome כשתתקין אותו${NC}"
fi
echo ""

echo -e "${GREEN}  ╔════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}  ║                                                    ║${NC}"
echo -e "${GREEN}  ║   ✅  הותקן בהצלחה!                                ║${NC}"
echo -e "${GREEN}  ║                                                    ║${NC}"
echo -e "${GREEN}  ║   חשוב: כדי שהתוסף ייטען —                        ║${NC}"
echo -e "${GREEN}  ║   ① סגור את כל חלונות Chrome (Cmd+Q)                ║${NC}"
echo -e "${GREEN}  ║   ② פתח את Chrome מחדש                             ║${NC}"
echo -e "${GREEN}  ║                                                    ║${NC}"
echo -e "${GREEN}  ║   התוסף יותקן בשקט — תראה אותו ב:                  ║${NC}"
echo -e "${GREEN}  ║   chrome://extensions/                             ║${NC}"
echo -e "${GREEN}  ║                                                    ║${NC}"
echo -e "${GREEN}  ╚════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${BOLD}Extension ID:${NC} $EXTENSION_ID"
echo ""
echo "  💡 להסרה: הרץ את אותו הקובץ עם הפרמטר -u"
echo "     bash install-force-mac.command -u"
echo ""
read -n 1 -s -r -p "  Press any key to close..."
echo ""
