#!/bin/bash 

# build prepare script

# $Id: dassbuild_prepare.sh 1198 2015-10-13 15:04:59Z joergs $

# Exitcodes:
#   0   normal end. Has created build directory
#   1   build directory already up-to-date. Nothing to do.
# 255   error

# TODO: 
#   needs force parameter for tar.gz creation


filesize()
{
	stat  --format='%s' $*
}

md5()
{
	md5sum $* | cut -f 1 -d ' '
}

export LANG=C

BUILDUSER=$USER
[ -z $DEST_DIR ] && DEST_DIR="/tmp/build.$BUILDUSER"
BUILDTEMP=$DEST_DIR/buildsrc/

[ -z "$BUILD_USES_SVN" ] && BUILD_USES_SVN="yes"
[ -z "$BUILD_MODIFIES_SPEC" ] && BUILD_MODIFIES_SPEC="yes"

if [ -z "$1" ]; then
    # without parameter, we are in source directory
    SPECFILE=$(ls *.spec | awk '{print $1}')
    PACKAGE=$(sed -n -e 's/^Name:\W*//pi' <$SPECFILE)
    VERSION=$(sed -n -e 's/^Version:\W*//pi' <$SPECFILE)
elif [ -r "$1" ]; then
    # parameter is src.rpm file
    PACKAGE=`rpm -qp --qf "%{NAME}" $1`
    VERSION=`rpm -qp --qf "%{VERSION}" $1`
    unset BUILD_MODIFIES_SPEC
fi


if [ -z "$PACKAGE" ]; then
    echo "nothing to build found"
    exit 255
fi



if [ "$1" ]; then
    EXPECTED_DEST_RPM_FILENAME=${DEST_DIR}/${BUILD_DIST}/`echo $1 | sed 's/\.src\./.*./'`
    if [ -f "$EXPECTED_DEST_RPM_FILENAME" ]; then
        echo
        echo "Build of \"${PACKAGE}\" unnecessary. Current RPM already at " $EXPECTED_DEST_RPM_FILENAME
        echo
        exit 1
    else
        rm -rf ${BUILDTEMP}/src/${PACKAGE}
        mkdir -p ${BUILDTEMP}/src/${PACKAGE}
        cp -a "$1" ${BUILDTEMP}/src/${PACKAGE}
        cd ${BUILDTEMP}/src/${PACKAGE}; rpm2cpio $1 | cpio -i
    fi
else
    # uses Subversion (svn) to generate more information for the RPM
    if [ "$BUILD_USES_SVN" = "yes" ]; then
        echo "receiving subversion information ..."
        # set RELEASE number (last modification in this directory)
        # requires subversion (but connection to server isn't neccessary)
        SVN_BUILD_RELEASE=$(unset LANG; svn info . | sed -n 's/^Last Changed Rev: \([0-9]*\)/\1/p')
        # in case of local modification a "m" is added to the release number
        SVN_BUILD_MODIFIED=$(svn status -v | grep "^ *M" | wc -l)
        # checks if a file is commited, 
        # but update on its directory is not performed
        SVN_LAST_MODIFICATION=$(svn status -v | sed -n 's/^ *[0-9]* *\([0-9]*\) .*/\1/p' | sort -n | tail -1)
        if [ $SVN_BUILD_MODIFIED -gt 0 ]; then  
            SVN_BUILD_RELEASE=${SVN_BUILD_RELEASE}m
            REBUILD="yes"
        elif [ $SVN_LAST_MODIFICATION -ne $SVN_BUILD_RELEASE ]; then
            SVN_BUILD_RELEASE=${SVN_BUILD_RELEASE}p
            REBUILD="yes"
        fi

        if [ "$SVN_BUILD_RELEASE" ]; then
            # Release will be overwritten bei OpenSUSE build service,
            # therefore we add SVN_BUILD_RELEASE to Version
            VERSION_ORIG=$VERSION
            VERSION=$VERSION.$SVN_BUILD_RELEASE
        fi
        echo "SVN_BUILD_RELEASE: $SVN_BUILD_RELEASE"
        echo "VERSION: $VERSION"

        #
        # check, if RPM should be build again
        #
        if [ -z "$REBUILD" ]; then
            # check if RPM has been built already
            # TODO: is this useful for OpenSUSE Build Service?
            EXPECTED_DEST_RPM_FILENAME=${DEST_DIR}/${BUILD_DIST}/${PACKAGE}-${VERSION}-*.*.rpm
            echo "EXPECTED_DEST_RPM_FILENAME: $EXPECTED_DEST_RPM_FILENAME"
            if find $EXPECTED_DEST_RPM_FILENAME ; then
                echo
                echo "Build of \"${PACKAGE}\" unnecessary."
                echo "Current RPM already at " $EXPECTED_DEST_RPM_FILENAME
                echo
                exit 1
            fi
        fi

        printf "adding subversion changelog: "
        # changelog header
        echo "-------------------------------------------------------------------" > Changes
        DATE=`unset LANG; date +"%a %b %d %T UTC %Y"`
        echo -e "$DATE - svn_build@localhost\n" >> Changes
        echo "- Subversion status:" >> Changes
        # additional infos for the Changes file (see if everything is checked in)
        svn status -v | grep -v '^? ' >> Changes
        echo >> Changes
        echo "- ChangeLog:" >> Changes
        # requires connection to the subversion server
        svn log -v . > ChangeLog.new && mv ChangeLog.new ChangeLog
        # indent all svn revisions by "- ", to form a changelog entry,
        # changelog format uses * at the start of the line to determine new entry,
        #   therefore replace our * by -
        # % may be treated as a macro, there replaced by %%
        sed -r -e 's/^(r[0-9]+ \|)/- \1/' -e 's/(^[\*]+)/-/g' -e 's/%/%%/g'  ChangeLog >> Changes
        mv Changes $PACKAGE.changes
        printf "done\n"
    fi

    # if "SOURCES" file exist, create tar file on the fly
    if [ -r "SOURCES" ]; then
        # create a tar file from the sources
        SOURCE_ARCHIVE="${PACKAGE}_${VERSION}.orig.tar.gz"
        printf "creating $SOURCE_ARCHIVE: "

        if [ "$REBUILD" -o ! -r ${BUILDTEMP}/src/${PACKAGE}/$SOURCE_ARCHIVE ]; then
            rm -rf ${BUILDTEMP}/src/${PACKAGE}
            mkdir -p ${BUILDTEMP}/src/${PACKAGE}
            tar cvzf ${BUILDTEMP}/src/${PACKAGE}/$SOURCE_ARCHIVE --files-from SOURCES --exclude .svn --exclude "*~"
        else
            printf "already exists. Skipped\n"
            printf "  (${BUILDTEMP}/src/${PACKAGE}/$SOURCE_ARCHIVE)\n"
            # exit, but without error, so that the calling script will continue
            exit 0
        fi
    elif [ -r "SPECSOURCES" ]; then
        # SPECSOURCES has to list the files 
        # that are referenced in the .spec file
        # these files are copied to the build environment
        rm -rf ${BUILDTEMP}/src/${PACKAGE}
        mkdir -p ${BUILDTEMP}/src/${PACKAGE}
        cp -av `cat SPECSOURCES` ${BUILDTEMP}/src/${PACKAGE}

        # do not modify SPEC-file
        unset BUILD_MODIFIES_SPEC

    else
        printf "error: neither SOURCES nor SPECSOURCES file found. One of these is required. Exiting\n"
        exit 255
    fi

    # copy orig SPEC-file (may be modified later)
    cp -p $SPECFILE ${BUILDTEMP}/src/${PACKAGE}/
    test -r ${PACKAGE}.changes && cp -a ${PACKAGE}.changes ${BUILDTEMP}/src/${PACKAGE}/

    echo $SVN_BUILD_RELEASE
    if [ "$BUILD_MODIFIES_SPEC" = "yes" ]; then
        if [ "$SVN_BUILD_RELEASE" ]; then
            # Release will be overwritten bei OpenSUSE build service,
            # therefore we add SVN_BUILD_RELEASE to Version
            #sed "s/^Release:.*/Release: $SVN_BUILD_RELEASE/ig" $SPECFILE > ${BUILDTEMP}/src/${PACKAGE}/$SPECFILE
            #sed -r "s/^(Version:\s*\S*)/\1.$SVN_BUILD_RELEASE/ig"  $SPECFILE > ${BUILDTEMP}/src/${PACKAGE}/$SPECFILE
            sed -i "s/^Version:.*/Version: $VERSION/ig" ${BUILDTEMP}/src/${PACKAGE}/$SPECFILE
        fi

        if [ "$SOURCE_ARCHIVE" ]; then
            sed -i "s/^Source:.*/Source: $SOURCE_ARCHIVE/ig" ${BUILDTEMP}/src/${PACKAGE}/$SPECFILE
        fi
    fi

    # if there is no changelog section in the spec file,
    # also append the Changes there
    # if ! grep -q -i "%changelog" $SPECFILE ; then
    #     # paste "Changes" into SPEC file. 
    #     echo "%changelog" >> ${BUILDTEMP}/src/${PACKAGE}/$SPECFILE
    #     # without trailing *, except for the initial
    #     echo -n "*" >> ${BUILDTEMP}/src/${PACKAGE}/$SPECFILE
    #     cat Changes | sed 's/\(^[\*]\+\)//g' >> ${BUILDTEMP}/src/${PACKAGE}/$SPECFILE
    # fi

    # if there is a directory named "debian", prepare the
    # necessary files to build a debian package on OpenSUSE build service
    if [ -d debian ]; then

        # create a changelog file
        (echo "${PACKAGE} (${VERSION}-1) unstable; urgency=low"
        echo
        echo "  * generated from SVN revision ${SVN_BUILD_RELEASE}"
        echo
        echo -n " -- dass IT GmbH <info@dass-it.de>  "; date +"%a, %e %b %Y %X %z"
        echo
        )>debian/changelog

		tar cvzf ${BUILDTEMP}/src/${PACKAGE}/${PACKAGE}_${VERSION}.orig.tar.gz --files-from SOURCES --exclude .svn --exclude "*~"

		# create DSC file from template
        # replace version number in the description file
        if [ -r "${PACKAGE}.dsc" ]; then
            DSC="${PACKAGE}.dsc"
        elif [ -r "debian/${PACKAGE}.dsc" ]; then
            DSC="debian/${PACKAGE}.dsc"
        else
            echo "failed: debian directory exists, but ${PACKAGE}.dsc not found."
            exit 1
        fi
        sed -e "s/^Version:.*/Version: $VERSION-1/ig" -e  "/^Files:/,$ d" "$DSC" >${BUILDTEMP}/src/${PACKAGE}/${PACKAGE}_${VERSION}-1.dsc

        # update the file list in the description file
		files="${PACKAGE}_${VERSION}.orig.tar.gz"
		echo "Files: " >> ${BUILDTEMP}/src/${PACKAGE}/${PACKAGE}_${VERSION}-1.dsc
		for filename in $files; do
			path=${BUILDTEMP}/src/${PACKAGE}/$filename
			printf ' %s %s %s\n' `md5 $path` `filesize $path` $filename >> ${BUILDTEMP}/src/${PACKAGE}/${PACKAGE}_${VERSION}-1.dsc
		done

    fi

    if [ -r "EXTRASOURCES" ]; then
        # EXTRASOURCES has to list the files
        # that are used to control the buildprocess of
       # obs. rpmlintrc is such an example
        # these files are copied to the build environment
        mkdir -p ${BUILDTEMP}/src/${PACKAGE}
        cp -av `cat EXTRASOURCES` ${BUILDTEMP}/src/${PACKAGE}
    fi
fi
exit 0
