#!/bin/bash
#
# ::copy::
# ::maintainer::
#
#	wrap for poweroff command
#
CMD=`basename $0`


confirm()
{
	local ans=

	while :
	do
		echo -en "$@ (y/n): "
		read ans
		case $ans in
		  y|Y|yes|YES|s|S|si|SI|1)	return 0 ;;
		  n|N|no|NO|0)			return 1 ;;
		esac
	done
}

has_smbclients()
{
	set `show_smbclients | wc -l` 0
	echo $1
	[ $1 == 0 ] && return 1
	return 0
}

has_users()
{
	set `show_users | wc -l` 0
	echo $1
	[ $1 == 0 ] && return 1
	return 0
}

check_all()
{
	local has_warnings=false
	local msg="\n${title}\n\n"
	local warn=`printf "  * ${B}%-18.18s${N}" "[attenzione]"`
	local ok=`printf "  * %-18.18s" "[ok]"`
	local trush=
	local smbclients=
	local users=

	if smbclients=`has_smbclients`
	then
		status="${warn} ci sono ${U}$smbclients files${N} in uso sui dischi di rete"
		has_warnings=true
	else
		status="${ok} non ci sono files in uso sui dischi di rete"
	fi
	msg="${msg}\n${status}\n"

	if users=`has_users`
	then
		status="${warn} ci sono ${U}$users altri utenti${N} connessi al sistema"
		has_warnings=true
	else
		status="${ok} non ci sono altri utenti connessi al sistema"
	fi
	msg="${msg}\n${status}\n"

	$has_warnings && {
		echo -en "$msg\nPremi invio per visualizzare i dettagli: " >&2
		read trush
		(
			echo -e "\n${R} files in uso su dischi di rete ${N}\n"
			show_smbclients
			echo -e "\n${R} utenti connessi ${N}\n"
			show_users
		) | more >&2
		echo >&2

		while :
		do
			echo -en "C=Continua, R=Ricontrolla, E=Esci: " >&2
			read trush
			case $trush in
			  c|C)		break ;;
			  r|R)		echo ""; return 1 ;;
			  e|E|q|Q)	echo "EXIT"; return 1 ;;
			esac
		done
	}
	echo "$msg"
	return 0
}


show_smbclients()
{
	local pid uid mode access rw oplock share file

	smbstatus 2>/dev/null | sed -e '1,/Locked files:/d' \
		| sed -e '1,2d' | while read pid uid mode access rw oplock share file
	do
			[ "$uid" = "" ] && continue

			uid=`getent passwd $uid | cut -d':' -f1`
			file=`echo "$file" | sed \
				-e 's/ *Mon .*//' \
				-e 's/ *Tue .*//' \
				-e 's/ *Wed .*//' \
				-e 's/ *Thu .*//' \
				-e 's/ *Fri .*//' \
				-e 's/ *Sat .*//' \
				-e 's/ *Sun .*//'
			`
			[ "$file" == "." ] && continue

			printf "%-9.9s %-70.70s\n" "$uid" "$share/$file"
	done
}

show_users()
{
	local who=`who`
	local whoami=`who am i`

	echo "$who" | fgrep -v "$whoami"
}


# (MAIN)

R=`tput rev 2>/dev/null`
B=`tput bold 2>/dev/null`
U=`tput bold 2>/dev/null; tput smul 2>/dev/null`
N=`tput sgr0 2>/dev/null`

uname=`uname -n | sed -e 's/\..*//'`
title=`printf "${R} %-70.70s ${N}" "Spegnimento sistema '$uname'"`


# not root? try sudo ..
#
[ `id -u` != 0 ] && exec sudo $0 "$@"


# check loop
#
msg=
while :
do
	msg=`check_all`		&& break
	[ "$msg" == "EXIT" ]	&& exit 1
done

msg="${msg}\nOk per spegnimento '$uname'?"

confirm "$msg" || exit 1

exec /sbin/poweroff "$@"
exit 0
