#!/bin/sh -m

#    AntiRight (c) 2002-2007 Jeffrey Bedard antiright@gmail.com

#    This file is part of AntiRight.

#     AntiRight is free software; you can redistribute it and/or
#     modify it under the terms of the GNU General Public License as
#     published by the Free Software Foundation; either version 2 of
#     the License, or (at your option) any later version.  AntiRight
#     is distributed in the hope that it will be useful, but WITHOUT
#     ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.  You should have
#     received a copy of the GNU General Public License along with
#     AntiRight; if not, write to the Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

# /bin/sh should have job control enabled.  (-m)

icon=$PREFIX/share/ACE-desktop/icons

DEBUG=0
if [ "$DEBUG" = "1" ]; then
	#set -vx
	Debug()
	{
		COUNTER=$(($COUNTER+1))
		echo $COUNTER
	}
else
	Debug()
	{
    		echo -n
	}
fi

Get_Temp()
{
	if [ "$TMPDIR" = "" ]; then
		TMPDIR=/tmp
	fi
	echo $TMPDIR/ACE.$1.$$
}

Prepare_Temp()
{
	rm -f $1
	touch $Secure1
	chmod og-rwx $1
	chmod u+x $1
	trap "rm -f $@" EXIT QUIT
}

Prepare_Temp_Script()
{
	Prepare_Temp $1
	echo '#!/bin/sh' >> $1
}


ARSHELL=gtkshell
AWK=awk 

ACE_Verification()
{
	$ARSHELL  -or 1 -oe -al "$(echo $1 __ | tr '_' ' ')"\
		'echo Yes' 'echo No'
}
ACE_Check_Configuration_File()
{
	if [ ! -f ~/.antiright ]; then
		cp $PREFIX/share/ACE-desktop/system.antiright\
			~/.antiright
    	fi
}
ACE_record_titles()
{
    	$AWK -F : 'NF > 0 {if ($0 !~ /#/){print $1}}' ~/.antiright\
		| sort | uniq | tr '\n' ' '
}
ACE_read_configuration_value()
{
# This prints values of records matching $1 that do not contain # characters
    	$AWK -v config_item=$1 '\
		BEGIN {FS=":"}\
		$1 ~ config_item {if ($0 !~ /#/) value=$2}\
		END {print value}' ~/.antiright
# The value is printed in the end to ensure that it is the most recent value
}
AR_Prepare_Environment()
{
	xrdb ~/.Xdefaults
	xsetroot -solid "$(ACE Background)"
	ACE_Check_Configuration_File
	touch ~/.antirightrc
	chmod +x ~/.antirightrc
	~/.antirightrc
}
AR()
{
	AR_Prepare_Environment
	ACE -A Deskbar
	if [ "$WINDOWMANAGER" != "" ]; then
		exec $WINDOWMANAGER
	else
		exec twm
	fi
}
Prompt_User()
{
	$ARSHELL  -oe -al "Enter $1:" 
}
Binary_Command()
{
	if [ "$2" = "" ]; then
		local SOURCE="$(Prompt_User Source)"
	fi
	local DEST="$(Prompt_User Destination)"
	$1 $SOURCE $DESTINATION
}
Check_AR_IN_FM()
{
	if [ "AR_IN_FM" = "1" ]; then
		ACE -A File_Manager &
	fi
}
Move()
{
	Binary_Command mv $1
	Check_AR_IN_FM
}
Copy()
{
	Binary_Command cp $1
	Check_AR_IN_FM
}
Delete()
{
	if [ "$1" = "" ]; then
		local FILE="$(Prompt_User)"
	else
		local FILE=$1
	fi
	rm $FILE

	Check_AR_IN_FM
}
Modes()
{
	$ARSHELL -or 5 -al "$(ls -l $1)" -ar\
		-al 'Drag a mode to the appropriate chmod'\
		'chmod u' 'chmod g' 'chmod o' -ar -al add: '+r' '+w' '+x'\
		-ar -al subtract: 'chmod -r' '-w' '-x'
	Check_AR_IN_FM
}
FM_Text_Editor()
{
	ACE Text_Editor $@ &
	ACE -A File_Manager &
}
File_Manager()
{
	if [ "$1" != "" ]; then
		cd $1 
	fi
	export AR_IN_FM=1
	local CMD="exec $ARSHELL -or 16 -og 750x500 -oe -al $(pwd)"
	local FM="ACE -A File_Manager"
	CMD="$CMD 'exit # CLOSE'"
	CMD="$CMD \"cd .. ; $FM & # UP\""
	
	CMD="$CMD 'ACE -A Delete & # ACE_-A_Delete'"
	CMD="$CMD 'ACE Text_Editor & # ACE_-A_FM@Text@Editor'"
	CMD="$CMD 'ACE -A Move & # ACE_-A_Move'"
	CMD="$CMD 'ACE -A Copy & # ACE_-A_Copy'"
	CMD="$CMD 'ACE -A Command & # ACE_-A_Command'"
	CMD="$CMD 'ACE -A Modes & # ACE_-A_Modes'"
	CMD="$CMD 'ACE -A File_Manager & # Refresh'"
	CMD="$CMD -al '--------'"
	local FILE
	for FILE in *; do
		CMD="$CMD \"ACE -A ARO $FILE & # $FILE\",gtk-file"
	done
	CMD="$CMD 'exit # CLOSE'"
	CMD="$CMD \"cd .. ; $FM & # UP\""
	if [ "$DEBUG" = "1" ]; then
		echo $CMD
	fi
	#echo $CMD
	exec sh -c "$CMD"
}
Clock()
{
	gtkshell  -on -og -0-0 -aul "date | tr '\n' ' '"
}
Console()
{
	local CMD="$ARSHELL -os -og 750x500+0-0 -ou 5000 "

	for ITEM in "$@"; do
		CMD="$CMD -al $ITEM -aul \"tail -n 3 $ITEM\" "
	done

	CMD="$CMD -aul date"
	echo "$CMD"
	exec sh -c "$CMD"
}
swap_load()
{
	echo -n '  '
	swapctl -l | tail -n 1 | awk '{print $5}' | tr '\n' '\0'
}
taskbar_update()
{
# From the NetBSD date man page
	date '+%m/%d/%y%n%H:%M:%S'
#		uptime | awk '{$7=$7"\n"; print $0}'
}
Sticky_Note()
{
	nice $ARSHELL  -aT -og 175x200 
}

Old_Deskbar()
{
	exec $ARSHELL -og $(ACE Deskbar_X)$(ACE Deskbar_Y)\
		-or 1\
		-aul "uptime | tr -d '\n'"\
		'ACE Lock'\
		'ACE Screen'\
		'ACE Terminal'\
		'ACE Browser'\
		'ACE Sticky_Note'\
		'ACE'\
		-at env
}

Deskbar()
{
	if [ "$(ACE deskbar_style)" = "0" ]; then
		Old_Deskbar
	else 
		local STYLE="$(ACE deskbar_style)"

		if [ "$STYLE" = "2" ]; then
			local OPTIONS="-or 16 -oh"
		else
			STYLE=1
			local OPTIONS="-or 1"
		fi

		local ACE_STRING="ACE,$icon/ACE.png::'ACE'::eclipse::xload"
		local UPDATER=$(ACE deskbar_updater)

		local CMD="exec $ARSHELL  -of -on $OPTIONS"
		CMD="$CMD -og +$(ACE Deskbar_X)+$(ACE Deskbar_Y)"

		if [ "$UPDATER" = "TRUE" ]; then
	    		CMD="$CMD $ACE_STRING"
    		fi

		if [ "$STYLE" = "1" ]; then
	   		CMD="$CMD -at env"
		fi

	  	for item in $(ACE Panel_Items); do
		 	CMD="$CMD \"ACE $item # \",$icon/$item.png"
	  	done

    		if [ "$UPDATER" = "TRUE" ]; then
    			CMD="$CMD -aul 'ACE -A taskbar_update'"
    		else
      			CMD="$CMD $ACE_STRING"
    		fi
		#echo "$CMD"
		exec sh -c "$CMD"
	fi
}
ARO()
{
#	TMP=Get_Temp ARO
#	TMP=Prepare_Temp $TMP
#	echo $@
	if [ $# -gt 0 ]; then
		TMP=/tmp/ARO.$$
    		file $1 > $TMP
		if grep script $TMP; then
			$@ &
		elif grep HTML $TMP; then
			ACE Browser $1 & 
    		elif grep text $TMP; then
			ACE Text_Editor $1 &
    		elif grep executable $TMP; then
    			# Execute the file and any arguments.  
			$@ &
    		elif grep gzip $TMP; then
    			# Decompress the file.  
			gzip -d $1 &
    		elif grep tar $TMP; then
    			# Untar the file.  
			tar xf $1 &
    		elif grep emacs $TMP; then
    		# Open the file in GNU Emacs.  No xterm is needed because most
    		# modern emacs builds link to the X libraries.
			emacs $1 &
    		elif grep MP3 $TMP; then
			ACE Terminal -e mpg123 $1 &
    		elif grep image $TMP; then
    			# ImageMagick's display command is used.
			display $1 &
    		elif grep MS $TMP; then
    			# Wine is used to run MS programs.
			wine $1 & 
    		elif grep "No such file or directory" $TMP; then
			touch $1
			ACE Text_Editor $1 &
    		elif grep empty $TMP; then
			ACE Text_Editor $1 &
    		elif grep directory $TMP; then
			local AR_IN_FM=0
			cd $1 && File_Manager
    		else
    			# Execute the file.  
			$@ &
		fi
		rm -f $TMP
	else
		$ARSHELL -de "No arguments were specified" &
	fi
	if [ "$AR_IN_FM" = "1" ]; then
		File_Manager
	fi
}
Read_Man_Page()
{
	ACE Terminal -e man $1 $2
}
Man_Browse_Section()
{
	local CMD="exec $ARSHELL -os -og 500x450 -or 42"
	manual_root=$(ACE Manual_Root)
	cd $manual_root/man$1
	CMD="$CMD \"Manual Section $1\""
	for file in $(ls | cut -d. -f1); do
		CMD="$CMD \"ACE -A Read_Man_Page \'$1\' $file\""
	done
	CMD="$CMD \"ACE -A Man_Browse_Section $1 # Back\""

if [ "DEBUG" = "1"]; then
	echo $CMD
fi
	exec sh -c "$CMD"
}
Manual_Browser()
{
	mbs=Man_Browse_Section
	exec $ARSHELL  -or 3 -al "Manual section:" -al ' ' -al ' '\
		"ACE -A $mbs 1" "ACE -A $mbs 2"\
		"ACE -A $mbs 3" "ACE -A $mbs 4" "ACE -A $mbs 5"\
		"ACE -A $mbs 6" "ACE -A $mbs 7" "ACE -A $mbs 8"\
		"ACE -A $mbs 9" 
}

ACE_Panel()
{
   exec $ARSHELL  -or 5 \
	'ACE IRC' \
	'ACE CD_Player' \
	'ACE File_Manager' \
	'ACE -A Manual_Browser' \
	'ACE -A Alarm' \
	'ACE Mail' \
 	'ACE -A Settings' \
 	'ACE -A Command' \
	'ACE -A Administration_Panel' \
	'ACE -A File_System_Panel' \
	'ACE -A Network_Panel' \
	'ACE -A Manual_Browser' \
	'ACE -A Publishing_Panel' \
	'ACE -A Calendar'\
	'gtkshell -da & # About'

}
OS_Specific()
{
	$ARSHELL -di 'No OS specific functionality available.'
}
Command()
{
	local COMMAND="$($ARSHELL  -al 'Command:' -oe -at env)"
	exec $COMMAND $@
}
Calendar()
{
	exec $ARSHELL  -al "$(cal)"
}
ARI()
{
    $ARSHELL 'make install; $ARSHELL -r 1 Done; echo Install' >& /dev/null &
}
Diff()
{
	local file_a="$($ARSHELL -df)"
	if [ "$file_a" = "" ]; then
		exit
	fi
	local file_b="$($ARSHELL -df)"
	if [ "$file_b" = "" ]; then
		exit
	fi
	diff $file_a $file_b > /tmp/diff.$$
	ACE Terminal -e less /tmp/diff.$$
	rm -f /tmp/diff.$$
}
Message()
{
    $ARSHELL -di $1
}

set_value()
{
    echo "$1":"$2" >> ~/.antiright
}

Settings_Node()
{
    new_value=$($ARSHELL -og 256x154\
    	-al 'Current command:'\
	-al "$(ACE -r $1)"\
	-al 'Enter a new command:'\
	-oe -at "echo"\
	'# Close')
#    echo new value is $new_value
    if [ "$new_value" != "" ]; then
	set_value $1 "$new_value"
    fi
}
Settings()
{
	# Ensure the existance of a configuration file.
    ACE_Check_Configuration_File
    local CMD="exec $ARSHELL -or 10"
    for title in $(ACE_record_titles); do
      CMD="$CMD \"ACE -A Settings_Node $title\""
    done
    exec sh -c "$CMD"
}
Load_Meter()
{
	$ARSHELL -aul uptime
}
VMStat()
{
	$ARSHELL -aul vmstat
}
Alarm()
{
    local alarm_time="$($ARSHELL  -al 'Alarm Time (ex 22:40):' -oe -at echo)"
    if [ "$alarm_time" != "" ]; then
	$ARSHELL  -al "Alarm Command:" -oe -at echo | at "$alarm_time"
    fi
}

File_System_Panel()
{
    exec $ARSHELL -or 2 \
	'ACE -A Mount_File_System'\
	'ACE -A Unmount_File_System'\
	'ACE See_Free_Space'\
	'ACE -A Show_All_File_Systems'\
	'ACE -A Diff'
}

Network_Panel()
{
    exec $ARSHELL -or 3 \
	'ACE -A Open_Display' 'ACE Open_URL'\
	'ACE -A ACE_peer_operation ftp'\
	'ACE -A ACE_peer_operation telnet'\
	'ACE -A ACE_Peer_operation ssh'\
	'ACE -A ACE_peer_operation sftp'\
	'ACE -A See_Open_Ports'\
	'ACE PPP_On' 'ACE PPP_Off'
}

IOStat()
{
	$ARSHELL -aul 'iostat'
}
Monitoring_Panel()
{
	exec $ARSHELL -or 4 \
		"$ARSHELL -os -og 640x480 -ou 3000 -aul 'ps xau' & # Processes"\
		"$ARSHELL -ou 2000 -aul who & # Users"\
		"$ARSHELL -ou 5000 -aul df & # Disks"\
		'ACE System_Monitor'\
		"$ARSHELL -ou 2500 -aul uptime & # Uptime"\
		'ACE -A System_Accounting'\
		'xload -bg darkslategrey -fg white -hl azure & # X_Load'
}
Administration_Panel()
{
    exec $ARSHELL -or 4 \
	'ACE -A Secure_Permissions'\
	'ACE Root_Shell'\
	'ACE -A Monitoring_Panel'\
	'ACE -A OS_Specific'
}
System_Accounting()
{
	if [ "$(which sar)" != "" ]; then
		$ARSEHLL -aul sar
	else
		Message 'SAR must be installed.' 
	fi
}
Secure_Permissions()
{
	local choice=$(ACE_Verification\
	Make_all_your_files_invisible_to_other_users?)
	if [ "$choice" = "Yes" ]; then
		chmod -R o-w ~/*
	fi
}
See_Open_Ports()
{
	nmap localhost > /tmp/nmap.$$
 	ACE Terminal -e less /tmp/nmap.$$ 
	rm -f /tmp/nmap.$$
}
See_User_Processes()
{
	$ARSHELL -aul 'ps u'
}
Mount_File_System()
{
    ACE -L 'File System' mount
}
Unmount_File_System()
{
    ACE -L 'File System' umount
}
Show_All_File_Systems()
{
	ACE Terminal -e less /etc/fstab &
}
ACE_peer_operation()
{
    ACE -L "$(echo -n $1 | tr [a-z] [A-Z]) Peer" ACE Terminal -e $1
}
Open_Display()
{
    ACE_peer_operation 'xhost +'
}

# desktop pulishing with roff
arroff()
{
	groff -Tps \
	"$(ACE roff_flags)"\
	"$(ACE roff_file)" \
	> /tmp/roff.ps.$$
}
clean_roff()
{
	rm -f /tmp/roff.ps.$$
}
Preview_roff()
{
	arroff
	gv /tmp/roff.ps.$$ &
	clean_roff
}
Print_roff()
{
	arroff
	$(ACE print_command)\
	/tmp/roff.ps.$$ 
	clean_roff
}
Save_PS()
{
	arroff
	mv /tmp/roff.ps.$$ \
	$(ACE roff_file).ps
}
Save_PDF()
{
	arroff
	ps2pdf /tmp/roff.ps.$$\
		$(ACE roff_file).pdf
	clean_roff
}
Publishing_Panel()
{
	exec $ARSHELL -or 4\
		'ACE -A Preview_roff'\
		'ACE -A Print_roff'\
		'ACE -A Save_PDF'\
		'ACE -A Save_PS'\
		'ACE -A Save_TEXT'\
		'ACE -A Save_JPEG'\
		'ACE -A Word_Count_roff'
}
Word_Count_roff()
{
	local filename=$(ACE roff_file)
	local output=$(wc $filename)
	ACE -A Message "$output"
}
Save_JPEG()
{
	arroff
	convert /tmp/roff.ps.$$\
		$(ACE roff_file).jpg
	clean_roff
}
Save_TEXT()
{
	groff -Tascii\
	"$(ACE roff_flags)"\
	"$(ACE roff_file)"\
	> $(ACE roff_file).txt
}
# Disk space admin commands
Select_Directory()
{
	directory="$($ARSHELL \ 
		-al 'Select the current directory.'\
		-at echo)"
}
Get_Largest_Files()
{
	Select_Directory
	du -ak $directory | sort -n | tail -n 64 > /tmp/ACE.du.$$
}
Show_Largest_Files()
{
	Get_Largest_Files
	ACE Terminal -e less /tmp/ACE.du.$$
}

# Problem here can be cases where files contain spaces.

Prompt_to_Clean()	
{
	Get_Largest_Files

	for file in "cat /tmp/ACE.du.$$"; do
		ask_del $file
	done
}
ACE_show_usage_and_exit()
{
    echo "usage: `basename $1` [+-ctr ARG] [+-p ARG] [+-L ARG] [+-V ARG]\
	[+-A ARG] [--] ARGS..."
    exit 2
}

while getopts :ctp:r:L:V:A: OPT; do
    case $OPT in
	c|+c)
	ACE_Check_Configuration_File
	exit 0
	;;
	t|+t)
	ACE_record_titles
	exit 0
	;;
	p|+p) # This argument allows executing a configured binding
	      # while not passing any proceeding arguments.
	$(ACE_read_configuration_value "$OPTARG")
	exit 0
	;;
	r|+r)
	ACE_read_configuration_value "$OPTARG"
	exit 0
	;;
	L|+L)
	arguments=$($ARSHELL  -al 'Launch Arguments:' -oe -at "echo")
	shift $(($OPTIND - 1))
	$@ $arguments &
	exit 0
	;;
	V|+V)
	ACE_Verification "$OPTARG"
	;;
	A|+A)
	shift $(($OPTIND-2))
	$@
	exit 0
	;;
	*)
	ACE_show_usage_and_exit $0
    esac
done
shift `expr $OPTIND - 1`

if [ $# -gt 0 ]; then # This runs a command configured in ~/.antiright
    if grep theme <<EOF
$1
EOF
	then
	ACE_set_theme $1
    else
        # This allows parameters to be passed to a configured command.
	command="$(ACE_read_configuration_value $1)"
	shift
	$command $@ &
    fi
else
    ACE_Panel
fi


