#! /bin/sh

# Copyright (C) 2010 Nishio Futoshi <futoshi@momonga-linux.org>
#                    NAKAYA Toshiharu <nakaya@momonga-linux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# script name
BUILD_SCRIPT=momonga-nonfree-package-builder.rb

# pkgdatadir
PKGDATADIR=/usr/share/momonga-nonfree-package-builder

# nonfree.csv
NONFREE_FILE=${PKGDATADIR}/nonfree.csv

# script file check
if test ! -f ${PKGDATADIR}/${BUILD_SCRIPT} ; then
  zenity --error --text="Could not find ${BUILD_SCRIPT}"
  exit 1
fi

# user setting file
USER_CONF=${HOME}/.mnprc

if test -f ${USER_CONF} ; then
  . ${USER_CONF}
fi

# error constants
MNPB_ERROR_NOT_SUPPORT_ARCH=3
MNPB_ERROR_COULD_NOT_CONNECT=5
MNPB_ERROR_ARGV=10
MNPB_ERROR_UNAVAILABLE_PACKAGE=15
MNPB_ERROR_UNAVAILABLE_ARCH=18
MNPB_ERROR_PACKAGE_NOTFOUND=20
MNPB_ERROR_SVN_EXPORT=30
MNPB_ERROR_ONLY_IX86=35
MNPB_ERROR_DEPENDENCY=40
MNPB_ERROR_YUM=50
MNPB_ERROR_SOURCES_NOTFOUND=55
MNPB_ERROR_DOWNLOAD=60
MNPB_ERROR_CHECKSUM=65
MNPB_ERROR_RPMBUILD=70
MNPB_ERROR_INSTALL=80

# nonfree.csv check
if test ! -f ${NONFREE_FILE} ; then
  zenity --error --text="Could not find ${NONFREE_FILE}"
  exit 1
fi

# nonfree list
NONFREE_LIST=$(ruby -rcsv -e 'CSV.foreach("/usr/share/momonga-nonfree-package-builder/nonfree.csv") { |r| puts(r.shift + " dummy " + r.join(",")) }')

# get package name with zenity
PACKAGE_NAME=$(zenity --list \
                      --title "Momonga Nonfree Package Builder" \
                      --text "Available package list" \
                      --hide-column 2 \
                      --height 320 --width 320 \
                      --column "Name" --column dummy --column "Arch" \
                      ${NONFREE_LIST})

# exit not selected package
if test "x${PACKAGE_NAME}" != "x" ; then
  # proxy
  if test "x${USE_PROXY}" = "x" ; then
    # Y => 0, N => 1
    zenity --question \
           --title "Do you want to use proxy server?" \
           --text "Do you want to use proxy server?"
    USE_PROXY=$?
    echo "USE_PROXY=${USE_PROXY}" > ${USER_CONF}
  fi
  if test ${USE_PROXY} -eq 0 ; then
    if test "x${PROXY_HOST}" = "x" -o "x${PROXY_PORT}" = "x" ; then
      PROXY_SETTINGS=$(zenity --entry \
                              --title "Please fill in host and port" \
                              --text "Please fill in host and port\ne.g.) example.com:8080")
      PROXY_HOST=$(echo ${PROXY_SETTINGS} | cut -d : -f 1)
      PROXY_PORT=$(echo ${PROXY_SETTINGS} | cut -d : -f 2)
      echo "PROXY_HOST=${PROXY_HOST}" >> ${USER_CONF}
      echo "PROXY_PORT=${PROXY_PORT}" >> ${USER_CONF}
    fi
  fi
  if test "x${PROXY_HOST}" != "x" -a "x${PROXY_PORT}" != "x" ; then
    PROXY_OPTIONS="--proxy-host ${PROXY_HOST} --proxy-port ${PROXY_PORT}"
  fi

  # execute build script in /tmp
  LOGFILE=/tmp/mnp$$.log
  TOPDIR=/var/tmp/mnp$$
  cd /tmp
  ruby ${PKGDATADIR}/${BUILD_SCRIPT} -d ${PROXY_OPTIONS} ${PACKAGE_NAME} | \
  tee ${LOGFILE} | \
  zenity --progress --pulsate --auto-close \
         --text="Building ${PACKAGE_NAME}\nSee ${LOGFILE}"
  STATUSES=(${PIPESTATUS[@]})

  EXIT_STATUS=${STATUSES[0]}

  QUIT_BUILD=${STATUSES[2]}
  if test ${QUIT_BUILD} -eq 1 ; then
    zenity --info --text="Quit build ${PACKAGE_NAME}"
    exit 0
  fi

  # dialog box with error
  case $EXIT_STATUS in
    $MNPB_ERROR_NOT_SUPPORT_ARCH )
      zenity --error --text="This program works on ix86 and x86_64 only"
      ;;
    $MNPB_ERROR_ARGV )
      zenity --error --text="Can not get package name"
      ;;
    $MNPB_ERROR_PACKAGE_NOTFOUND )
      zenity --error --text="${PACKAGE_NAME} is not found in Momonga svn repository"
      ;;
    $MNPB_ERROR_UNAVAILABLE_PACKAGE )
      zenity --error --text="${PACKAGE_NAME} is not available in Momonga"
      ;;
    $MNPB_ERROR_UNAVAILABLE_ARCH )
      zenity --error --text="${PACKAGE_NAME} is not available on this arch"
      ;;
    $MNPB_ERROR_COULD_NOT_CONNECT )
      zenity --error --text="Can not connect svn.momonga-linux.org"
      ;;
    $MNPB_ERROR_SVN_EXPORT )
      zenity --error --text="Can not checkout from svn.momonga-linux.org"
      ;;
    $MNPB_ERROR_ONLY_IX86 )
      zenity --error --text="${PACKAGE_NAME} is available on only ix86"
      ;;
    $MNPB_ERROR_DEPENDENCY )
      zenity --error --text="Unknown dependency flag (sorry, this is an internal error)"
      ;;
    $MNPB_ERROR_YUM )
      zenity --error --text="yum was failed before the build"
      ;;
    $MNPB_ERROR_SOURCES_NOTFOUND )
      zenity --error --text="SOURCES/sources file is not found"
      ;;
    $MNPB_ERROR_DOWNLOAD )
      zenity --error --text="Download error occurred"
      ;;
    $MNPB_ERROR_CHECKSUM )
      zenity --error --text="Checksum error occurred"
      ;;
    $MNPB_ERROR_RPMBUILD )
      zenity --error --text="rpmbuild was failed"
      ;;
    0 )
      zenity --info  --text="Build success: ${PACKAGE_NAME}"

      PKGFILES=()
      PKGNAMES=()
      for rpm in $(ls ${TOPDIR}/RPMS/*/*.rpm) ;
      do
        PKGFILES=("${PKGFILES[@]}" $(basename ${rpm}))
        PKGNAMES=("${PKGNAMES[@]}" $(rpm -qp --queryformat '%{NAME}' ${rpm}))
      done

      # install message
      INSTALL_MESSAGE="Do you want to install the following packages?"
      for rpm in ${PKGFILES[@]} ;
      do
        INSTALL_MESSAGE="${INSTALL_MESSAGE}\n- ${rpm}"
      done

      zenity --question --text="${INSTALL_MESSAGE}"

      # create repo and yum
      if test $? -eq 0 ; then
        createrepo -v -d ${TOPDIR}/RPMS
        cat <<EOF > ${TOPDIR}/momonga-nonfree-package-builder.repo
[momonga-nonfree-package-builder]
name=Momonga Nonfree Package Builder
baseurl=file://${TOPDIR}/RPMS
enabled=1
gpgcheck=0
EOF

        YUM_RUNSPEC="env LANG=C yum -c ${TOPDIR}/momonga-nonfree-package-builder.repo"
        if test "x${PROXY_OPTIONS}" != "x" ; then
          YUM_RUNSPEC="${YUM_RUNSPEC} --setopt=proxy=http://${PROXY_HOST}:${PROXY_PORT}/"
        fi
        YUM_RUNSPEC="${YUM_RUNSPEC} -y install"
	for pkg in ${PKGNAMES[@]} ;
	do
          YUM_RUNSPEC="${YUM_RUNSPEC} ${pkg}"
        done

        $YUM_RUNSPEC

	if test $? -ne 0 ; then
	  zenity --error --text="yum was failed before the build\nPlease install manually"
          EXIT_STATUS=$MNPB_ERROR_INSTALL
        fi
      fi

      # always copy packages to $HOME (/root directory)
      LAST_MESSAGE="Done!"
      for rpm in ${PKGFILES[@]} ;
      do
        LAST_MESSAGE="${LAST_MESSAGE}\n- ${rpm}"
      done
      LAST_MESSAGE="${LAST_MESSAGE}\nin /root directory"
      zenity --info --text="${LAST_MESSAGE}"
      for rpm in ${PKGFILES[@]} ;
      do
        mv -f /tmp/${rpm} $HOME
      done

      # remove build directory
      rm -rf ${TOPDIR}
      ;;
    * )
      zenity --info --text="Unknown error occurred"
      ;;
  esac
fi

exit $EXIT_STATUS
