#!/bin/bash

# This simple script is used to get the current K3b version from CVS and compile 
# it. Do not expect wonders, the CVS version may not even compile, that's why it
# is called "development version".
#
# After this script finishes its work (and if all goes well) you may just issue
# a 'make install'.
#
# If you have Red Hat 9, check for some rpms at
#  http://fenrir.infoiasi.ro/~xcyborg/k3b
#
# Mihai Maties <mihai@xcyb.org>

scriptversion="v0.3"

function ShowHelp () {
    cat <<END
  -c		  the equivalent of a 'make clean' command
  -d workdir	  the 'workdir' directory is used as working directory
		  instead of current directory
  -e              save a spec file for a final K3b version to the current 
                  directory
  -h|--help	  this help screen
  -i		  compiles and installs the latest version of K3b on your
		  system ( the equivallent of './configure && make &&
		  make install' )
  -j 		  select 'tar.bz2' output format ( default option )
  -m		  compiles the K3b snapshot ( the equivallent of
		  './configure && make' )
  -p patchfile	  apply 'patchfile' to the sources. The patch is applied in
		  the top level directory with the '-p1' paramater ( see
		  'man patch' for more info )
  -s		  select 'src.rpm' output format
  -o outputdir 	  write the output file into the specified directory
  -v		  verbose
  -z 		  select 'tar.gz' output format
  
END
    exit 0
}

function InCaseOfError () {
    [ $? -ne 0 ] && echo -e ERROR: $1 && exit $2
}

function Verbose () {
    [[ $verbose == "v" ]] && echo -e "$(echo -e "$1"|sed -e 's/^/v> /')"
}

function CheckClean () {
[[ $(find $dirname -name "*.la"|wc -l) -ne 0 ]] && \
    echo "Warning: This directory holds binary objects from a previous 'make'."\
	"Since you are creating an archive you should eliminate the stale objects"\
	"by issuing the '-c' (make clean) flag. If you don't do it the resulting"\
	"archive will be bigger."
}

function DumpSpec () {
cat <<\END > k3b.spec

%define name    k3b
%define version xversion
%define release xrelease
%define cvs yes

%define linux_distribution %(%{_sourcedir}/linuxdist.sh)

%define _rpmfilename %%{ARCH}/%%{NAME}-%%{VERSION}-%%{RELEASE}%(%{_sourcedir}/linuxdist.sh).%%{ARCH}.rpm

Summary:        Excellent CD-Burner for KDE3
Name:           k3b
Version:        %{version}
Release:        %{release}.xcyb.9
Epoch:		1
License:        GPL
Vendor:         Sebastian Trueg <trueg@k3b.org>
URL:            http://www.k3b.org
Packager:       Mihai Maties <mihai@xcyb.org>
Group:          Applications/Multimedia
Source:         xsource
Source1:	linuxdist.sh
#Patch0:	k3b-desktop-files.patch
BuildRoot:      %{_tmppath}/%{name}-%{version}
Prefix:         %(kde-config --prefix)
Provides:       cd-burner
Requires:       cdrecord >= 2.0, mkisofs >= 2.0, cdrdao >= 1.1, kdelibs >= 3.1, libsndfile, libsamplerate
BuildRequires:  kdelibs-devel >= 3.1, qt-devel, audiofile-devel, XFree86-devel, libsamplerate-devel
BuildRequires:	libart_lgpl-devel, libpng-devel

# Unfortunately the --without-libmad and --without-libvorbis options do not work
# because Sebastian always enables it if it's available.
# ( also the --without-arts parameter seems to be ignored, so actually only
#   --without-k3bsetup does work )
%{!?_without_libmad:Requires: libmad, id3lib}
%{!?_without_libmad:BuildRequires: libmad-devel, id3lib-devel}
%{!?_without_libogg:Requires: libvorbis, libogg}
%{!?_without_libogg:BuildRequires: libvorbis-devel, libogg-devel}
%{!?_without_arts:Requires: arts}
%{!?_without_arts:BuildRequires: arts-devel}


%description
K3b - The CD Creator - Writing cds under linux made easy. It has an extremely
easy to use interface and supports many features: data/audio/video/mixed
[on-the-fly] CD burning, CD copying, erasing and ripping, CD-text writing,
burning iso/bin-cue images and many more.

if [[ %{cvs} == 'yes'  ]]; then %define ldir "kdeextragear-1/k3b/"
fi

%prep
%setup
if [[ %{cvs} == 'yes'  ]]; then cd kdeextragear-1; fi
#%patch -p1

%build

if [[ %{cvs} == 'yes'  ]]; then cd kdeextragear-1; fi
#WANT_AUTOCONF_2_5=1 make -f admin/Makefile.common
CFLAGS="$RPM_OPT_FLAGS" CXXFLAGS="$RPM_OPT_FLAGS" \
./configure \
                 --prefix=%{prefix} \
	         %{?_without_k3bsetup:--without-k3bsetup} \
	         %{?_without_libmad:--without-libmad} \
	         %{?_without_arts:--without-arts} \
                $LOCALFLAGS
# Setup for parallel builds
numprocs=`egrep -c ^cpu[0-9]+ /proc/stat || :`
if [ "$numprocs" = "0" ]; then
  numprocs=1
fi

make -j$numprocs

%install
if [[ %{cvs} == 'yes'  ]]; then cd kdeextragear-1; fi

make install-strip DESTDIR=$RPM_BUILD_ROOT

# We don't install the files directly to avoid conflicts with other
# packages (e.g. kde3.2)
cd $RPM_BUILD_ROOT/usr/share/mimelnk/application/
mv x-cue.desktop x-cue.desktop.k3b
mv x-iso.desktop x-iso.desktop.k3b

desktop-file-install --vendor xcyborg --delete-original\
  --dir $RPM_BUILD_ROOT%{_datadir}/applications\
  --add-category X-Red-Hat-Base\
  --add-category Application\
  --add-category System\
  --add-category AudioVideo\
  $RPM_BUILD_ROOT%{_datadir}/applnk/Multimedia/%{name}.desktop

desktop-file-install --vendor kde --delete-original \
  --dir $RPM_BUILD_ROOT%{_datadir}/applications \
  --add-category X-KDE-System \
  --add-category Application \
  --add-category System \
  $RPM_BUILD_ROOT%{_datadir}/applnk/Settings/System/k3bsetup2.desktop

rm -rf $RPM_BUILD_ROOT%{_datadir}/applnk

cd $RPM_BUILD_ROOT

install -D -m 644 $RPM_BUILD_ROOT/usr/share/icons/crystalsvg/48x48/apps/k3b.png \
  $RPM_BUILD_ROOT/usr/share/pixmaps/k3b.png

find . -type d | sed '1,2d;s,^\.,\%attr(-\,root\,root) \%dir ,' > $RPM_BUILD_DIR/file.list.k3b
find . -type f | sed 's,^\.,\%attr(-\,root\,root) ,' >> $RPM_BUILD_DIR/file.list.k3b
find . -type l | sed 's,^\.,\%attr(-\,root\,root) ,' >> $RPM_BUILD_DIR/file.list.k3b

%clean
rm -rf $RPM_BUILD_ROOT
rm -rf $RPM_BUILD_DIR/%{name}-%{version}
rm -rf ../file.list.k3b

%post
# Workaround: if x-iso|cue.desktop files were installed by another package (e.g. kde3.2)
# then don't mess with it - else install them
cd %{_datadir}/mimelnk/application
[ ! -f x-cue.desktop ] && cp -f x-cue.desktop.k3b x-cue.desktop || :
[ ! -f x-iso.desktop ] && cp -f x-iso.desktop.k3b x-iso.desktop || :

%postun
# Workaround: if x-iso|cue.desktop files were installed by another package (e.g. kde3.2)
# then don't remove them
cd %{_datadir}/mimelnk/application
rpm -qf %{_datadir}/mimelnk/application/x-cue.desktop &>/dev/null || rm -f x-cue.desktop
rpm -qf %{_datadir}/mimelnk/application/x-iso.desktop &>/dev/null || rm -f x-iso.desktop


%files -f ../file.list.k3b
%doc "%{ldir}AUTHORS"
%doc "%{ldir}COPYING"
%doc "%{ldir}ChangeLog"
%doc "%{ldir}FAQ"
%doc "%{ldir}INSTALL"
%doc "%{ldir}README"
%doc "%{ldir}TODO"


%changelog
xchangelog

* Wed Jan 21 2004 - Mihai Maties <mihai@xcyb.org> - k3b-*
- added a define (%CVS) to be able to build stable and CVS versions with the same 
spec

* Thu Jan 10 2004 - Mihai Maties <mihai@xcyb.org> - k3b-0.10.3-2.xcyb.9.*
- install x-iso and x-cue mimelinks only if needed to avoid conflicts with other
packages (e.g. kde3.2)
- install 'k3b setup 2' as a standalone application in K/System Tools/ 
- added a few translations to the desktop files

* Thu Nov 13 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10.2-3.xcyb.8.*
- added small script (linuxdist.sh) that determines the linux distribution
the package was built on and adds it to the name of the rpm (fc1, rh9, mdk82 etc)
- fixed yet another bug with BuildRequires ( I need to get some sleep ... )
- removed my k3bsetup2.desktop file from the package / now using the original
one from the kit

* Thu Nov 13 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10.2-2.xcyb.7.rh9
- fixed some bugs with BuildRequires
- added libart_lgpl and XFree86-devel to BuildRequires

* Fri Oct 31 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10.1-2.xcyb.6.rh9
- added --without-libmad , --without-k3bsetup and --without-arts options
- added requirements for libmad* , libvorbis* and libogg*

* Mon Oct 27 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10.1-1.xcyb.5.rh9
- increased Epoch value to 1 to increase priority of this package over other ones
(this rpm is suppose to be more up to date with K3b changes )

* Thu Oct 16 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10-2.xcyb.4.rh9
- "manually" added k3bsetup2 to KDE's Control Center

* Thu Oct 09 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10-1.xcyb.3.rh9
- corrected some issues in the "clean" section

* Tue Aug 19 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10-CVS.20030819.xcyb.3.rh9
- added patch file that fixes a compile error on many systems
- rebuilt

* Wed Aug 06 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10-CVS.20030801.xcyb.3.rh9
- added audiofile-devel to BuildRequires

* Sat Aug 02 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.10-CVS.20030801.xcyb.2.rh9
- adapted spec file for CVS release

* Fri Jul 19 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.9-2.rh9
- changed rpm name to reflect the release, too
- added "requires" and "provides" tags
- added "conflict" tag with arson (because of the mimetypes files)
- added separate doc directive to correctly mark appropriate files as documentation
- added patch file which:
  - removes wrong Categories from the original k3b.desktop file
  - adds romanian translation to the desktop-files

* Tue Jul 15 2003 - Mihai Maties <mihai@xcyb.org> - k3b-0.9.rh9
- initial rpm release

END

}

function SaveSpecToCurDir () {
    DumpSpec
    changelogdate=`date +"%a %b %d %Y"`
    k3bversion="xversion"
    srpmname="k3b-${k3bversion}.xcyb.9.*"
    changelogentry="* $changelogdate - Mihai Maties <mihai@xcyb.org> - $srpmname\n\
- spec automatically generated with K3b CVS \"snapshooter\" $scriptversion"
    sed -i -e "s/xversion/${k3bversion}/;\
	s/xchangelog/${changelogentry}/;\
	s/cvs yes/cvs no/;\
        s/xsource/k3b-%{version}-%{release}.tar.bz2/" k3b.spec
    
    echo "Spec file saved to $PWD/k3b.spec"
    echo "NOTE: You must edit the spec file and replace 'xversion' with the actual version"
    echo "      and 'xrelease' with the actual release."
}

cat <<END
K3b CVS "snapshooter" $scriptversion - Mihai Maties <mihai@xcyb.org>
http://fenrir.infoiasi.ro/~xcyborg/k3b/

END

function InfoSnapshot () {
cat <<END
This snapshot was made using K3b CVS "snapshooter" $scriptversion by 
Mihai Maties <mihai@xcyb.org> . The latest version of the 
script can be found on http://fenrir.infoiasi.ro/~xcyborg/k3b/

Info about the person who took the snapshoot:
User: $USER
Name: $(finger $USER|grep Name:|sed -e 's/.*Name: //')
Host: $HOSTNAME
Date: $(date)

END
if [[ -n $patchfile ]]
then
    pushd $initialdir >/dev/null
    echo "The following patch was applied to the original CVS sources:"
    echo "<--- cut here --->"
    cat $patchfile
    echo "</--- cut here --->"
    popd >/dev/null
else
    echo "No patch was applied to the original CVS sources"
fi
}

# In case you need --help
if [[ $1 == "--help" ]]
then
    ShowHelp
fi

# Setting default values
initialdir=$PWD
outputdir=$initialdir
compress="no"
action="no action"
clean="no"
srpm="no"
umask 022

# Checking command line options
while getopts ":-cd:ehijmo:p:svz" Option
do
  case $Option in
    c     ) clean="yes";;
    d	  ) initialdir=$OPTARG; cd $initialdir; initialdir=$PWD;;
    e	  ) SaveSpecToCurDir; exit 0;;
    h     ) ShowHelp;;
    i     ) action="install";;
    j     ) compress="j";;
    m     ) action="make";;
    o     ) outputdir=$OPTARG;;
    p	  ) patchfile=$OPTARG;;
    s     ) srpm="yes";;
    v     ) verbose="v";;
    z     ) compress="z";;
    *     ) echo "What ? You need --help."; exit 0;;
  esac
done
Verbose "Setting default values:\n initialdir='$initialdir'\n \
outputdir='$outputdir'"
Verbose "Checking command line options"

# Checking if the current directory already contains a k3b CVS dir structure
dirname=`find . -name "k3b*" -type d -maxdepth 1 -printf %P`
Verbose "Checking for an existing k3b- directory"
if [ -z $dirname ]
then # there is no k3b* dir, so we create one
    Verbose " ...not found."
    echo "Creating 'k3b-CVS' directory ..."
    mkdir k3b-CVS
    dirname="k3b-CVS"
else
    Verbose " ...found $dirname"
fi

cd $dirname
echo "Running cvs in ${PWD}/ ..."

cvs -d:pserver:anonymous:@anoncvs.kde.org:/home/kde login
cvs -d:pserver:anonymous@anoncvs.kde.org:/home/kde -z4 -q co -P kdeextragear-1/k3b
cvs -d:pserver:anonymous@anoncvs.kde.org:/home/kde -z4 -q co -P -l kdeextragear-1
cvs -d:pserver:anonymous@anoncvs.kde.org:/home/kde -z4 -q co -P kde-common

InCaseOfError "Could not complete CVS snapshot." 1
InfoSnapshot > INFO-SNAPSHOT

# Looking for the actual version that we just downloaded
maincpp=`find . -regex '.*k3b/src/main.cpp'`
Verbose "Looking for the actual version that we just downloaded."
Verbose " Trying to locate k3b/src/main.cpp to extract version."
if [[ -n $maincpp ]]
then # we found the file containing the version number, extracting it
    Verbose " File found: $maincpp"
    k3bversion=`egrep '".*", description' $maincpp | cut -d\" -f2`
    if [[ -n $k3bversion ]]
    then # we found the version
	k3bversion=$( echo $k3bversion|sed -e 's/-//' )
	k3bversion=$( echo $k3bversion|sed -e 's/cvs//i' )
	Verbose " The version is $k3bversion."
	finaldir="k3b-$k3bversion"
	if [[ $finaldir != $dirname ]]
	then # the k3b version changed, setting the apropriate directory
	    echo -n "The k3b version changed since the last snapshot," \
		"renaming the directory accordingly: "
	    cd ..
	    mv -f $dirname $finaldir
	    echo "$dirname -> $finaldir"
	    dirname=$finaldir
	    cd $dirname
	else
	    Verbose " The k3b version did not change since the last snapshot, using the same dir name"
	fi
    else
	Verbose "Could not determine the version, using the old $dirname name"
    fi
fi

if [[ -n $patchfile ]]
then
    cd $initialdir
    echo "Applying patch $patchfile in ${initialdir}/${dirname}/ ... "
    patch -p1 -N < $patchfile -d $dirname
    cd $dirname
fi

cd kdeextragear-1
[ ! -L admin ] && ln -fs ../kde-common/admin
make -f Makefile.cvs
cd $initialdir


# Create an archive only if no parameter (-c|-i|-m) was specified on the
# command line or if it was a explicit request (-j|-z)

if [[ $action == "no action" && $clean == "no" && \
    $srpm != "yes" || $compress != "no" ]]
then
    # Executing make clean if -c was specified
    # ( it's a bad idea to include .objects in the archive )
    [[ $clean == "yes" ]] && cd ${dirname} && make clean && cd ..

    [ $compress == "no" ] && compress="j"

    # Getting current date
    timestamp=`date +%Y%m%d`

    # Creating archive with an easy to understand name
    # (if the dir containing K3b already contains 'CVS' in its name, strip it)
    filename=$(echo $dirname|sed -e 's/.CVS//').CVS.$timestamp.tar
    if [ "$compress" == "j" ]
    then
        filename=${filename}.bz2
	echo "Creating bzip2 archive ..."
    else
        filename=${filename}.gz
	echo "Creating gzip archive ..."
    fi
    CheckClean
    outputdir=`echo $outputdir | sed -e 's/\/$//'`
    tar -c${compress}${verbose}f "${outputdir}/$filename" $dirname
    [ $? -eq 0 ] && echo "Wrote ${outputdir}/$filename"
fi


if [[ $srpm == "yes" ]]
then
    if ! echo $filename|egrep "bz2$">/dev/null
    then
        # Executing make clean if -c was specified
	# ( it's a bad idea to include .objects in the src.rpm )
        [[ $clean == "yes" ]] && cd ${dirname} && make clean && cd ..

        # Getting current date
	timestamp=`date +%Y%m%d`
        filename=$(echo $dirname|sed -e 's/.CVS//').CVS.$timestamp.tar
        filename=${filename}.bz2

	#echo "Creating bzip2 archive ..."
	CheckClean
	outputdir=`echo $outputdir | sed -e 's/\/$//'`
	tar -cj${verbose}f "${outputdir}/$filename" $dirname
	deletefile="yes"
    fi
    cd $outputdir

DumpSpec

cat <<\END > linuxdist.sh
#!/bin/sh

# Simple sh script that determines the Linux distribution and generates
# a release token to be used in the names of rpms
#
# Mihai Maties <mihai@xcyb.org>

# Samples :
#release="Fedora Core release 1 (Yarrow)"
#release="Mandrake Linux release 9.2 (FiveStar) for i586"
#release="Red Hat Linux release 9 (Shrike)"
#release="Yellow Dog Linux release 2.3 (Dayton)"
#release="UnitedLinux 1.0 (i386)"
#release="SuSE Linux 8.2 (i586)"
#release="Red Hat Enterprise Linux ES release 3 (Taroon)"

release=$(cat `echo /etc/*release|tr ' ' '\n'|grep -v lsb|head -1`)
dist=`echo $release|sed -re 's/(.*) (release|Linux).*/\1/;s/ *Linux.*//'`
version=`echo $release|sed -re 's/([a-zA-Z]| )*\ (([0-9]|\.)*) .*/\2/;s/\.//'`

case "$dist" in
    "Red Hat" ) dist=".rh";;
    "Fedora Core" ) dist=".fc";;
    "SuSE" ) dist=".suse";;
    "Mandrake" ) dist=".mdk";;
    "United" ) dist=".ul";;
    "Yellow Dog" ) dist=".yd";;
    "Red Hat Enterprise" ) dist=".rhel";;
esac
echo $dist$version
END

	chmod +x linuxdist.sh

	changelogdate=`date +"%a %b %d %Y"`
    srpmname="k3b-${k3bversion}-CVS.${timestamp}.xcyb.9.*"
    changelogentry="* $changelogdate - Mihai Maties <mihai@xcyb.org> - $srpmname\n\
- automatically rebuilt with K3b CVS \"snapshooter\" $scriptversion"
    sed -i -e "s/xversion/${k3bversion}/;\
	s/xrelease/CVS.${timestamp}/;\
	s/xchangelog/${changelogentry}/;\
        s/xsource/$(basename $filename)/" k3b.spec

    rpmbuild -bs --define "_srcrpmdir $PWD" \
	--define "_sourcedir $PWD" k3b.spec

    rm -f k3b.spec linuxdist.sh
    [[ $deletefile == "yes" ]] && rm -f $filename
    cd $initialdir/$dirname
fi

# Executing ./configure && make if -i or -m was specified
if [[ $action == "make" || $action == "install" ]]
then
    cd $dirname/kdeextragear-1
    echo $PWD
    ./configure && make
    InCaseOfError "Could not complete the './configure && make' phase.\n\nYou \
	should not expect a fully working version of K3b from every snapshot \
        as this is a work in progress. Maybe the current version doesn't compile \
	but be sure the developers are working on it. Wait a few days, then try \
        again with a new snapshot." 2
fi

# Executing make install if -i was specified
if [[ $action == "install" ]]
then
    make install
    InCaseOfError "Could not complete the 'make install' phase.\n\nYou \
	should not expect a fully working version of K3b from every snapshot \
        as this is a work in progress. Maybe the current version doesn't compile \
        but be sure the developers are working on it. Wait a few days, then try \
        again with a new snapshot." 3
fi

# Executing make clean if -c was specified
[[ $clean == "yes" ]] && make clean

exit


