#!/bin/bash
# Sunday, 04/25/2021

pth=`dirname "$1"`
if [ -z "$1" ]; then
	DIALOG=Xdialog
	$DIALOG   --rc-file /usr/share/pixmaps/colorboxDOH.rc  --icon /usr/share/pixmaps/doh.xpm  --title "DOH!" \
		--msgbox "\nFile to convert not found\n" 0 0
	exit 1
fi
cd $pth


echo 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAA
GXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAXpJREFUOI2lkLFqwmAUhc/fPxpS
DUiDU3V0EqRDBVdfQTo5uQkOgk+gr+Di6gM4OBSd1DdowUXQVRwSAlI0KGni6dKG/mgLtme7cM+5
37nAPyUAmAAeAcgrvScAr0LX9Rcp5Z2U8niNOwxDLQgCgVgs9r7ZbEiSruvS931eUhAEynw4HAiA
N1+J3W4X6XQauVwOjuMo1xaLBYrFInq93jnKF0GpVCIAAuBwOIwuzWYzZjIZAqCUkp1ORyGIAvr9
PnVdZ6FQ4Ha7JUkOBgNalhUFA6AQgo1Gg57nqRVqtRp2ux3m8zlSqRSWyyWm0ykqlYpCnM/nEYYh
xuOxWuEn+b6vEDSbzctP/KuUANu2MZlMopkk2u327wnfK7RaLWqaxnq9zvV6zWq1quBfqhAFrFYr
mqYZLRqGcWa+FCASiYRTLpffXNc1bNu+FUIwHo+fSIpPwnC/38eTyaQPAJZlHbPZ7N7zvNhoNLoX
AB4APAHQrvxfCOD5Ss+5PgD2lznepMOYHAAAAABJRU5ErkJggg==' | base64 -d > /tmp/icon.png

yy=`command -v inkscape`
if [ -z "$yy" ]; then	
	DIALOG=Xdialog
	$DIALOG   --rc-file /usr/share/pixmaps/colorboxDOH.rc  --icon /usr/share/pixmaps/doh.xpm  --title "DOH!" \
		--msgbox "\nInkscape is needed for this conversion.\n" 0 0
	exit 1
fi

# get rid of spaces in filename
newname="$(echo "$1" | sed 's/ /_/g')"
mv "$1" "$newname" 2> /dev/null
jname=`echo "$newname" | sed 's/\.ai/\.svg/I'`

FNAME=`basename "$newname" | cut -d. -f1`

# Convert 
$(sleep .5 && wmctrl -F -a 'Converting' -b add,above)&
inkscape "$newname" --actions="select-all;fit-canvas-to-selection;export-margin:8;export-type:svg;export-plain-svg; export-do" -o $newname \
| zenity --width=400 --title="Converting" --progress --pulsate --window-icon="/tmp/icon.png" --auto-close --text="\n\t\t\t\t<b>$FNAME</b>\n\n\t\t\t\tConverting AI to SVG\n"&
####  THE REST of this simply stops the conversion if the dialog is cancelled #########
# get zenity process id
PID_ZENITY=${!}
# get firstly created child process id, which is running all tasks
PID_CHILD=$(pgrep -o -P $$)
# loop to check that progress dialog has not been cancelled
while [ "$PID_ZENITY" != "" ]
do
  # get PID of all running tasks
  PID_TASKS=$(pgrep -d ' ' -P ${PID_CHILD})
  # check if zenity PID is still there (dialog box still open)
  PID_ZENITY=$(ps h -o pid --pid ${PID_ZENITY} | xargs)
  # sleep for 2 second
  sleep 1
done
# since dialog is finished or cancelled...
killall -9 inkscape 2>/dev/null
###################################################################

rm /tmp/icon.png 2>/dev/null
echo "Conversion complete"
exit 0
