#!/bin/bash

# TODO: Wait for response on https://bugzilla.gnome.org/show_bug.cgi?id=761969

# This is based on grml-lock by: 
# grml-team (grml.org), (c) Michael Prokop <mika@grml.org>
# License:       This file is licensed under the GPL v2.

PN="$(basename $0)"

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
  echo "${PN}: wrapper script to lock desktop
This script is a wrapper to lock your desktop session.
Usage: just execute $PN without any further options."
  exit 0
fi

SET_PWD_TEXT="Set password (hidden typing):"
CONFIRM_PWD_TEXT="Retype new password:"
ERROR_TEXT="Error retrieving password. Exiting."
ASK_SET_PWD_TEXT="You have not set a password yet. Without a password you will not be able to log in again. Do you want to set a password now?"
CANCEL_LABEL="Cancel"
OK_LABEL="OK"

DIALOG='gdialog'
PWD_CMD="zenity --title $PN --entry --hide-text"


lock_desktop() {
#  gnome-screensaver-command -l
  dbus-send --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.Lock
}

is_passwd_set() {
  if [ $(passwd --status | awk '{printf $2}') = "NP" ] ; then
    return 1
  else
    return 0
  fi
}

set_passwd() {

  PASSWD1="$($PWD_CMD --text="$SET_PWD_TEXT")"
  PASSWD2="$($PWD_CMD --text="$CONFIRM_PWD_TEXT")"

  if [ -z "$PASSWD1" ] ; then
    $DIALOG --title "$PN" --msgbox "$ERROR_TEXT" 0 0
    exit 1
  fi
  stderr=$(echo -e "$PASSWD1\n$PASSWD2" | passwd 2>&1 > /dev/null)
  result=$(echo "$stderr" | sed "s/Enter new UNIX password: //g" | sed "s/Retype new UNIX password: //g")
  
  if [ "$result" = "passwd: password updated successfully" ] ; then
    return 
  else 
    $DIALOG --title "$PN" --msgbox "Error: $result. Exiting." 0 0
    exit 1
  fi
}

askpwd() {
  if [ "$DIALOG" = "gdialog" ] ; then
    zenity --title="$PN" --question --cancel-label="${CANCEL_LABEL}" --ok-label="${OK_LABEL}" --text="${ASK_SET_PWD_TEXT}"
  fi

  if [ "$?" = "0" ] ; then
    set_passwd && sleep 2 # TODO Remove the sleep if GNOME Bug 761969 is fixed
  else
    exit 1
  fi
}

is_passwd_set || askpwd
[ "$?" = "0" ] && lock_desktop || exit 1

