#!/bin/bash
#
# Helper script for self-build rpm package.
# arguments 1:package name, 2:spec file, 3 to n-1: source url
#           n:build log size
#
# NOTE: To avoid scriptlet failure during rpm transaction,
#       This script should always return 0 even if there is an error.

TEXTDOMAIN=self-build-setup
TEXTDOMAINDIR=/usr/share/locale

_NAME=$1
_SPEC=$2
_QUEDIR=/var/cache/self-build
_BASE_SIZE=0

#
# bar() : function to draw text-base progress bar
#

BAR_W=$((`tput cols 2>/dev/null`-20))
COUNT=0
LINES=0

bar(){
    while read line; do
        let $((COUNT+=${#line}))
        let $((LINES+=1))
        if [ $(($LINES % 10)) = 0 ]; then
            if [ $_BASE_SIZE -gt 0 ]; then
                PERCENT=$((100*COUNT/_BASE_SIZE))
                [ $PERCENT -gt 100 ] && PERCENT=100 
                BAR_LEFT=$((BAR_W*PERCENT/100))
                printf "     %3d%%[" $PERCENT
                for i in $(seq 1 $BAR_LEFT); do
                    printf "="
                done
                printf ">"
                for i in $(seq 1 $((BAR_W-BAR_LEFT))); do
                    printf " "
                done
                printf "]\r"
            else
                printf "      --%%["
                for i in $(seq 1 $(($LINES / 10))); do
                    printf "="
                done
                printf ">]\r"
                if [ $(($LINES / 10)) -eq $BAR_W ]; then
                    LINES=0
                    printf "\n"
                fi
            fi
        fi
    done
    printf "\n"
}

#
# percentage() : function to print progress percentage (for zenity)
#

percentage(){
    while read line; do
        let $((COUNT+=${#line}))
        let $((LINES+=1))
        if [ $(($LINES % 10)) = 0 ]; then
            PERCENT=$((100*COUNT/_BASE_SIZE))
            [ $PERCENT -lt 100 ] && echo $PERCENT"%"
        fi
    done
}

#
# main
#

. /etc/self-build.conf


echo -n "     "
echo -n $"Start creating rpm packages."
echo "($_NAME)"

# create temporary rpm directory
if ! _TOPDIR=`mktemp -d $TEMP_DIR/$_NAME.XXXXXX`; then
    echo -n "     "
    echo $"*ERROR: can't crete temporary directory."
    exit 0
fi
mkdir $_TOPDIR/rpm
mkdir $_TOPDIR/rpm/BUILD
mkdir $_TOPDIR/rpm/RPMS
mkdir $_TOPDIR/rpm/RPMS/i386
mkdir $_TOPDIR/rpm/RPMS/i586
mkdir $_TOPDIR/rpm/RPMS/i686
mkdir $_TOPDIR/rpm/RPMS/x86_64
mkdir $_TOPDIR/rpm/RPMS/ppc
mkdir $_TOPDIR/rpm/RPMS/noarch
mkdir $_TOPDIR/rpm/SOURCES

# copy patches and other files.
cp -a /usr/share/$_NAME/* $_TOPDIR/rpm/SOURCES

# check last argument and set build log size
eval LAST=\$\{$(expr $#)\}
if echo $LAST | grep -E '^[0-9]+$' > /dev/null 2>&1; then
    _BASE_SIZE=$LAST
fi

# get source
echo -n "     "
echo $"Downloading source files..."
shift 2
for u in $@; do
    # if not valid url (https?: or ftp:) then skip
    if ! echo $u | egrep "^(https?|ftp):"; then
        continue
    fi

    # if you already downloaded source files, 
    # then copy these files from cache directory
    _SRC=$_TOPDIR/rpm/SOURCES/$(basename $u)
    _CACHEDSRC=$_QUEDIR/$(basename $u)
    if [ "$CACHE_DOWNLOADED_FILES" = "yes" ]; then
	[ -s $_CACHEDSRC ] && cp -af $_CACHEDSRC $_SRC
    fi
    [ -s $_SRC ] && continue

    if [ ! $DL_SHOW_PROGRESS = "yes" ]; then
        # run quiet, no GUI 
        wget -q -O $_TOPDIR/rpm/SOURCES/$(basename $u) $u
        RESULT=$?
    elif [ -z `pgrep -n synaptic` ]; then
        # run verbose, without GUI (because no synaptic running)
        wget -O $_TOPDIR/rpm/SOURCES/$(basename $u) $u
        RESULT=$?
    else
    	# run verbose with GUI (zenity)
    	DLSTAT=0
        DLSTAT=(`wget -O $_TOPDIR/rpm/SOURCES/$(basename $u) $u 2>&1 | \
             sed -u 's/.* \+\([0-9]\+%\).*$/\1/' 2>/dev/null | \
             zenity --auto-close --progress --auto-kill \
                     --title $"Download files" \
                     --text $"Downloading $(basename $u)..."; echo ${PIPESTATUS[0]}`)
        RESULT=$?
        # need to use string cpmparison for DLSTAT because PIPESTATUS[0] returns
        # null value when wget is killed with zenity auto-kill function.
        if [ "$DLSTAT" == "0" ] && [ $RESULT -eq 0 ]; then
            RESULT=0
        else
            RESULT=1
        fi
    fi
    if [ $RESULT -ne 0 -a -e $_SRC ]; then
	rm -f $_SRC
    else
	# if cache directory has no source files, then copy these files to cache directory
	if [ "$CACHE_DOWNLOADED_FILES" = "yes" ]; then
	    [ -s $_CACHEDSRC ] || cp -af $_SRC $_CACHEDSRC
	fi
    fi
done
for f in $(echo $@ | xargs -r -n1 basename|sort -u|egrep "^(https?|ftp):"); do
    if [ ! -s $_TOPDIR/rpm/SOURCES/$f ]; then
        echo -n "     "
        echo $"*ERROR: can't download source file."": $f"
        rm -rf $_TOPDIR
        exit 0
    fi
done
echo -n "     "
echo $"Source files download successfully."

# build rpm package
echo -n "     "
echo $"Building rpm packages..."
echo -n "      "
echo $"(see $TEMP_DIR/$_NAME.log for detail.)"
# now rpmbuild done by non-root user $BUILD_USER
rm -f $TEMP_DIR/$_NAME.log
chown -R $BUILD_USER:$BUILD_USER $_TOPDIR

if [ ! $BUILD_SHOW_PROGRESS = "yes" ]; then
    # run quiet, no GUI 
    su $BUILD_USER -c "rpmbuild -bb --define=\"_topdir $_TOPDIR/rpm\" /usr/share/$_NAME/$_SPEC" >$TEMP_DIR/$_NAME.log 2>&1
    RESULT=$?
elif [ -z `pgrep -n synaptic` ]; then
    # run verbose, without GUI (because no synaptic running)
    su $BUILD_USER -c "rpmbuild -bb --define=\"_topdir $_TOPDIR/rpm\" /usr/share/$_NAME/$_SPEC" 2>&1 | tee $TEMP_DIR/$_NAME.log | bar 
    RESULT=$?
else
    # run verbose with GUI (zenity)
    BUILDSTAT=0
    if [ $_BASE_SIZE -gt 0 ]; then
        BUILDSTAT=(`su $BUILD_USER -c "rpmbuild -bb --define=\"_topdir $_TOPDIR/rpm\" /usr/share/$_NAME/$_SPEC" 2>&1 | \
                tee $TEMP_DIR/$_NAME.log | percentage | \
                zenity --auto-close --progress --auto-kill \
                        --title $"Build of rpm package" \
                        --text $"Building $(basename $_SPEC .spec | sed -e 's/-vl$//') rpm packages..."; \
                echo ${PIPESTATUS[0]}`)
        RESULT=$?
    else
        BUILDSTAT=(`su $BUILD_USER -c "rpmbuild -bb --define=\"_topdir $_TOPDIR/rpm\" /usr/share/$_NAME/$_SPEC" 2>&1 | \
                tee $TEMP_DIR/$_NAME.log | \
                zenity --auto-close --progress --pulsate --auto-kill \
                        --title $"Build of rpm package" \
                        --text $"Building $(basename $_SPEC .spec | sed -e 's/-vl$//') rpm packages..."; \
                echo ${PIPESTATUS[0]}`)
        RESULT=$?
    fi   
    # need to use string cpmparison for BUILDSTAT because PIPESTATUS[0] returns
    # null value when rpmbuild is killed with zenity auto-kill function.
    if [ "$BUILDSTAT" == "0" ] && [ $RESULT -eq 0 ]; then
        RESULT=0
    else
        RESULT=1
    fi
fi

if [ $RESULT -eq 0 ] ; then
    echo -n "     "
    echo $"rpm packages are successfully built."
    # move created rpm packages to que directory
    find $_TOPDIR/rpm/RPMS -type f -name "*.rpm" -exec mv {} $_QUEDIR \;
    rm -rf $_TOPDIR
else
    echo -n "     "
    echo $"*ERROR: can't build rpm packages."
    rm -rf $_TOPDIR
    exit 0
fi
exit 0
