#!/bin/bash
#Automatically Created by slkbuild 0.5.1
#Maintainer: Maximus (maximuus[at]gmail[dot]com)
#url: http://earth.google.com/index.html

######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 () {
	rm -rf $package.{t[xlgb]z,md5}
	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 {} \;
}


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
	[ -a $startdir/pkg/usr/info/dir.gz ] && rm -f $startdir/pkg/usr/info/dir.gz
}

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/SLKBUILD ] && cp $startdir/SLKBUILD	$startdir/pkg/usr/src/$pkgname-$pkgver/SLKBUILD
}

create_package() {
	ls -lR $startdir/pkg
	cd $startdir/pkg
	/sbin/makepkg -l y -c n $startdir/$package.txz
	cd $startdir
	md5sum $package.txz > $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|:.*||')
	        file=$(basename $SOURCES | awk -F= '{print $NF}')
		if [ ! -f "$file" ]; then
			if [ "$protocol" = "http" -o "$protocol" = "https" -o "$protocol" = "ftp" ]; then
				echo -e "\nDownloading $(basename $SOURCES)\n"
        	                wget $SOURCES -O $file
				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 $file $startdir/src
		if ! [ "$protocol" = "http" -o "$protocol" = "https" -o "$protocol" = "ftp" ]; then
			cp -R $startdir/$(basename $SOURCES) $startdir/pkg/usr/src/$pkgname-$pkgver/
		fi
	done
}

extract_source() {
	cd $startdir/src
	if [[ "$(ls $startdir/src)" ]]; then	
		for FILES in ${source[@]}; do
	        	FILES="$(basename $FILES | awk -F= '{print $NF}')"
			file_type=$(file -biz "$FILES")
			unset cmd
			case "$file_type" in
				*application/x-tar*)
					cmd="tar -xf" ;;
				*application/x-zip*)
					cmd="unzip" ;;
				*application/zip*)
					cmd="unzip" ;;
				*application/x-gzip*)
					cmd="gunzip -d -f" ;;
				*application/x-bzip*)
					cmd="bunzip2 -f" ;;
				*application/x-xz*)
					cmd="xz -d -f" ;;
				*application/x-lzma*)
					cmd="lzma -d -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() {
	# Copyright 2007-2009  Michiel van Wessem, Manchester, United Kingdom
	# All rights reserved.
	#
	# Redistribution and use of this script, with or without modification, is
	# permitted provided that the following conditions are met:
	#
	# 1. Redistributions of this script must retain the above copyright
	#    notice, this list of conditions and the following disclaimer.
	#
	# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
	# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
	# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
	# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
	# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
	# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
	# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
	# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
	# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
	# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	#
	# Thanks to rworkman for the additional code and script cleanups
	# and to Daniel de Kok and Alan_Hicks for their comments.
	
	#create directory structure
	mkdir -p $startdir/pkg/usr/{bin,doc,share}
	mkdir $startdir/pkg/usr/share/{applications,googleearth,mime}
	mkdir -p $startdir/pkg/usr/share/icons/hicolor/48x48/apps
	
	#extract source
	sh $startdir/src/GoogleEarthLinux.bin --noexec --target $startdir/pkg/usr/share/googleearth
	cd $startdir/pkg/usr/share/googleearth
	tar xf googleearth-data.tar
	tar xf googleearth-linux-x86.tar
	rm {googleearth-linux-x86.tar,googleearth-data.tar}
	
	#move docs
	mv {README.linux,gpl.txt} $startdir/pkg/usr/doc
	
	#move, modify and link executable
	cat bin/googleearth | sed '/# Set the home/a\GOOGLEEARTH_DATA_PATH=/usr/share/googleearth/' > googleearth || exit 1
	rm -rf bin 
	cd $startdir/pkg/usr/bin
	ln -s ../share/googleearth/googleearth googleearth || exit 1
	
	#move icon
	mv $startdir/pkg/usr/share/googleearth/googleearth-icon.png $startdir/pkg/usr/share/icons/hicolor/48x48/apps/googleearth.png
	
	#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
	find . | xargs file | grep "current ar archive" | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
	
	#create .desktop
cat > $startdir/pkg/usr/share/applications/googleearth.desktop << EOF
[Desktop Entry]
Encoding=UTF-8
Name=Google Earth
GenericName=3D planet viewer
Comment=Explore, search and discover the planet
Exec=googleearth %f
Terminal=false
MultipleArgs=false
Type=Application
Icon=googleearth
Categories=Application;Network
MimeType=application/vnd.google-earth.kml+xml;application/vnd.google-earth.kmz;application/earthviewer;application/keyhole
EOF

	#add mime info
cat > $startdir/pkg/usr/share/mime/googleearth-mimetypes.xml << EOF
<?xml version="1.0"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
  <mime-type type="application/vnd.google-earth.kml+xml">
    <comment>Keyhole Markup Language data</comment>
    <glob pattern="*.kml"/>
  </mime-type>

  <mime-type type="application/vnd.google-earth.kmz">
    <comment>Keyhole Markup Language archive</comment>
    <glob pattern="*.kmz"/>
  </mime-type>

  <mime-type type="application/keyhole">
    <comment>Keyhole Markup Language data</comment>
  </mime-type>

  <mime-type type="application/earthviewer">
    <comment>Keyhole Markup Language data</comment>
  </mime-type>
</mime-info>
EOF

	#verify permissions
	cd $startdir/pkg
	chown -R root:root .
	find . -perm 666 -exec chmod 644 {} \;
	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 {} \;
	find . \( -name "*.png" -o -name "*.kml" -o -name "*.xml" \) -exec chmod 644 {} \;


	#remove fluff
	rm -f $startdir/pkg/usr/share/googleearth/{preuninstall,setup,postinstall}.sh
	rm -rf $startdir/pkg/usr/share/googleearth/setup.data
	rm -rf $startdir/pkg/usr/share/googleearth/linux
}

create_slackdesc() {
mkdir $startdir/pkg/install
cat <<"EODESC" >$startdir/pkg/install/slack-desc
googleearth: googleearth - a virtual globe, map and geographic information program
googleearth: 
googleearth: Google Earth lets you fly anywhere on Earth to view satellite imagery,
googleearth: maps, terrain, 3D buildings, from galaxies in outer space to the
googleearth: canyons of the ocean. You can explore rich geographical content, save
googleearth: your toured places, and share with others.
googleearth: NOTE: This program may not be stable on machines with certain
googleearth: combinations of hardware. It may crash itself and/or cause X to crash
googleearth: 
googleearth: 
googleearth: 
EODESC
}

setup_doinst() {
cat <<"EODOINST" >>$startdir/pkg/install/doinst.sh
doinst() {
		if [ -x usr/bin/update-desktop-database ]; then
			usr/bin/update-desktop-database -q ./usr/share/applications >/dev/null 2>&1
		fi
		if [ -x usr/bin/update-mime-database ]; then
			usr/bin/update-mime-database ./usr/share/mime >/dev/null 2>&1
		fi		
}
doinst
EODOINST
}
create_source_file(){
	[ -f $package.src ] && rm $package.src
	if [ ! -z $sourcetemplate ]; then
		echo $sourcetemplate/SLKBUILD >> $package.src
		echo $sourcetemplate/build-$pkgname.sh >> $package.src
		for SOURCES in ${source[@]}; do
			protocol=$(echo $SOURCES | sed 's|:.*||')
			if ! [ "$protocol" = "http" -o "$protocol" = "https" -o "$protocol" = "ftp" ]; then
				if [ ! -z $sourcetemplate ]; then
					echo $sourcetemplate/$(basename $SOURCES) >> $package.src
				else
					echo $(basename $SOURCES) >> $package.src
				fi
			else
				echo $SOURCES >> $package.src
			fi
		done
	fi
}
post_checks(){
	# Ideas taken from src2pkg :)
	if [ -d "$startdir/pkg/usr/doc/$pkgname-$pkgver" ]; then
		for DIRS in usr/doc/$pkgname-$pkgver usr/doc; do
			cd $startdir/pkg/$DIRS
			if [[ $(find . -type f) = "" ]] ; then
				cd ..
				rmdir $DIRS
			fi
		done
	fi
	# if the docs weren't deleted ...
	if [ -d "$startdir/pkg/usr/doc/$pkgname-$pkgver" ]; then
		cd $startdir/pkg/usr/doc/$pkgname-$pkgver
		#remove zero lenght files
		if [[ $(find . -type f -size 0) ]]; then
			echo "Removing some zero lenght files"
			find . -type f -size 0 -exec rm -f {} \;
		fi
	fi
	# check if we need to add code to handle info pages
	if [[ -d $startdir/pkg/usr/info ]] && [[ ! $(grep install-info $startdir/pkg/install/doinst.sh &> /dev/null) ]] ; then
		echo "Found info files - Adding install-info command to doinst.sh"
		INFO_LIST=$(ls -1 $startdir/pkg/usr/info)
		echo "" >> $startdir/pkg/install/doinst.sh
		echo "if [ -x usr/bin/install-info ] ; then" >> $startdir/pkg/install/doinst.sh
		for page in $(echo $INFO_LIST) ; do
			echo " usr/bin/install-info --info-dir=usr/info usr/info/$page 2>/dev/null" >> $startdir/pkg/install/doinst.sh
		done
		echo "fi" >> $startdir/pkg/install/doinst.sh
	fi
	[[ -e $startdir/pkg/usr/info/dir ]] && rm -f $startdir/pkg/usr/info/dir

	if [ -d $startdir/pkg/etc ]; then
		cd $startdir/pkg/
		for conf in $(find ./etc -type f) ; do
			conf=${conf: 2}
			dotnew=( "${dotnew[@]}" "$conf" )
		done
	fi
	if [[ "$dotnew" ]]; then
        for files in ${dotnew[@]} ; do
                fullfile="${startdir}/pkg/${files}"
                if [ -e "$fullfile" ]; then
                        mv $fullfile ${fullfile}.new
                else
                        echo "$fullfile was not found"
                        exit 2
                fi
        done
        cat<<"EODOTNEW" >>$startdir/pkg/install/doinst.sh
#Added by slkbuild 0.5.1
dotnew() {
        NEW="${1}.new"
        OLD="$1"
        if [ ! -e $OLD ]; then
                mv $NEW $OLD
        elif [ "$(cat $OLD | md5sum)" = "$(cat $NEW | md5sum)" ]; then
                rm $NEW
        fi
}
EODOTNEW
for i in ${dotnew[@]}; do
echo "dotnew $i" >> $startdir/pkg/install/doinst.sh
done
fi
}

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

#Variables

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

pkgname=googleearth
pkgver=5.1.3509.4636.1
pkgrel=1mb
arch=i486
package=$pkgname-$pkgver-$arch-1mb
source=("http://dl.google.com/earth/client/current/GoogleEarthLinux.bin")
sourcetemplate=http://people.salixos.org/maximuus/googleearth/5.1.3509.4636.1
docs=()
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
post_checks
setup_doinst
strip_binaries
gzip_man_and_info_pages
set_post_permissions
copy_build_script
create_package
create_source_file
echo "Package has been built."
echo "Cleaning pkg and src directories"
clean_dirs
