#!/bin/bash
. /usr/share/autodist/webbuild-functions
. /etc/sysconfig/autoport

export LANG="C.UTF-8"
MODE=$1
ENVIRONMENT=$2
USER=$3
PACKAGE=$4
COMMAND=$5
TMPFILE=$6

[ -e $WEBBUILD_STATEDIR/cache/config-dynamic ] && . $WEBBUILD_STATEDIR/cache/config-dynamic

echo "REQUEST: $@" >> $WEBBUILD_STATEDIR/commands_log
if [ "$MODE" = "killtree" ]; then
   KILLPID=$2
   [ $KILLPID -gt 1 ] && {
      echo "COMMAND: kill_tree $KILLPID" >> $WEBBUILD_STATEDIR/commands_log
      kill_tree $KILLPID
   }
   exit $?
elif [ "$MODE" = "finishprocess" ]; then
   PROCESSPID=$2
   PROCESSLOG=$4
   if [ -e $PROCESSLOG ]; then
      RETCODE=`tail -n1 $PROCESSLOG | grep "^# WEBBUILD_EXITCODE=" | sed "s|^# WEBBUILD_EXITCODE=||"`
      [ "$RETCODE" ] || RETCODE=257
   else
      RETCODE=0
   fi
   sed -i "s|\(^$PROCESSPID [^[:space:]]* [^[:space:]]* [^[:space:]]* [^[:space:]]* \)[^[:space:]]*|\1$RETCODE|" $WEBBUILD_STATEDIR/processes
   exit $RETCODE
elif [ "$ENVIRONMENT" = "local" ]; then
   echo "COMMAND: $COMMAND" >> $WEBBUILD_STATEDIR/commands_log
   $COMMAND 2>&1
   # | sed "s|<|\&lt;|g"
   RET=$?
   exit $RET
fi

if [ "$ENVIRONMENT" = "local" ]; then
   ENVPREFIX=
   ENVUSER=root
   WORKINGHOME=
   SUCMDPREFIX=
elif [ "${AUTOPORT_CHROOT[$ENVIRONMENT]}" ]; then
   ENVPREFIX="/var/autoport/${AUTOPORT_CHROOT[$ENVIRONMENT]}"
   ENVUSER=${AUTOPORT_CHROOT_USER[$ENVIRONMENT]}
   if [ "${AUTOPORT_CHROOT_USER[$ENVIRONMENT]}" = "autodist" ]; then
      WORKINGHOME="/var/autodist/"
      RPMBUILDROOT="/var/tmp/autodist/"
   else
      WORKINGHOME="/usr/src/"
      RPMBUILDROOT="/var/tmp/"
   fi
   SUCMDPREFIX="chroot $ENVPREFIX su -l ${AUTOPORT_CHROOT_USER[$ENVIRONMENT]} -c"
   [ "$TMPFILE" ] && {
      cp $TMPFILE /var/autoport/${AUTOPORT_CHROOT[$ENVIRONMENT]}/$TMPFILE
      chmod +r /var/autoport/${AUTOPORT_CHROOT[$ENVIRONMENT]}/$TMPFILE
   }
elif [ "${AUTOPORT_NATIVE[$ENVIRONMENT]}" ]; then
   ENVPREFIX=
   ENVUSER=${AUTOPORT_CHROOT_USER[$ENVIRONMENT]}
   WORKINGHOME=`getent passwd ${AUTOPORT_CHROOT_USER[$ENVIRONMENT]} | cut -d: -f6`
   [ -e "$WORKINGHOME/RPM" ] || WORKINGHOME="/usr/src/"
   SUCMDPREFIX="su -l ${AUTOPORT_CHROOT_USER[$ENVIRONMENT]} -c"
else
   ENVPREFIX=
   ENVUSER=autodist
   WORKINGHOME="/var/autodist"
   SUCMDPREFIX="su -l autodist -c"
   RPMBUILDROOT="/var/tmp/autodist"
#   [ "$TMPFILE" ] && chown autodist $TMPFILE
fi
if [ "$MODE" = "specinfo" ]; then
   eval `$SUCMDPREFIX "autospec --eval=tmppath_dir|grep -v '^#'"`
   RPMBUILDROOT=$tmppath_dir
   SPECFILE=${ENVPREFIX}${WORKINGHOME}/RPM/SPECS/$PACKAGE.spec
   if [ "$PACKAGE" -a -r "$SPECFILE" ]; then
      rm -f $SPECFILE.tmp
      while read line; do
         case "$line" in
            "## AUTOBUILDREQ-BEGIN"*) AUTOBUILDREQ_BEGIN=1 ;;
            "## AUTOBUILDREQ-END"*) AUTOBUILDREQ_END=1 ;;
            "## note: run "*" to get the list of build requirements") AUTOBUILDREQ_UNDONE=1 ;;
         esac
      done < ${ENVPREFIX}${WORKINGHOME}/RPM/SPECS/$PACKAGE.spec
      [ "$AUTOBUILDREQ_BEGIN" -a "$AUTOBUILDREQ_END" -a ! "$AUTOBUILDREQ_UNDONE" ] || \
         echo "SPECVAR_CHECK_NOAUTOBUILDREQ=1"
      $SUCMDPREFIX "rpmspec -P ${WORKINGHOME}/RPM/SPECS/$PACKAGE.spec > ${WORKINGHOME}/RPM/SPECS/$PACKAGE.spec.tmp 2>/dev/null"
      if [ -e  $SPECFILE.tmp ]; then
         echo "SPECVAR_Specfile=\"$SPECFILE\""
         # Resolve builddir by parsing %setup macro or use default
         BUILDDIR_UNPARSED=`grep "^%setup" ${WORKINGHOME}/RPM/SPECS/$PACKAGE.spec | sed "s|.*-n \([^[:space:]]*\).*|\1|"`
         if [ "$BUILDDIR_UNPARSED/%setup" != "$BUILDDIR_UNPARSED" ]; then
            BUILDDIR_UNPARSED="$PACKAGE-%{version}"
         fi
         BUILDDIR=`rpmspec -q --srpm --queryformat "${BUILDDIR_UNPARSED}" ${WORKINGHOME}/RPM/SPECS/$PACKAGE.spec`
         while read line; do
            set -- $line
            [ "$1" = "%package" -o "$1" = "%description" ] && break
            if [[ "$1" =~ ^[a-zA-Z]*[0-9]*:.* ]]; then
               line="$(echo ${line/$1})"
               specvarfull="SPECVAR_${1/:*}"
               specvar="${specvarfull/[0-9]*}"
               specvaridx="${specvarfull/$specvar}"
               [ "$specvar" = "$lastspecvar" ] && varidx=$(($varidx + 1)) || varidx=0
               echo "$specvar[$varidx]=\"${line//\"/}\""
               [ "$specvaridx" != "" ] && echo "${specvar}_idx[$varidx]=$specvaridx"
               [ "$specvar" = "SPECVAR_Version" ] && PACKAGE_VERSION="${line}"
            fi
            lastspecvar=$specvar
         done < $SPECFILE.tmp
         rm -f $SPECFILE.tmp
         echo "SPECVAR_BUILDDIR=\"$BUILDDIR\""
         echo "SPECVAR_BUILDROOT=\"$PACKAGE-root\""
         echo "SPECVAR_WORKINGHOME=\"$WORKINGHOME\""
         echo "SPECVAR_RPMBUILDDIR=\"${WORKINGHOME}/RPM/BUILD/${PACKAGE}-${PACKAGE_VERSION}-build\""
         echo "SPECVAR_RPMSOURCESDIR=\"${WORKINGHOME}/RPM/SOURCES\""
         echo "SPECVAR_RPMBUILDROOT=\"${WORKINGHOME}/RPM/BUILD/${PACKAGE}-${PACKAGE_VERSION}-build/BUILDROOT\""
         exit 0
      fi
   else
      exit 1
   fi
fi
echo "COMMAND: $COMMAND" >> $WEBBUILD_STATEDIR/commands_log

cmdtmpfile=`mktemp --tmpdir=$WEBBUILD_STATEDIR/tmp --suffix=.webbuildcmd`

[ "$PACKAGE" ] || PACKAGE=nopackage
if [ "$MODE" = "background" ]; then
   if [ "$WORKINGHOME" ]; then
      [ "$DEBUG" ] && echo "=> . /etc/profile;cd $WORKINGHOME/RPM/SPECS;stdbuf -oL -eL $SUCMDPREFIX \"$COMMAND\""
      # WARNING: don't add pipes after $COMMAND or command pid will be wrong
      $SUCMDPREFIX ". /etc/profile;cd $WORKINGHOME/RPM/SPECS;stdbuf -oL -eL $COMMAND 2>&1;echo \"# WEBBUILD_EXITCODE=\$?\"" 2>&1 > $cmdtmpfile &
      # | tr -d '\f'
      #sed "s|<|\&lt;|g" | 
   else
      [ "$DEBUG" ] && echo "=> $SUCMDPREFIX \"stdbuf -oL -eL $COMMAND\""
      # WARNING: don't add pipes after $COMMAND or command pid will be wrong
      $SUCMDPREFIX "stdbuf -oL -eL $COMMAND;echo \"# WEBBUILD_EXITCODE=\$?\"" 2>&1 > $cmdtmpfile &
      # | sed "s|<|\&lt;|g" | tr -d '\f'
   fi
   echo "$! $USER $ENVIRONMENT $PACKAGE $cmdtmpfile 256 $COMMAND" >> $WEBBUILD_STATEDIR/processes
   echo "Started background command: $COMMAND"
   echo
   echo "You may watch command live output and result in the <b>Webbuild jobs</b> box above."
   RET=0
else
   echo "$$ $USER $ENVIRONMENT $PACKAGE $cmdtmpfile 256 $COMMAND" >> $WEBBUILD_STATEDIR/processes
   rettmpfile=`$SUCMDPREFIX "mktemp --suffix=.webbuildret"`
   if [ "$WORKINGHOME" ]; then
      [ "$DEBUG" ] && echo "=> . /etc/profile;cd $WORKINGHOME/RPM/SPECS;\"$COMMAND\""
      if [ "$MODE" = "binary" ]; then
         $SUCMDPREFIX ". /etc/profile;cd $WORKINGHOME/RPM/SPECS;$COMMAND;echo \$? > $rettmpfile" 2>&1
      else
         $SUCMDPREFIX ". /etc/profile;cd $WORKINGHOME/RPM/SPECS;$COMMAND;echo \$? > $rettmpfile" 2>&1 | tr -d '\f' | tee $cmdtmpfile | parse_generic_output
      fi
      # sed "s|<|\&lt;|g" | 
   else
      [ "$DEBUG" ] && echo "=> $SUCMDPREFIX \"$COMMAND\""
      if [ "$MODE" = "binary" ]; then
         $SUCMDPREFIX "$COMMAND;echo \$? > $rettmpfile" 2>&1
      else
         $SUCMDPREFIX "$COMMAND;echo \$? > $rettmpfile" 2>&1 |  tr -d '\f' | tee $cmdtmpfile
      fi
      # sed "s|<|\&lt;|g" |
   fi
   RET=`cat $ENVPREFIX/$rettmpfile`
   [ "$RET" ] || RET=254
   $SUCMDPREFIX "rm -f $rettmpfile"
   sed -i "/^$$ $USER/d" $WEBBUILD_STATEDIR/processes
   if [ "$MODE" != "keeplog" ]; then
      rm -f $cmdtmpfile
   else
      echo "$$ $USER $ENVIRONMENT $PACKAGE $cmdtmpfile $RET $COMMAND" >> $WEBBUILD_STATEDIR/processes
   fi
fi

if [ "$ENVIRONMENT" != "local" ]; then
   if [ "$TMPFILE" -a "${AUTOPORT_CHROOT[$ENVIRONMENT]}" ]; then
      rm -f /var/autoport/${AUTOPORT_CHROOT[$ENVIRONMENT]}/$TMPFILE
   fi
fi
if [ -e $cmdtmpfile ]; then
   chmod 666 $cmdtmpfile
   chown apache.nobody $cmdtmpfile
fi

exit $RET
