#!/usr/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
# SPDX-FileCopyrightText: 2024 Thomas Duckworth <tduck973564@gmail.com>

# Must be run from within Polkit (pkexec)
uid="$PKEXEC_UID"

prev_tty=$(/usr/bin/loginctl list-sessions | grep $uid | xargs | cut -f 5 -d " ")
prev_tty_num=$(echo $prev_tty | cut -c 4-)
free_tty=$(find -L /proc/[1-9]*/fd/. ! -name . -prune -type c -exec  stat -Lc '%t %T' {} + |
  awk '$1 == "4" {seen[$2]}
       END {
         for (i=1; i<=63; i++)
           if (!(sprintf("%x", i) in seen))
             print "/dev/tty" i
       }' | tail -n 1)
seat_num=$(/usr/bin/loginctl list-sessions | grep $uid | xargs | cut -f 4 -d " " | cut -b 5-)

chvt "$(echo "$free_tty" | cut -c 9-)"

echo "prev_tty:     $prev_tty"
echo "prev_tty_num: $prev_tty_num"
echo "free_tty:     $free_tty"
echo "uid:          $uid"
echo "seat_num:     $seat_num"

# Suppress `atychiarc is not writable` error on launch
sudo install -g atychia -o atychia -d /home/atychia/

# Check for required components
if ! getent passwd atychia > /dev/null 2>&1; then
    kdialog --error "The \`atychia\` user does not exist, therefore Atychia cannot be launched.\nPlease open an issue at \`https://github.com/filotimo-linux/atychia\`.\n\nTo restart plasmashell, press Meta+Ctrl+Shift+B." --title "Error"
    exit 1
fi
if ! command -v cage &> /dev/null; then
    kdialog --error "The \`cage\` compositor is not installed, therefore Atychia cannot be launched.\nPlease open an issue at \`https://github.com/filotimo-linux/atychia\`.\n\nTo restart plasmashell, press Meta+Ctrl+Shift+B." --title "Error"
    exit 1
fi
if [ -z "$prev_tty" ] || [ -z "$prev_tty_num" ] || [ -z "$free_tty" ] || [ -z "$uid" ] || [ -z "$seat_num" ]; then
    kdialog --error "Values required for Atychia to start could not be generated, therefore Atychia cannot be launched.\nPlease open an issue at \`https://github.com/filotimo-linux/atychia\`.\n\nTo restart plasmashell, press Meta+Ctrl+Shift+B." --title "Error"
    exit 1
fi

sudo /usr/bin/systemd-run \
    --property PAMName=login \
    --property User="atychia" \
    --property StandardInput=tty \
    --property TTYPath="$free_tty" \
    --property TTYReset=yes \
    --property TTYVHangup=yes \
    --property Environment="XCURSOR_THEME=breeze_cursors" \
    --property Environment="WLR_NO_HARDWARE_CURSORS=1" \
    bash -c "cage -dsm last -- /usr/bin/atychia $prev_tty_num $uid $seat_num || chvt $prev_tty_num"
