#!/bin/sh

#    AntiRight (c) 2002-2006 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

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

DEBUG=0
if [ "$DEBUG" = "1" ]; then
	COUNTER=$(($COUNTER+1))
	echo $COUNTER
	set -vx
fi

ARSHELL=gtkshell
AWK=awk 

ACE_Verification()
{
    $ARSHELL -oe -al "$1"\
	'echo -n 1 \# Yes,_do_that.' 'echo -n 0 \# No,_do_not_do_that.'
}
ACE_Check_Configuration_File()
{
    # This probably should be replaced with a for loop.
    # In such the likely prefixes are what will be processed.
    if [ ! -f ~/.antiright ]; then
	cp $PREFIX/share/ACE-desktop/system.antiright ~/.antiright
    else
	# If ~/.antiright doesnt contain the text "revision" it does
	# not keep track of revisions and therefore is an old version.
	if [ "$(grep revision ~/.antiright)" = "" ]; then
	    # Backup customizations.
	    mv ~/.antiright ~/.antiright.old
	    # Restore2 ~/.antiright with a new instance.
	    ACE_Check_Configuration_File
	    # Alert the user.
	    echo 'Your old ~/.antiright has been saved to ~/.antiright.old'
	    echo 'This is due to the use of a new revision of the file,'
	    echo 'changing the theme support.'
	fi
    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 darkgrey
	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
}
swap_load()
{
	echo -n '  '
	swapctl -l | tail -n 1 | awk '{print $5}' | tr -d '\n'
#	echo -n ' ' Swap Used '            '
}
taskbar_update()
{
	if [ "$(uname)" = "NetBSD" ]; then
                dateload; swap_load
        else
                dateload
        fi
}
Sticky_Note()
{
	$ARSHELL -aT -og 128x128 
}
X_dimensions()
{
	xdpyinfo | grep dim | awk '{print $2}'
}
X_width()
{
	X_dimensions | cut -dx -f1
}
X_height()
{
	X_dimensions | cut -dx -f2
}
Deskbar()
{
	if [ "$(ACE deskbar_style)" = "0" ]; then
	$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
	else

	TMP=/tmp/ACE.panel.$$
	trap "rm -f $TMP" 2
	echo '#!/bin/sh' > $TMP
	echo "$ARSHELL -os -on -or 1 \\" >> $TMP
	echo " -og +$(ACE Deskbar_X)+$(ACE Deskbar_Y)\\" >> $TMP
	echo " -aI ACE $icon/ACE.png\\" >> $TMP
	echo " -at env\\" >> $TMP
	for item in $(ACE Panel_Items); do
		echo ' -aI '"'"ACE $item"'" $icon/$item.png "\\" >> $TMP
	done
	echo " -aul 'ACE -A taskbar_update'" >> $TMP
	chmod +x $TMP
	$TMP
	rm -f $TMP

	fi
}
ARO()
{
	TMP=/tmp/ARO.$$
	if [ $# -gt 0 ]; then
    		file $1 > $TMP
		if grep script $TMP; then
			$@ &
		elif grep HTML $TMP; then
			ACE Terminal -e lynx $1 & 
    		elif grep text $TMP; then
			ACE -A 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 -A Text_Editor $1 &
    		elif grep empty $TMP; then
			ACE -A Text_Editor $1 &
    		elif grep directory $TMP; then
			cd $1
			ACE -A File_Manager
    		else
    			# Execute the file.  
			$@ &
		fi
	else
		$ARSHELL -al "No arguments were specified" &
	fi
	rm -f $TMP
}
Read_Man_Page()
{
	ACE Terminal -T $2 -e man $1 $2
}
Man_Browse_Section()
{
	local tf=/tmp/antiright_mbs.$$
	touch $tf
	chmod og-rwx $tf
	chmod u+x $tf
	echo '#!/bin/sh' >> $tf
	echo "$ARSHELL -or 42\\" >> $tf
	manual_root=$(ACE Manual_Root)
	cd $manual_root/man$1
	echo "'Manual Section "$1"' \\" >> $tf
	for file in $(ls | cut -d. -f1); do
		echo " 'ACE -A Read_Man_Page "$1 $file"' \\" >> $tf
	done
	echo " 'ACE -A Man_Browse_Section $1 # Back'" >> $tf
	#cat $tf > /tmp/tf.out
	$tf
	rm -f $tf
}
Manual_Browser()
{
	mbs=Man_Browse_Section
	$ARSHELL -or 1 -al "Manual section:" "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" 
}
Man_Page()
{
	rmp " " $1
}
NetBSD_Package_Info()
{
	pkg_info > /tmp/pkg_info.$$
	ACE Terminal -e less /tmp/pkg_info.$$ &
	rm -f /tmp/pkg_info.$$
}
NetBSD_Panel()
{
	$ARSHELL -or 4 -og 64x32\
		'ACE -A NetBSD_Package_Info'
}
ACE_Panel()
{
   $ARSHELL -os -or 5 -og 410x240\
	'ACE IRC' \
	'ACE CD_Player' \
	'ACE File_Manager' \
	'ACE -A Manual_Browser' \
	'ACE -A Alarm' \
	'ACE Mail' \
 	'ACE -A Background_Editor' \
 	'ACE -A Settings' \
 	'ACE -A Command' \
	'ACE -A Administration_Panel' \
	'ACE -A NetBSD_Panel' \
	'ACE -A File_System_Panel' \
	'ACE -A Network_Panel' \
	'ACE -A Publishing_Panel'\
	'ACE -A Manual_Browser' 

}
Command()
{
	$ARSHELL -al 'Command:' -ap env
}
Calendar()
{
	ACE Terminal -e "cal | less"
}
ARI()
{
    $ARSHELL 'make install; $ARSHELL -r 1 Done; echo Install' > /dev/null &
}
return_pseudorandom_color()
{
	local colors="powderblue lavender pink wheat azure antiquewhite \
		lightsteelblue gainsboro thistle darkseagreen"
	local ones=$(date +%S | cut -c 2)
	echo $colors | awk '{print $'$(($ones+1))'}'
}
Diff()
{
	local file_a="$($ARSHELL -al 'Select the first file.' -al FIXME)"
	if [ "$file_a" = "" ]; then
		exit
	fi
	local file_b="$($ARSHELL -al 'Select the second file.' -al FIXME)"
	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 -al $1 -oe 'echo Dismiss' > /dev/null
}

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

Settings_Node()
{
    new_value=$($ARSHELL -og 256x154\
	-al "$(ACE -r $1)"\
	-ap "echo")
#    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
    TMP=${TMPDIR:-/tmp}/ACE.$$
    echo "$ARSHELL -or 9"\\ > $TMP
    for title in $(ACE_record_titles)
      do
      echo " \"ACE -A Settings_Node $title\""\\ >> $TMP
    done
    sh $TMP
    trap "rm $TMP* 2>/dev/null" 0
}
Load_Meter()
{
	$ARSHELL -aul uptime
}
VMStat()
{
	$ARSHELL -aul vmstat
}
Alarm()
{
    local alarm_time="$($ARSHELL -al 'Alarm Time (ex 22:40):' -ap echo)"
    if [ "$alarm_time" != "" ]; then
	$ARSHELL -al "Alarm Command:" -ap echo | at "$alarm_time"
    fi
}

File_System_Panel()
{
    $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()
{
    $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()
{
	$ARSHELL -or 5 \
		"$ARSHELL -aul 'ps xau' & # Processes"\
		"$ARSHELL -aul who & # Users"\
		"$ARSHELL -aul df & # Disks"\
		'ACE System_Monitor'\
		"$ARSHELL -aul uptime & # Uptime"\
		'ACE -A System_Accounting'\
		'xload -bg darkslategrey -fg white -hl azure & # X_Load'
}
Administration_Panel()
{
    $ARSHELL -or 3 \
	'ACE -A Secure_Permissions'\
	'ACE Root_Shell'\
	'ACE -A Monitoring_Panel'
}
System_Accounting()
{
	if [ "$(which sar)" != "" ]; then
		$ARSEHLL -aul sar
	else
		ACE -A Message 'SAR must be installed.' 
	fi
}
Secure_Permissions()
{
	chmod -R o-w ~/*
}
See_Open_Ports()
{
	nmap localhost > /tmp/nmap.$$
	ACE Terminal -e less /tmp/nmap.$$ 
	rm -f /tmp/nmap.$$
}
See_User_Processes()
{
	$ARSHELL -aul 'ps u'
}
rgb_background()
{
    if [ -f $HOME/.antiright_background ]; then
	cat $HOME/.antiright_background
    else
	echo black
    fi
}
Background_Editor()
{
    color="$($ARSHELL -l Color: -t echo)"
    if [ "$color" != "" ]; then
	echo $HOME
	echo $color > $HOME/.antiright_background
	set_value background 'ACE -A rgb_background'
	restart_desktop
    fi
}
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 &
}
Manual_Page()
{
    ACE Terminal -e man $1
}
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()
{
	$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:' -ap "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


