#!/bin/bash

# omarchy:summary=Install 1Password and its Chromium extension.
# omarchy:requires-sudo=true

set -e

EXTENSION_ID="aeblfdkhhhdcdjpifhhbdiojplfjncoa"
EXTENSION_DIR="/usr/share/chromium/extensions"
EXTENSION_FILE="$EXTENSION_DIR/$EXTENSION_ID.json"
WEBSTORE_UPDATE_URL="https://clients2.google.com/service/update2/crx"

install_chromium_extension() {
  if omarchy-cmd-missing chromium; then
    echo "Chromium is not installed; skipping 1Password Chromium extension."
    return
  fi

  sudo mkdir -p "$EXTENSION_DIR"
  printf '{ "external_update_url": "%s" }\n' "$WEBSTORE_UPDATE_URL" | sudo tee "$EXTENSION_FILE" >/dev/null
  sudo chmod 644 "$EXTENSION_FILE"
}

echo "Installing 1Password..."
omarchy-pkg-add 1password 1password-cli

echo "Installing 1Password extension for Chromium..."
install_chromium_extension

echo "Opening 1Password..."
uwsm-app -- 1password >/dev/null 2>&1 &

echo ""
echo "1Password has been installed. Restart Chromium to load the browser extension."
