#!/bin/bash

# Toggle passwordless sudo for the current user.
# Usage: omarchy-sudo-passwordless-toggle [MINUTES]
# First run: enables passwordless sudo for 15 minutes (after confirmation).
# Second run: disables it early.

NOPASSWD_FILE="/etc/sudoers.d/99-omarchy-nopasswd-${USER}"
TIMER_NAME="omarchy-nopasswd-expire-${USER}"

MINUTES=${1:-15}
if [[ $1 && ! $1 =~ ^[0-9]+$ ]]; then
  echo "Usage: omarchy-sudo-passwordless-toggle [MINUTES]" >&2
  exit 1
fi

# Safety: if the file exists but the timer doesn't (e.g. after reboot), clean up
if sudo test -f "$NOPASSWD_FILE" && ! systemctl is-active "${TIMER_NAME}.timer" &>/dev/null; then
  sudo rm "$NOPASSWD_FILE"
fi

# Check for the file directly — sudo -n can stay cached or be granted by other rules
if sudo test -f "$NOPASSWD_FILE"; then
  if [[ $1 ]]; then
    sudo systemctl stop "${TIMER_NAME}.timer" 2>/dev/null
    sudo systemd-run --on-active=${MINUTES}m --timer-property=AccuracySec=1s --unit="$TIMER_NAME" \
      rm "$NOPASSWD_FILE"
    echo "Passwordless sudo timer updated. It will now automatically disable in ${MINUTES} minutes."
  else
    sudo rm "$NOPASSWD_FILE"
    sudo systemctl stop "${TIMER_NAME}.timer" 2>/dev/null
    echo "Passwordless sudo has been DISABLED. Sudo will require a password again."
  fi
else
  echo ""
  echo "⚠️WARNING: This will allow ANY process running as your user to"
  echo "execute ANY command as root WITHOUT a password for ${MINUTES} minutes."
  echo ""
  echo "This is useful for AI agents that need to run sudo commands,"
  echo "but it significantly weakens the security of your system."
  echo "Anyone or anything with access to your user account gets full root."
  echo ""
  echo "Passwordless sudo will automatically disable after ${MINUTES} minutes."
  echo "Run this command again to disable it early."
  echo ""

  if gum confirm "Enable passwordless sudo for ${MINUTES} minutes? This is a significant security risk!"; then
    echo "${USER} ALL=(ALL) NOPASSWD: ALL" | sudo tee "$NOPASSWD_FILE" > /dev/null
    sudo chmod 440 "$NOPASSWD_FILE"
    sudo systemd-run --on-active=${MINUTES}m --timer-property=AccuracySec=1s --unit="$TIMER_NAME" \
      rm "$NOPASSWD_FILE"

    echo ""
    echo "Passwordless sudo has been ENABLED. It will automatically disable in ${MINUTES} minutes."
    echo "Note: if you restart before then, run omarchy-sudo-passwordless-toggle again to disable it."
  else
    echo "Aborted. No changes made."
  fi
fi
