#!/usr/bin/env bash
# This script will reset x2go sessions to a working state
# Use --all to reset all user X2Go sessions
# Copyright 2021-2025 Bryan C. Roessler
# Licensed under the Apache License, Version 2.0
p="${BASH_SOURCE[0]%/*}"; [[ -r $p/script-functions ]] && . "$p"/script-functions || exit 1

echo "Usage: $0 [username|--all]"

USER_LIST=()
if [[ $EUID -gt 0 ]]; then
    echo "Run as root for all users. Running in user mode for: $(whoami)"
    USER_LIST+=("$(whoami)")
else
    if [[ $1 == "--all" ]]; then
        for d in /home/*; do [[ -d $d ]] && USER_LIST+=("${d##*/}"); done
    elif [[ -n $1 ]]; then
        USER_LIST+=("$1")
    else
        prompt user
        USER_LIST+=("$user")
        unset user
    fi
fi

for user in "${USER_LIST[@]}"; do
    # Remove X2Go cache files
    shopt -s nullglob
    caches=(/home/"$user"/.x2go/C-"$user"-* /home/"$user"/.xsession-x2go-*)
    shopt -u nullglob
    if (( ${#caches[@]} )); then
        ask_ok "Remove X2Go cache files for $user?" &&
        rm -rf "${caches[@]}" &&
        echo "Removed: ${caches[*]} for $user"
    fi

    # Terminate X2Go sessions
    if [[ $EUID -gt 0 ]]; then
        mapfile -t sessions < <(x2golistsessions | grep "$user" | cut -f2 -d'|')
    else
        mapfile -t sessions < <(x2golistsessions_root | grep "$user" | cut -f2 -d'|')
    fi
    if (( ${#sessions[@]} )); then
        ask_ok "Terminate X2Go sessions for $user?" &&
        for session in "${sessions[@]}"; do
            x2goterminate-session "$session" &&
            echo "Terminated: $session for $user"
        done
    fi
done
