#!/bin/bash

# omarchy:summary=Lock the computer and turn off the display
# omarchy:group=system
# omarchy:name=lock
# omarchy:examples=omarchy system lock

omarchy-shell lock lock >/dev/null

# Set keyboard layout to default (first layout)
hyprctl switchxkblayout all 0 > /dev/null 2>&1

# Ensure 1password is locked. Use timeout because `1password --lock` can
# otherwise leave a full Electron helper tree running after each lock.
if pgrep -x "1password" >/dev/null && omarchy-cmd-present 1password; then
  lock_dir="${XDG_RUNTIME_DIR:-/tmp/omarchy-$EUID}"
  if [[ -z ${XDG_RUNTIME_DIR:-} ]]; then
    mkdir -m 700 -- "$lock_dir" 2>/dev/null || true
    if [[ -d $lock_dir && ! -L $lock_dir && -O $lock_dir ]]; then
      chmod 700 -- "$lock_dir" 2>/dev/null || true
    fi
  fi
  if [[ ! -d $lock_dir || -L $lock_dir || ! -O $lock_dir || $(stat -c %a -- "$lock_dir" 2>/dev/null || true) != "700" ]]; then
    lock_dir=""
  fi
  lock_path="$lock_dir/omarchy-1password-lock.lock"
  if [[ -n $lock_dir && ! -L $lock_path && ( ! -e $lock_path || -f $lock_path ) ]]; then
    (
      umask 077
      exec 9>"$lock_path" || exit 0
      flock -n 9 || exit 0
      timeout --kill-after=1s 3s 1password --lock >/dev/null 2>&1 || true
    ) &
  fi
fi

# Avoid running screensaver when locked
screensaver='[/]usr/lib/omarchy-screensaver/omarchy-screensaver'
if pkill -f "$screensaver" 2>/dev/null; then
  timeout 1s pidwait -f "$screensaver" 2>/dev/null || pkill -KILL -f "$screensaver" 2>/dev/null || true
  # It hid the cursor, and a killed or failed exit leaves it hidden.
  hyprctl eval 'hl.config({ cursor = { invisible = false } })' >/dev/null 2>&1 || hyprctl keyword cursor:invisible false >/dev/null 2>&1 || true
fi
