#!/bin/bash
#Automatically Created by buildpkg 1.4.3
#Maintainer: Godane <slaxemulator~at~gmail.com>
#url: http://italc.sourceforge.net/

######Begin Redundant Code######################################
check_for_root() {
	if [ "$UID" != "0" ]; then
		echo "You need to be root"
		exit 1
	fi
}

clean_dirs () {
        for COMPLETED in src pkg; do
                if [ -e $COMPLETED ]; then
                        rm -rf $COMPLETED
                fi
        done
}

clean_old_builds () {
	for COMPLETED in $package.{tgz,md5,dep}; do
		if [ "$KEEPDEPFILE" = "1" ] && [ $COMPLETED = $package.dep ]; then
			continue
		elif [ -e $COMPLETED ]; then
			rm -rf $COMPLETED
		fi
	done
	clean_dirs
}

set_pre_permissions() {
	cd $startdir/src
	find . -perm 664 -exec chmod 644 {} \;
	find . -perm 600 -exec chmod 644 {} \;
	find . -perm 444 -exec chmod 644 {} \;
	find . -perm 400 -exec chmod 644 {} \;
	find . -perm 440 -exec chmod 644 {} \;
	find . -perm 777 -exec chmod 755 {} \;
	find . -perm 775 -exec chmod 755 {} \;
	find . -perm 511 -exec chmod 755 {} \;
	find . -perm 711 -exec chmod 755 {} \;
	find . -perm 555 -exec chmod 755 {} \;
}


check_for_menu_compliance() {
	if [ -d "$startdir/pkg/usr/share/applications" ]; then
		cd $startdir/pkg/usr/share/applications
		for desktop in *.desktop; do
			Icon=$(grep -e "^Icon=" $desktop | sed 's/Icon=//')
			if [[ "$Icon" ]]; then
				if [ ! "$Icon" == "${Icon%.*}" ]; then
					sed '/Icon/s/\..*$//' -i $desktop
					Icon=$(grep -e "^Icon=" $desktop | sed 's/Icon=//')
				fi
				if [ -d "$startdir/pkg/usr/share/pixmaps" ]; then
					cd $startdir/pkg/usr/share/pixmaps
					for pixmaps in *; do
						[ -d $pixmaps ] && continue
						[ ! "${pixmaps##*.}" == "png" -a ! "${pixmaps##*.}" == "svg" ] && continue
				 		if [ "${pixmaps%.*}" == "$Icon" ]; then
				 			DIR=$(file $pixmaps | awk -F, '{print $2}' | sed 's/ //g')
							[ o"$DIR" == "o" ] && DIR="scalable"
							mkdir -p $startdir/pkg/usr/share/icons/hicolor/$DIR/apps
							mv $pixmaps $startdir/pkg/usr/share/icons/hicolor/$DIR/apps
							if [[ ! "$(ls $startdir/pkg/usr/share/pixmaps)" ]]; then
								rm -rf $startdir/pkg/usr/share/pixmaps
							fi
						fi
					done
				fi
				if [ -d "$startdir/pkg/usr/share/icons" ]; then
					cd $startdir/pkg/usr/share/icons
					for icons in *; do
				 		if [ "${icons%.*}" == "$Icon" ]; then
							[ ! "${pixmaps##*.}" == "png" -a ! "${pixmaps##*.}" == "svg" ] && continue
				 			DIR=$(file $icons | awk -F, '{print $2}' | sed 's/ //g')
							[ o"$DIR" == "o" ] && DIR="scalable"
							mkdir -p $startdir/pkg/usr/share/icons/hicolor/$DIR/apps
							mv $icons $startdir/pkg/usr/share/icons/hicolor/$DIR/apps
						fi
					done
				fi
			fi
		done
	fi
}


gzip_man_and_info_pages() {
	for DOCS in man info; do
		if [ -d "$startdir/pkg/usr/share/$DOCS" ]; then
			mv $startdir/pkg/usr/share/$DOCS $startdir/pkg/usr/$DOCS
			if [[ ! "$(ls $startdir/pkg/usr/share)" ]]; then
				rm -rf $startdir/pkg/usr/share
			fi
		fi
		if [ -d "$startdir/pkg/usr/$DOCS" ]; then
			# I've never seen symlinks in info pages....
			if [ "$DOCS" == "man" ]; then
				(cd $startdir/pkg/usr/$DOCS
				for manpagedir in $(find . -type d -name "man*" 2> /dev/null) ; do
					( cd $manpagedir
					for eachpage in $( find . -type l -maxdepth 1 2> /dev/null) ; do
						ln -s $( readlink $eachpage ).gz $eachpage.gz
						rm $eachpage
					done )
				done)
			fi
			find $startdir/pkg/usr/$DOCS -type f -exec gzip -9 '{}' \;
		fi
	done
}

set_post_permissions() {
	for DIRS in usr/share/icons usr/doc; do
		if [ -d "$startdir/pkg/$DIRS" ]; then
			if [ "$DIRS" == "usr/doc" ]; then
				find $startdir/pkg/$DIRS -type f -exec chmod 644 {} \;
				find $startdir/pkg/$DIRS -type d -exec chmod 755 {} \;
			fi
		fi
		[ -d $startdir/pkg/$DIRS ] && chown root:root -R $startdir/pkg/$DIRS
	done
	[ -d $startdir/pkg/usr/bin ] && find $startdir/pkg/usr/bin -user root -group bin -exec chown root:root {} \;
}

copy_build_script() {
	mkdir -p $startdir/pkg/usr/src/$pkgname-$pkgver/
	cp $startdir/build-$pkgname.sh $startdir/pkg/usr/src/$pkgname-$pkgver/build-$pkgname.sh
	[ -f $startdir/ZENBUILD ] && cp $startdir/ZENBUILD $startdir/pkg/usr/src/$pkgname-$pkgver/ZENBUILD
}

create_package() {
	cd $startdir/pkg
	/sbin/makepkg -l y -c n $startdir/$package.tgz
	cd $startdir
	md5sum $package.tgz > $startdir/$package.md5
}

strip_binaries() {
	cd $startdir/pkg
	find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | \
	xargs strip --strip-unneeded 2> /dev/null
	find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | \
	xargs strip --strip-unneeded 2> /dev/null
}
#########End Redundant Code#####################################
#########Begin Non Redundant Code##############################

prepare_directory() {
	mkdir $startdir/src
	mkdir -p $startdir/pkg/usr/src/$pkgname-$pkgver
	for SOURCES in ${source[@]}; do
		protocol=$(echo $SOURCES | sed 's|:.*||')
		if [ ! -f "$(basename $SOURCES)" ]; then
			if [ "$protocol" = "http" -o "$protocol" = "https" -o "$protocol" = "ftp" ]; then
				echo -e "\nDownloading $(basename $SOURCES)\n"
				wget $SOURCES
				if [ ! "$?" == "0" ]; then
					echo "Download failed"
					exit 2
				fi 
			else
				echo "$SOURCES does not appear to be a url nor is it in the directory"
				exit 2
			fi
		fi
		cp -R $(basename $SOURCES) $startdir/src
		if ! [ "$protocol" = "http" -o "$protocol" = "https" -o "$protocol" = "ftp" ]; then
			cp -R $startdir/$(basename $SOURCES) $startdir/pkg/usr/src/$pkgname-$pkgver/
		fi
		if [ "${SOURCES##*.}" == "desktop" ]; then
			[[ "$(grep -e "^Categories=[a-zA-Z]*;" $(basename $SOURCES))" ]] && install -D $startdir/$(basename $SOURCES) /mnt/sda3/source/italc/master/src/pkg/usr/share/applications/$(basename $SOURCES)
		fi
	done
}

extract_source() {
	cd $startdir/src
	if [[ "$(ls $startdir/src)" ]]; then	
		for FILES in ${source[@]}; do
			FILES="$(basename $FILES)"
			file_type=$(file -biz "$FILES")
			unset cmd
			case "$file_type" in
				*application/x-tar*)
					cmd="tar -xf" ;;
				*application/x-zip*)
					cmd="unzip" ;;
				*application/x-gzip*)
					cmd="gunzip -d -f" ;;
				*application/x-bzip*)
					cmd="bunzip2 -f" ;;
			esac
			if [ "$cmd" != "" ]; then
				echo "$cmd $FILES"
	        	        $cmd $FILES
			fi
		done
	elif [ ! "$source" ]; then
		echo -n "" # lame fix
	else
		echo "no files in the src directory $startdir/src"
		exit 2
	fi
}

build() {
	cd $startdir/src/italc-$pkgver
	./configure --prefix=/usr --localstatedir=/var --sysconfdir=/etc --with-linux --with-qtdir=/usr/lib/qt4
	make || return 1
	make install DESTDIR=$startdir/pkg
	mkdir -p $startdir/pkg/usr/share/icons/hicolor/48x48/apps
	mkdir -p $startdir/pkg/usr/share/icons/hicolor/128x128/apps
	mv $startdir/pkg/usr/share/icons/italc.png $startdir/pkg/usr/share/icons/hicolor/128x128/apps
	cp $startdir/italc.png $startdir/pkg/usr/share/icons/hicolor/48x48/apps
	sed -i "s_Icon=/usr/share/pixmaps/italc_Icon=italc_g" $startdir/pkg/usr/share/applications/italc.desktop
	sed -i "s_Exec=/usr/bin/italc_Exec=italc_g" $startdir/pkg/usr/share/applications/italc.desktop
	sed -i "s_Categories=Qt;KDE;Education;X-KDE-Edu-Teaching;_Categories=Applications;Network;_g" $startdir/pkg/usr/share/applications/italc.desktop
	rm $startdir/pkg/usr/bin/ica
	rm -R $startdir/pkg/usr/share/italc
	rm -R $startdir/pkg/usr/lib
	rm -R $startdir/pkg/usr/share/menu
	rm -f $startdir/pkg/usr/share/man/man1/ica.1
	
	# Create executable
	cat <<- "END" > $startdir/pkg/usr/bin/italc-start.sh
	#!/bin/bash
	if [ ! -d $HOME/.italc ]; then
		cat /usr/src/italc-master-$pkgver/help.txt | Xdialog --title "italc help" --left --textbox "-" 800x600;
		/usr/bin/italc;
		else /usr/bin/italc
	fi
	END
	chmod a+x $startdir/pkg/usr/bin/italc-start.sh

	# Modify .desktop file
	sed -i 's|Exec=italc %U|Exec=italc-start.sh|' \
		$startdir/pkg/usr/share/applications/italc.desktop	

} 

create_slackdesc() {
mkdir $startdir/pkg/install
cat <<"EODESC" >$startdir/pkg/install/slack-desc
italc-master: italc-master (Intelligent Teaching and Learning with Computers)
italc-master: 
italc-master: iTALC is a use- and powerful didactical tool for teachers. It lets 
italc-master: you view and control other computers in your network in several ways. 
italc-master: It supports Linux and Windows 2000/XP/Vista and it even can be used 
italc-master: transparently in mixed environments!
italc-master: 
italc-master: 
italc-master: 
italc-master: 
italc-master: 
EODESC
}

copy_docs() {
	for stuff in ${docs[@]}; do
		if [ ! -d "$startdir/pkg/usr/doc/$pkgname-$pkgver" ]; then
			mkdir -p $startdir/pkg/usr/doc/$pkgname-$pkgver
		fi
		find $startdir/src -type f -iname "$stuff" -exec cp -R '{}' $startdir/pkg/usr/doc/$pkgname-$pkgver \;
	done
}
detect_dependencies() {
	echo "Detecting dependencies..."
	depends=$(requiredbuilder -z $startdir/$package.tgz)
	depends="$(echo $depends | sed -e 's/\<glibc-solibs\>//' -e 's/,,/,/')"
	
	depstring=$depends,glibc,italc-client
	unset FIRST
	for deps in $(echo "${depstring}" | sed 's/,/\n/g' | sort -u); do
		if [[ ! "$FIRST" ]]; then
			finaldeps=$deps,
			FIRST='1'
			continue
		fi
		finaldeps=${finaldeps}${deps},
	done
	echo "$finaldeps" | sed -e 's/^,//' -e 's/,$//' > $startdir/$package.dep
}

####End Non Redundant Code############################

#Variables

startdir=$(pwd)
SRC=$startdir/src
PKG=$startdir/pkg

pkgname=italc-master
pkgver=1.0.7
pkgrel=1
zenver=52
arch=i486
package=$pkgname-$pkgver-$arch-$zenver.$pkgrel
source=(http://easynews.dl.sourceforge.net/sourceforge/italc/italc-1.0.7.tar.bz2 italc.png help.txt)
docs=(readme install copying changelog authors news todo)
export CFLAGS="-O2 -march=i486 -mtune=i686"
export CXXFLAGS="-O2 -march=i486 -mtune=i686"

#Execution

check_for_root
clean_old_builds
prepare_directory
extract_source
set_pre_permissions
build
if [ ! "$?" = "0" ]; then
	echo "build() failed."
	exit 2
fi
create_slackdesc
copy_docs
check_for_menu_compliance
strip_binaries
gzip_man_and_info_pages
set_post_permissions
copy_build_script
create_package
detect_dependencies
echo "Package has been built."
echo "Cleaning pkg and src directories"
clean_dirs
