#!/bin/sh

# This file is covered by the GNU General Public License,
# which should be included with libshell as the file LICENSE.
# All copyright information are listed in the COPYING.

# Copyright (C) 2012 Andrew V. Stepanov <stanv@altlinux.org>

#
# * Lock/unlock X screen
# * Uses alock + pam
# * Run alock as root (prevent from user kill)
#

# Use libshell
. shell-config
. shell-quote
. shell-var
export verbose=1

# alterator-tc-lock flag file
AL_CONFIG="/etc/alterator-tc-lock-nologin"

# PAM config file for alock
PAM_CFG="/etc/pam.d/alock"

if [ -z "${__included_alterator_tc_lock-}" ]; then
__included_alterator_tc_lock=1

# Update locker status regarding to flag file
al_run() {
    if [ -f "$AL_CONFIG" ]; then
        al_lock
    else
        al_unlock
    fi
}

# Lock screen
al_lock() {
    verbose "Ask to lock screen"

    # Update PAM config
    al_update_pam_cfg

    # Create sub-shell to save virgin environment
    (
    
    # Reset positional parameters
    set --

    # Use pam authentication
    set -- "$@" "-auth" "pam"

    # Set background
    set -- "$@" "-bg" "image:file=/usr/share/alterator-tc-lock/2.jpg:scale"

    # Check already locked
    ALOCK_PID="$(pidof alock)"
    if [ -n "$ALOCK_PID" ]; then
       verbose "Already locked, nothing to do."
       exit 0
    fi

    params="$(echo "$@")"

    # Lock
    verbose "Lock screen"
    if [ $USER = "$ACTIVE_USER" ]; then
        DISPLAY=":0" alock $params &
    else
        DISPLAY=":0" su - -c "alock $params" "$ACTIVE_USER" &
    fi

    )
}

# Unlock screen
al_unlock() {
    verbose "Ask to unlock screen"

    rm -f "$AL_CONFIG"

    # Kill root owned alock's
    for pid in $(pidof alock); do
        user="$(ps --no-headers -p $pid --format user)"
        if [ "$user" != "$ACTIVE_USER" ]; then
            continue
        fi

        # Goodbye locker!
        verbose "Kill $pid"

        kill $pid
    done
}

# Rewrite alock PAM config for our needs
al_update_pam_cfg() {
    verbose "Rewirte $PAM_CFG"
cat << EOF > "$PAM_CFG"
# %PAM-1.0
# Rewrited by alterator-tc-lock
auth required pam_nologin.so file=$AL_CONFIG successok
EOF
}

fi #__included_alterator_tc_lock

#
# ENTER POINT
#

export TARGET_DISPLAY=":0"

if ! which ck-list-sessions >/dev/null 2>&1; then
    verbose "Can't find ck-list-sessions"
    exit 0
fi

if ! which getent >/dev/null 2>&1; then
    verbose "Can't find getent"
    exit 0
fi

# Lookup for active user
ACTIVE_USER="$(
ck-list-sessions | sed -n -e '/unix-user =/p; /x11-display =/p' | sed -n -e "s/^.* = '\(.*\)'/\1/p" | while read uid && read disp; do
if [ "$disp" = "$TARGET_DISPLAY" ]; then
    getent passwd "$uid" | sed -n -e 's/:.*$//p'
    break
fi
done 
)"

if [ -z "$ACTIVE_USER" ]; then
    verbose "Can't find active X session"
    exit 0
fi

verbose "X session run by user $ACTIVE_USER"

# Check PAM config
if ! [ -f "$PAM_CFG" ]; then
    verbose "Can't find $PAM_CFG"
    exit 0
fi

# Run alterator-tc-lock
al_run
