#!/bin/sh
# revision 2 
# 01micko 131202
# the design is so it can be called from a pinstall.sh, or even
# 3builddistro in woof and it can also run interactively so that
# users can roll their own easily.

ver=0.1

# target and temporary writing place
TARGET=$XDG_CONFIG_HOME/autostart
TMP=/tmp/${RANDOM}

err()
{
	echo "error in name" 
	exit 1
}

desktop_func()
{
	# sanity check - first char must be alpha
	echo ${thename::1} | grep -q [a-zA-Z] || err
	# build the file
	echo -e \
	"[Desktop Entry]\nEncoding=UTF-8\nType=Application\nNoDisplay=true" > $TMP
	echo "Name=${thename}" >> $TMP
	echo -n "Exec=${thename}" >> $TMP
	[ "$option" ] && echo -n " "$option"" >> $TMP
	echo "" >> $TMP # carriage return
}

usage_func()
{
	echo -e "${0##*/}-${ver} - creates simple desktop files for autostart.\n"
	echo -e "\t${0##*/} [executable_name] [-option(s)] :\n\t\t- automatically \
creates \n\t\t\"[executable_name].desktop\" in \$XDG_CONFIG_HOME/autostart/ \
	\n\t\twith optional arguments, useful if called from a script. \
	\n\t\tSpecial characters (\",*,\,$) need to be escaped."
	echo -e "\t${0##*/} :\n\t\t- runs this script interactiveley in virtual terminal."
	exit 0
}

interactive()
{
	# loop to get sane input
	echo "Type the name of executable that you want to autostart, NO SPACES"
	while [ 1 ];do
	 read thename
	 case $thename in
	 "")echo "try again" && continue ;;
	 *)echo "$thename" | grep -q " " && continue || break;;
	 esac
	done
	echo
	
	echo -e "Now, optionally, you can pass paramaters to the executable. \
	\nIf you don't know, leave this field blank. \
	\nEXAMPLE: \
	\nIn the case of retrovol you would probably want to pass the \"-hide\" \
option. \
	\nType it without quotes and press ENTER, or ENTER only for no options."
	read option
	
	desktop_func
	
	echo -e "\nBelow is the entry to be written to ${thename}.desktop. \
	\nDoes this look OK?\n"
	echo -en "\033[0;34m" #blue text
	cat $TMP
	echo -e "\033[0m" #unset blue text
	echo
	echo -e "If not hit ENTER to quit without writing the file or \
	\nhit \"W\" and ENTER to write the file and exit."
	read writeit
	case $writeit in
	 w|W)cat $TMP > $TARGET/${thename}.desktop # writes the file
	 echo "File is written to $TARGET/${thename}.desktop." ;;
	 *)echo "Not writing file." ;;
	esac
	rm $TMP
	exit 0
}

case "$@" in
 -h|-*help)usage_func;;
 "")interactive ;;
 *)thename=$1
   #echo "$@"
   option=`echo "$@"|sed -e "s'$thename''" \
                          -e "s'^ ''" \
                          -e 's#"#\\"#g'`
   [ "$thename" = "$option" ] && option=
   desktop_func
   cat $TMP > $TARGET/${thename}.desktop # writes the file
   rm $TMP
esac
