#!/bin/bash

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

set -e

EXTENSION_ID="aeblfdkhhhdcdjpifhhbdiojplfjncoa"
WEBSTORE_UPDATE_URL="https://clients2.google.com/service/update2/crx"

# Chrome and Chromium each read external extensions from their own directory.
# Seed both, so the extension is there whichever is installed now or later.
install_browser_extension() {
  local dir

  for dir in /usr/share/google-chrome/extensions /usr/share/chromium/extensions; do
    sudo mkdir -p "$dir"
    printf '{ "external_update_url": "%s" }\n' "$WEBSTORE_UPDATE_URL" | sudo tee "$dir/$EXTENSION_ID.json" >/dev/null
    sudo chmod 644 "$dir/$EXTENSION_ID.json"
  done
}

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

echo "Installing 1Password browser extension..."
install_browser_extension

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

echo ""
echo "1Password has been installed."

# The browser only picks up the extension when it starts.
if ! omarchy-runs-browser; then
  omarchy-restart-browser --quiet && exit 0
elif gum confirm "Restart your browser now to load the 1Password extension?"; then
  omarchy-restart-browser --force && exit 0
fi

echo "Restart your browser to load the extension."
