#!/bin/bash

if [[ "--remove" == "$1" ]]; then
  yay -Rns --noconfirm fprintd
  sudo rm -rf /etc/pam.d/polkit-1
  sudo sed -i '/pam_fprintd\.so/d' /etc/pam.d/sudo
  echo -e "\e[32mYou've successfully removed the fingerprint setup.\e[0m"
else
  yay -S --noconfirm --needed fprintd usbutils

  if ! lsusb | grep -Eiq 'fingerprint|synaptics|goodix'; then
    echo -e "\e[31m\nNo fingerprint sensor detected.\e[0m"
  else
    # Add fingerprint authentication as an option for sudo
    if ! grep -q pam_fprintd.so /etc/pam.d/sudo; then
      sudo sed -i '1i auth    sufficient pam_fprintd.so' /etc/pam.d/sudo
    fi

    # Add fingerprint authentication as an option for hyprpolkitagent
    if [ ! -f /etc/pam.d/polkit-1 ] || ! grep -q pam_fprintd.so /etc/pam.d/polkit-1; then
      sudo tee /etc/pam.d/polkit-1 >/dev/null <<'EOF'
auth      required pam_unix.so
auth      optional pam_fprintd.so

account   required pam_unix.so
password  required pam_unix.so
session   required pam_unix.so
EOF
    fi

    # Enroll the first finger
    echo -e "\e[32m\nLet's setup your right index finger as the first fingerprint.\nKeep moving the finger around on sensor until the process completes.\n\e[0m"
    sudo fprintd-enroll $USER

    echo -e "\e[32m\nNow let's verify that it's working correctly.\e[0m\n"

    if fprintd-verify; then
      echo -e "\e[32m\nPerfect! Now you can use your fingerprint on the lock screen (Super + Escape).\e[0m"
    else
      echo -e "\e[31m\nSomething went wrong. Maybe try again?\e[0m"
    fi
  fi
fi
