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

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

ARSHELL=gtkshell
AWK=awk 

ACE_Verification()
{
    $ARSHELL "$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=":"}\
	$0 ~ 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()
{
	xrdb ~/.Xdefaults
	xsetroot -solid darkgrey
	ACE_Check_Configuration_File
	touch ~/.antirightrc
	chmod +x ~/.antirightrc
	~/.antirightrc
	ACE -A Panel
	if [ "$WINDOWMANAGER" != "" ]; then
		exec $WINDOWMANAGER
	else
		exec mwm
	fi
}

ARO()
{
	TMP=/tmp/ARO.$$
	if [ $# -gt 0 ]; then
    		file $1 > $TMP
		if grep script $TMP; then
			$@ &
		elif grep HTML $TMP; then
			ACE Terminal 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
			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
}
rmp()
{
	Read_Man_Page $@
}
Man_Browse_Section()
{
	local tf=/tmp/mbs.$$
	touch $tf
	chmod og-rwx $tf
	chmod u+x $tf
	echo '#!/bin/sh' >> $tf
	echo 'gtkshell -r 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 rmp "$1 $file"' \\" >> $tf
	done
	echo " 'ACE -A Man_Browse_Section $1 # Back'" >> $tf
	#cat $tf > /tmp/tf.out
	$tf
	rm -f $tf
}
mbs()
{
	Man_Browse_Section $@
}
Manual_Browser()
{
	gtkshell -r 3 '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 -r 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 -r 4\
		'ACE -A NetBSD_Package_Info'
}
ACE_Panel()
{
   gtkshell -r 6\
	'ACE IRC' \
	'ACE Calculator' \
	'ACE CD_Player' \
	'ACE File_Manager' \
	'ACE -A Sticky_Note' \
	'ACE Lock' \
	'ACE -A Manual' \
	'ACE Editor' \
	'ACE -A Alarm' \
	'ACE Load_Meter' \
	'ACE Terminal' \
	'ACE Browser' \
	'ACE Imager' \
	'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' \

}
Panel()
{
	ACE_Panel
}

Command()
{
	command="$(arshell -At Command:)"
	command="$(echo $command | cut -d: -f2)"
	echo $command
	$command &
}

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))'}'
}
Sticky_Note()
{
    local background=$(return_pseudorandom_color)
    $ARSHELL -W 'Sticky Note' -Am -Amf 'ACE -A Sticky_Note \# New' -Aw\
	-xrm "*XmText.background: $background"\
	-xrm '*XmText.height: 256' -xrm '*XmText.width: 192'\
	-xrm '*XmText.wordWrap: True' 
}
Delete_File()
{
    rm $($ARSHELL -Al 'Select File to Delete:' -ADf)
    # Start a new file manager to show the results and allow further
    # operations.
    ACE -A File_Manager
}
Copy_File()
{
	cp $($ARSHELL -Al 'Select Source:' -ADf) \
	$($ARSHELL -Al 'Select Destination:' -ADf)
    # 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 -r 4 "Choose an operation to perform"\
	'ACE -A Delete_File'\
	'ACE -A Copy_File'\
	'ACE -A Cancel_File_Operation'
}
File_Manager()
{
    local file=$($ARSHELL -Am -ADf -E 'ACE -A Manage_Files')
    if [ "$file" != "" ]; then
	ARO $file
    fi
}
Diff()
{
	local file_a="$(arshell -Al 'Select the first file.' -ADf)"
	if [ "$file_a" = "" ]; then
		exit
	fi
	local file_b="$(arshell -Al 'Select the second file.' -ADf)"
	if [ "$file_b" = "" ]; then
		exit
	fi
	diff $file_a $file_b | arshell -p -geometry 550x400 &
}
Files()
{
    File_Manager
}
Message_Dialog()
{
    $ARSHELL "$(echo $1 | tr '_' ' ')"
}
Help_Dialog()
{
    Message_Dialog "$1"
}

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

Settings_Node()
{
    new_value=$($ARSHELL\
	-l "$1"\
	-t "echo $1: [$(ACE_read_configuration_value $1)]")
    #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 "gtkshell -r 8"\\ > $TMP
    for title in $(ACE_record_titles)
      do
      echo " \"ACE -A Settings_Node $title\""\\ >> $TMP
    done
    echo ' "Select an option to configure."' >> $TMP
    sh $TMP
    trap "rm $TMP* 2>/dev/null" 0
}
ACE_print_time_and_load()
{
    date_and_time="$(date +'%X %x')"
    mail_or_users=$(users | awk '{print NF " Users."}')
    if [ -f /var/mail/$USER ]; then
	if [ "$(ls -l /var/mail/jefbed | $AWK '{print $5}')" != "0" ]; then
	    mail_or_users="Mail."
	fi
    fi
    # In order to conserve space, only the 5 minute load is given.
    echo -n\
	 ' ' $date_and_time $(uptime | cut -d : -f 4 | cut -d , -f 2)\
	$mail_or_users
}

ACE_load_value()
{
    local load=$(uptime | cut -d : -f 4 | cut -d , -f $1)
    local to_show=$(echo $load | cut -d . -f 2)
    local divide_by=$(($(echo $load | cut -d . -f 1) + 1))
    echo $(($to_show / $divide_by))
}
Load_Meter()
{
	gtkshell -u uptime
}
VMStat()
{
	gtkshell -u vmstat
}
Dashboard()
{
	gtkshell\
 -g +0+0\
 -u\
 'date; uptime; vmstat; iostat -d wd0 wd1 wd2 wd3; envstat -r | grep Temp'
}
Alarm()
{
    local alarm_time="$($ARSHELL -l 'Alarm Time (ex 22:40):' -t echo)"
    if [ "$alarm_time" != "" ]; then
	$ARSHELL -l "Alarm Command:" -t echo | at "$alarm_time"
    fi
}

ACE_get_color()
{
    $ARSHELL -W $1 -At "$1 Value:" |  $AWK '{print $3}'
}
File_System_Panel()
{
    $ARSHELL -r 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 -r 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'
}

Uptime()
{
	arshell -u "$(uptime)"
}

IOStat()
{
	arshell -u "$(iostat)" 
}

Administration_Panel()
{
    $ARSHELL -r 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 -u sar
}
System_Accounting()
{
	if [ "$(which sar)" != "" ]; then
		Run_SAR
	else
		$ARSHELL -ADm 'SAR must be installed.' &
	fi
}
Secure_Permissions()
{
    chmod og-rwx ~/.*/*
}
See_All_Processes()
{
	gtkshell -u 'ps xau'
}
See_All_Users()
{
	gtkshell -u 'who'
}
See_Disk_Info()
{
	gtkshell -u 'df'
}
See_Open_Ports()
{
	nmap localhost > /tmp/nmap.$$
	ACE Terminal -e less /tmp/nmap.$$ 
	rm -f /tmp/nmap.$$
}
See_User_Processes()
{
	gtkshell -u '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 &
}
texted_base()
{
	$ARSHELL -Am -Aw -As -geometry 550x400 -xrm '*XmText.fontList: fixed' \
		-Amf 'ACE -A Text_Editor' $@
}
Text_Editor()
{
    local file


    if [ -z "$1" ]; then
	texted_base
    else
	file=$1

	if [ ! -f $file ]; then
	    touch $file
	fi

	cat $file | texted_base -p -W $file
    fi
}
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 +'
}
Show_Runlevel_Information()
{
    runlevel=$($ARSHELL -At "Runlevel:" | cut -d : -f 2)
    $ARSHELL -Al "$(ls /etc/init.d.d/rc${runlevel}.d)" -E "echo Dismiss"
}
SysV_Delete_Service()
{
    local runlevel=$($ARSHELL -At Runlevel:)
    rm /etc/init.d/rc${runlevel}.d/*${1}
}
SysV_Service()
{
    local order=$($ARSHELL -Al "Enter 'runlevel:order'"\
	-At "$1:" "ACE -A Show_Runlevel_Information"\
	"ACE -A SysV_Delete_Service $1" | cut -d : -f 2-)
    local runlevel=$(echo $order | cut -d : -f 1)
    local order=$(echo $order | cut -d : -f 2)
    cp /etc/init.d/$1 /etc/init.d/rc${runlevel}.d/S${order}${1}
}
SysV_Init()
{
    local service=$(ls /etc/init.d | grep -v '.d' | $ARSHELL -Am\
	-Aw -p -geometry 550x400 -At Modify: | cut -d : -f 2)
    if [ "$service" != "" ] && [ "$service" != "Dismiss" ]; then
	SysV_Service $service &
	SysV_Init &
    fi
}

# 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 -r 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()
{
	wc "$(ACE roff_file)"\
		| arshell -Aw -p
}
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()
{
	du -a | sort -n | tail -n\
	"$(gtkshell \
	-l 'Number of files to show'\
	-t echo)"
}
Show_Largest_Files()
{
	Get_Largest_Files\
		| arshell -Aw -p
}
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
}
Prompt_to_Clean()	
{
	local files="$(ACE -A \
		Get_Largest_Files)"
	echo $files | arshell -Aw -p &
	for file in "$files"; do
		ask_del $file
	done
}
IRC_Panel()
{
	arshell -r 4 \
		'ACE -A IRC_Kick' \
		'ACE -A IRC_Ban' \
		'ACE -A IRC_Topic' \
		'ACE -A IRC_Invite'\
		'ACE -A IRC_Mode'\
		'ACE -A X_Command'
}
X_Command()
{
	local command=\
	"$(arshell \
	-Al 'Enter the command to'\
	-Al 'pass to X'\
	-At Command:\
	| cut -d : -f 2)"
	echo "msg \
	X@channels.undernet.org\
	$command"
}
getirc()
{
	nick="$(ACE -A getircuser)"
	chan="$(ACE -A getircchan)"
}
IRC_Topic()
{
	getirc
	local topic=\
		"$(arshell -l Topic: -t echo)"
	echo "topic $chan $topic"
}
IRC_Kick()
{
	getirc
	echo "kick $chan $nick"
}
IRC_Ban()
{
	getirc
	echo "mode $chan +b $nick"
}
getircchan()
{
	arshell \
		-Al 'Enter the name of'\
		-Al 'the channel on which'\
		-Al 'you wishbto perform'\
		-Al 'an operation'\
		-At Channel: | cut -d : -f 2
}
getircuser()
{
	arshell \
		-Al 'Enter the user on'\
		-Al 'which you wish to'\
		-Al 'perform an operation.'\
		-At Nick: | cut -d : -f 2
}
IRC_Mode()
{
	echo "mode\
		$(arshell -At Object:\
		 | cut -d : -f 2) $(arshell \
		 -At Flag: | cut -d : -f 2) \
		$(arshell -At Value: \
		| cut -d : -f 2)"
		
}
IRC_Invite()
{
	getirc
	echo "$nick $channel"
}
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 -W Launch -ADp "$OPTARG:  ")
	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







