#!/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

PREFIX=/usr/local
icon=$PREFIX/share/antiright/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
	if [ -e /usr/local/share/antiright/system.antiright ]; then
	    cp /usr/local/share/antiright/system.antiright ~/.antiright
	elif [ -e /usr/share/antiright/system.antiright ]; then
	    cp /usr/share/antiright/system.antiright ~/.antiright
	fi
    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()
{
	gtkshell -aT -og 128x128 
}
Deskbar()
{
	if [ "$(ACE deskbar_style)" = "0" ]; then
	$ARSHELL -og +0+0\
		-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.$$
	echo '#!/bin/sh' > $TMP
	echo 'gtkshell -og +0+0 -on -or 1 \' >> $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.'\
		-E 'echo Close'
	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 'gtkshell -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
	gtkshell -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" 
}
Manual()
{
	Manual_Browser
}
Man_Page()
{
	rmp " " $1
}
Deb_Search()
{
    keywords="$(arshell -At Keywords: | cut -d: -f2)"
    apt-cache search $keywords | arshell -p -geometry 550x400
}
Deb_Install()
{
    package="$(arshell -At Package: | cut -d: -f2)"
    ACE Terminal -e su -c "apt-get install $package"
}
Deb_Show()
{
    package="$(arshell -At Package: | cut -d: -f2)"
    apt-cache show $package | arshell -p -geometry 550x400
}
Debian_Panel()
{
	gtkshell -or 4\
	'ACE -A Deb_Search'\
	'dpkg -l | arshell -p -geometry 550x400 # List_All_Packages'\
	'ACE -A Deb_Install'\
	'ACE -A Deb_Show'
}
NetBSD_Package_Info()
{
	pkg_info > /tmp/pkg_info.$$
	ACE Terminal -e less /tmp/pkg_info.$$ &
	rm -f /tmp/pkg_info.$$
}
NetBSD_Panel()
{
	gtkshell -or 4\
		'ACE -A NetBSD_Package_Info'
}
ACE_Panel()
{
   gtkshell -or 5\
	'ACE IRC' \
	'ACE CD_Player' \
	'ACE File_Manager' \
	'ACE -A Manual' \
	'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 Debian_Panel' \
	'ACE -A File_System_Panel' \
	'ACE -A Network_Panel' \
	'ACE -A Manual_Browser' 

}
Command()
{
	arshell -al 'Command:' -ap env
}
Calendar()
{
	ACE Terminal -e "cal | less"
}
ARI()
{
    $ARSHELL 'make install; gtkshell -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))'}'
}
Delete_File()
{
    rm $($ARSHELL -al 'Select File to Delete:' -al FIXME)
    # Start a new file manager to show the results and allow further
    # operations.
    ACE -A File_Manager
}
Copy_File()
{
	cp $($ARSHELL -al 'Select Source:' -al FIXME) \
	$($ARSHELL -al 'Select Destination:' -al FIXME)
    # Start a new file manager to show the results and allow further
    # operations.
	ACE -A File_Manager
}
Cancel_File_Operation()
{
    ACE -A File_Manager
}
Manage_Files()
{
    gtkshell -or 4 -al "Choose an operation to perform"\
	'ACE -A Delete_File'\
	'ACE -A Copy_File'\
	'ACE -A Cancel_File_Operation'
}
File_Manager()
{
    local file=$($ARSHELL -al FIXME -oe 'ACE -A Manage_Files')
    if [ "$file" != "" ]; then
	ARO $file
    fi
}
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\
	-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()
{
	gtkshell -aul uptime
}
VMStat()
{
	gtkshell -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 4 \
	'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 PPP_On' 'ACE PPP_Off'
}

IOStat()
{
	gtkshell -aul 'iostat'
}

Administration_Panel()
{
    $ARSHELL -or 5 \
	'ACE -A Secure_Permissions'\
	'ACE Root_Shell'\
	'ACE -A See_All_Processes'\
	'ACE -A See_All_Users'\
	'ACE -A See_Disk_Info'\
	'ACE -A SysV_Init'\
	'ACE -A See_Open_Ports'\
	'ACE -A See_User_Processes'\
	'ACE System_Monitor'\
	'ACE -A VMStat & # Memory_Statistics' \
	'ACE -A Uptime' \
	'ACE -A Load_Meter'\
	'ACE -A System_Accounting'\
	'xload -bg red4 -fg yellow -hl yellow & # X_Load'
}
Run_SAR()
{
	gtkshell -aul sar
}
System_Accounting()
{
	if [ "$(which sar)" != "" ]; then
		Run_SAR
	else
		ACE -A Message 'SAR must be installed.' 
	fi
}
Secure_Permissions()
{
    chmod og-rwx ~/.*/*
}
See_All_Processes()
{
	gtkshell -aul 'ps xau'
}
See_All_Users()
{
	gtkshell -aul 'who'
}
See_Disk_Info()
{
	gtkshell -aul 'df'
}
See_Open_Ports()
{
	nmap localhost > /tmp/nmap.$$
	ACE Terminal -e less /tmp/nmap.$$ 
	rm -f /tmp/nmap.$$
}
See_User_Processes()
{
	gtkshell -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
}
See_Free_Space()
{
	See_Disk_Info
}
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 \ 
		-l 'Select the current directory.'\
		-t 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.$$
}
ask_del()
{
	local file_type=\
	"$(file $1)"
	local choice=$(arshell \
		-al "Delete $1?"\
		-al 'File type:'\
		-al "$file_type"\
		'echo Yes' 'echo No')
	if ["$choice" = "Yes"]; then
		rm -rf $1
	fi
}

# 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


