#!/bin/bash -e
### Unlike most other msys-build-foo scripts, this one does
### not accept the 'tarball name' as a command line argument.
### That is hardcoded...
###
### However, this script DOES accept an optional argument:
###   --non-interactive
### which skips all of the questions and warnings. BE CAREFUL.
### The warnings and questions are there to give you a chance
### to back out, BEFORE this script installs perl and other
### components directly into your / directory!!!  Only use
### this option if you really know what you are doing!
opt_interactive=1
while [ "${1+defined}" ]
do
  if [ "$1" == "--non-interactive" ]
  then
    opt_interactive=0
    shift
  elif [ "${1:0:1}" == "-" ]
  then
    echo "Ignoring option: $1" 1>&2
    shift
  else
    echo "Non-option argument $1 reached. Ignoring further options" 1>&2
    break
  fi
done

export PKG=perl
export UPSTREAM_VER=5.8.8
export VER=5.8.8
export MAJOR=5.8
export BLD=1
export SYS=msys
_sysver=$(uname -r)
export SYSVER=${_sysver%%\(*}
FULLPKG=${PKG}-${VER}-${BLD}-${SYS} # not sysver
SRCDIR_=${PKG}-${UPSTREAM_VER}
RELDOCDIR=share/doc/${PKG}/${VER}
BINPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-bin.tar.lzma
MANPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-man.tar.lzma
DOCPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-doc.tar.lzma
HTMLPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-html.tar.lzma
LICPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-lic.tar.lzma
SRCPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-src.tar.lzma

PVER=$PKG-$VER
PTAR=$PVER.tar.gz

exts="\
	Win32API-File-0.1001 \
	Pod-Escapes-1.04 \
	Pod-Simple-3.05 \
	Test-Pod-1.26 \
	Devel-Symdump-2.07 \
	Pod-Coverage-0.18 \
	Test-Pod-Coverage-1.08 \
	IO-Compress-Base-2.005 \
	Compress-Raw-Zlib-2.005 \
	IO-Compress-Zlib-2.005 \
	Compress-Zlib-2.005 \
	Compress-Raw-Bzip2-2.005 \
	IO-Compress-Bzip2-2.005 \
	Compress-Bzip2-2.09 \
        IO-Zlib-1.05	\
        IO-String-1.08	\
        MD5-2.03 \
        Archive-Tar-1.32
	Archive-Zip-1.20 \
	Math-BigInt-FastCalc-0.15 \
	Term-ReadLine-Perl-1.0302 \
	TermReadKey-2.30 \
        XML-NamespaceSupport-1.09 \
	XML-SAX-0.15 \
	XML-LibXML-Common-0.13 \
	XML-LibXML-1.63 \
	XML-Parser-2.34	\
	File-Temp-0.18 \
	YAML-0.62 \
	Config-Tiny-2.10 \
	File-Copy-Recursive-0.33 \
	IPC-Run3-0.037 \
	Probe-Perl-0.01 \
    	Tee-0.13 \
	IO-CaptureOutput-1.03 \
	File-pushd-0.99 \
	File-HomeDir-0.65 \
	Digest-SHA-5.45 \
	URI-1.35 \
	HTML-Tagset-3.10 \
	HTML-Parser-3.56 \
	libwww-perl-5.805 \
	CPAN-1.9102 \
	Test-Reporter-1.27 \
	CPAN-Reporter-0.44 \
	Net-Telnet-3.03	\
	Module-Build-0.2808 \
	Module-ScanDeps-0.75 \
	PAR-Dist-0.23 \
	ExtUtils-CBuilder-0.19 \
	ExtUtils-ParseXS-2.18 \
	Regexp-Common-2.120 \
	version-0.7203 \
	podlators-2.0.5 \
	Pod-Readme-0.09 \
	B-Generate-1.09 \
	PadWalker-1.5 \
	Alias-2.32 \
	"


# displays error message and exits
error() {
        case $? in
                0) local errorcode=1 ;;
                *) local errorcode=$? ;;
        esac

        echo -e "\e[1;31m*** ERROR:\e[0;0m ${1:-no error message provided}";
        exit ${errorcode};
}

# displays information message
inform() {
        echo -e "\e[1;32m*** Info:\e[0;0m ${1}";
}

# displays warning message only
warning() {
        echo -e "\e[1;33m*** Warning:\e[0;0m ${1}";
}

# query
query() {
	while true
	do
          echo -e "\e[1;35m*** Query:\e[0;0m ${1}";
	  if read -e answer
	  then
	    query_result=$answer
	    return 0
	  else
	    # user did a ^D
	    echo -e "Quitting.\n"
	    exit 1
	  fi
	done
}

# displays command to stdout before execution
verbose() {
        echo "${@}"
        "${@}"
        return $?
}
export -f verbose warning inform error

cmparg=
set_cmparg() {
        case "$1" in
        *tar.bz2       ) cmparg="j" ;;
        *tar.lzma      ) cmparg=" --lzma" ;;
        *tar.xz        ) cmparg="J" ;;
        *tar.gz | *tgz ) cmparg="z" ;;
        *              ) cmparg="" ;;
        esac
}

do_patch() {
  #local patchfile_name;
  #local patchfile_path;
  #local patchlevel;
  if [ -n "$specific_patchlevel" ]
  then
    starting_patchlevel=$specific_patchlevel
    stopping_patchlevel=$specific_patchlevel
  else
    starting_patchlevel=0
    stopping_patchlevel=3
  fi
  specific_patchlevel=

  for patchfile_path
  do
    patchfile_name="${patchfile_path##*/}"

    if [ ! -e ${patchfile_path} ]
    then
      warning "patch ${patchfile_name} not found";
      continue;
    fi

    patchlevel=$starting_patchlevel

    while test $patchlevel -le $stopping_patchlevel
    do
      if patch -N -s --dry-run -p${patchlevel} -i ${patchfile_path} &> /dev/null
      then
        echo "*** applying patch ${patchfile_name}:";
        patch -N -p${patchlevel} -i ${patchfile_path} || error "patch ${patchfile_name} failed"
        break;
      elif patch -N -s --binary --dry-run -p${patchlevel} -i ${patchfile_path} &> /dev/null
      then
        echo "*** applying patch ${patchfile_name}:";
        patch -N --binary -p${patchlevel} -i ${patchfile_path} || error "patch ${patchfile_name} failed"
        break;
      elif patch -R -s --dry-run -p${patchlevel} -i ${patchfile_path} &> /dev/null
      then
        warning "patch ${patchfile_name} already applied; skipping";
        break;
      else
        if (( patchlevel == $stopping_patchlevel ))
        then
          error "patch ${patchfile_name} will not apply";
        else
          patchlevel=`expr $patchlevel + 1`;
          continue;
        fi
      fi
    done
  done
}
export -f do_patch


if [ "x" != "x$PTAR" ]; then
    case "$PTAR" in
    *.tar.bz2 ) srcdir=`echo $PTAR | sed -e 's/\.tar\.bz2$//'`
                unpack=tbz
                savedir="$PWD" ;;
    *.tar.gz  ) srcdir=`echo $PTAR | sed -e 's/\.tar\.gz$//'`
                unpack=tgz
                savedir="$PWD" ;;
    *.zip     ) srcdir=`echo $PTAR | sed -e 's/\.zip$//'`
                unpack=zip
                savedir="$PWD" ;;
    *.tar.lzma ) srcdir=`echo $PTAR | sed -e 's/\.tar\.lzma$//'`
                unpack=tlz
                savedir="$PWD" ;;
    * ) error "Bad src directory specified: $PTAR" ;;
    esac
else
  savedir="$PWD"
  srcdir="$PWD"
fi

if [ "$MSYSTEM" != "MSYS" ]
then
  echo "You must be in an MSYS shell to use this script"
  exit 1
fi

msys_download () {
  url=ftp://ftp.funet.fi/pub/CPAN/src/5.0
  md5='b8c118d4360846829beb30b02a6b91a7'

  test -f $PTAR || {
	echo "Downloading $PTAR ..." 
	curl $url/$PTAR -o $PTAR || exit
  }

  echo "Verifying md5 sum ..." 
  echo "$md5 *$PTAR" > $PTAR.md5
  md5sum -c --status $PTAR.md5 || exit
}

msys_unpack () {
  if [ -n "$unpack" ] ; then
    if test "x${SRCDIR_}" != "x"
    then
      rm -rf ./${SRCDIR_}
    fi
    touch ./install_timestamp
    case "$unpack" in
    tbz ) inform "unpacking $PTAR" ; tar xjf $PTAR ;;
    tgz ) inform "unpacking $PTAR" ; tar xzf $PTAR ;;
    zip ) inform "unpacking $PTAR" ; unzip -q $PTAR ;;
    tlz ) inform "unpacking $PTAR" ; tar --lzma -xf $PTAR ;;
    * ) error "unknown pack format" ;;
    esac
    if [ -n "${SRCDIR_}" ]; then
      if [ ! -d "${SRCDIR_}" ]; then
        echo "src package $PTAR does not unpack into assumed srcdir $SRCDIR_"
        exit 1
      fi
      srcdir=`cd ${SRCDIR_} && pwd`
    fi
    if [ ! -d "$srcdir" ]; then
      echo "src package $PTAR does not unpack into assumed srcdir $srcdir"
      exit 1
    fi

    tar xjvf ${PVER}-ext-Win32CORE.tar.bz2

    cd ${srcdir}
    specific_patchlevel=1 do_patch ${savedir}/patches/0001-MSys-Core-perl-code-mods.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0002-MSys-Core-perl-build-system-mods.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0003-MSys-Core-lib-mods-CGI.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0004-MSys-Core-lib-mods-ExtUtils-MakeMaker.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0005-MSys-Core-lib-mods-File.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0006-MSys-Core-lib-mods-ExtUtils-Embed.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0007-MSys-Core-lib-mods-Net.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0008-MSys-Core-lib-mods-Pod.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0009-MSys-Core-lib-mods-Test-Harness.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0010-MSys-Core-lib-mods-Perl-Debugger-perl5db.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0011-MSys-Extension-lib-mods-NDBM_File-ODBM_File.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0012-MSys-Extension-lib-mods-SDBM_File.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0013-MSys-Extension-lib-mods-POSIX.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0014-MSys-Extension-lib-mods-Time-HiRes.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0015-MSys-Documentation.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0016-MSys-Correct-environ-handling-bug.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0017-MSys-TEST-op-tests.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0018-MSys-TEST-io-tests.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0019-MSys-TEST-lib-tests.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0020-MSys-TEST-run-tests.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0021-MSys-TEST-Core-perl-mods.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0022-MSys-TEST-Core-lib-mods-AnyDBM_File.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0023-MSys-TEST-Core-lib-mods-ExtUtils.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0024-MSys-TEST-Core-lib-mods-File-Spec.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0025-MSys-TEST-Core-lib-mods-IPC.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0026-MSys-TEST-Core-lib-mods-Net.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0027-MSys-TEST-Core-lib-mods-User.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0028-MSys-TEST-Extension-lib-mods-B.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0029-MSys-TEST-Extension-lib-mods-Cwd.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0030-MSys-TEST-Extension-lib-mods-DB_File.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0031-MSys-TEST-Extension-lib-mods-File-Glob.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0032-MSys-TEST-Extension-lib-mods-IO.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0033-MSys-TEST-Extension-lib-mods-SDBM_File-GDBM_File.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0034-MSys-Fix-compiling-if-you-have-paths-with-spaces-in-.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0035-MSys-Fix-issue-with-trying-to-link-with-lm.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0036-MSys-MallocCfg_ptr-is-really-EXT-not-extern.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0037-MSys-Various-build-system-fixes-from-LRN.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0038-MSys-Incorporate-Win32CORE-extension-into-libperl.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0039-MSys-XSTypes-capitalization-fix.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0040-MSys-Use-custom-cwd-implementations.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0041-MSys-TEST-Extension-lib-mods-Net-Ping.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0042-MSys-TEST-Extension-lib-mods-NDBM_File-ODBM_File.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0043-MSys-TEST-Extension-lib-mods-Socket.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0044-MSys-TEST-Extension-lib-mods-Net-Ping-2.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0045-MSys-cygwin-Slight-improvement-in-path-canonicalizat.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0046-MSys-TEST-Avoid-die-in-testsuite-due-to-symlink.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0047-MSys-Workaround-fclose-success-but-errno-EBADF-issue.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0048-MSys-Cygwin-Keep-usr-bin-in-PATH-for-taint.patch
    specific_patchlevel=1 do_patch ${savedir}/patches/0049-MSys-Build-with-DDEBUGGING-to-enable-D-options.patch

    cd ${savedir}
    srcdir=`cd $srcdir; pwd`
  else
    srcdir=`cd ${SRCDIR_} && pwd`
    cd ${savedir}
    srcdir=`cd $srcdir; pwd`
  fi
}

curdir=`pwd`
NEED_INIT=0
if [ -f ./Configure ]
then
  # started from srcdir
  srcdir=${curdir}
else
  # assume we need to unpack and initialize _log, _inst
  msys_download
  msys_unpack # sets srcdir
  for i in $exts; do test -e exts/$i.tar.gz || echo preq exts/$i.tar.gz not found; done
  for i in $exts; do test -e exts/$i.tar.gz || exit; done
  NEED_INIT=1
fi

PREFIX=/usr
unset INCLUDE
unset LIB

abovedir=`cd ${srcdir}/..; pwd`
BIN_CONTENTS="--exclude lib/perl5/${MAJOR}/html bin lib"
MAN_CONTENTS="share/man"
DOC_CONTENTS="share/doc --exclude share/doc/perl/${VER}/Artistic --exclude share/doc/perl/${VER}/Copying --exclude share/doc/perl/${VER}/README"
HTML_CONTENTS="lib/perl5/${MAJOR}/html"
LIC_CONTENTS="share/doc/perl/${VER}/Artistic share/doc/perl/${VER}/Copying share/doc/perl/${VER}/README"

sysroot=$(echo ${SYSTEMROOT} | sed -e 's;\\;/;g' -e 's;\(\S\):;/\1;')
# NO SPACES!!
export PATH=`pwd`:/bin:/mingw/bin:${sysroot}/system32:${sysroot}

if [ "$NEED_INIT" -ne 0 ]
then
  rm -rf ${abovedir}/_logs
  mkdir -p ${abovedir}/_logs
  rm -rf ${abovedir}/_inst
  mkdir -p ${abovedir}/_inst
fi
logdir=${abovedir}/_logs
instdir=${abovedir}/_inst

inform "Here we go..."

msys_prep () {
  cd ${srcdir}
  inform "Preparing ${PKG}"
  #chmod -R +w *
  
  # clean up
  find . -name "*.o" | xargs rm -f
  find . -name "*.a" | xargs rm -f
  find . -name "*.dll" | xargs rm -f
  find . -name "*.exe" | xargs rm -f
  rm -f config.sh
  rm -f myconfig
  rm -f config.h

  ## path settings configured here:
  cp ${abovedir}/Policy.sh .

  sh -x ./Configure -de \
                -Duse64bitint   \
                -Dusesitecustomize \
                2>&1 | tee ${logdir}/log-configure.txt
}

msys_build () {
  cd ${srcdir}
  inform "Building ${PKG}"
  export PERL5LIB=${srcdir}/lib
  make 2>&1 | tee ${logdir}/log-make.txt
  inform "Rebasing ${PKG}"
  ${abovedir}/rebasesome -v -b 0x56000000 -o 0x20000 -d ${srcdir} 2>&1 | tee ${logdir}/log-rebase.txt
  inform "Done rebasing ${PKG}"
}

msys_check () {
  cd ${srcdir}
  inform "Testing ${PKG}"
  make -j1 install.perl DESTDIR=""
  export PERL5LIB=${srcdir}/lib
  export PERL=/bin/perl
  rm -rf ${srcdir}/t/for_find
  make test PERL=/bin/perl 2>&1 | tee ${logdir}/log-test.txt
  rm -rf ${srcdir}/t/for_find
  (cd t;/bin/perl harness) 2>&1 | tee ${logdir}/log-harness.txt
}

msys_perl_install () {
  cd ${srcdir}
  inform "Installing ${PKG}"
  echo

  export PERL5LIB=${srcdir}/lib
  # NOTE: "make install" doesn't work
  # To install perl:          "make install.perl"
  # To install with manpages: "make install.perl install.man"
  # To install with HTML-docs:"make install.perl install.man install.html"
  # Worse, using DESTDIR or prefix= doesn't work correctly
  # with this version of perl. So, we have to install into
  # /usr.
  inform "About to install into /usr (using a DESTDIR or"
  inform "alternate prefix doesn't work correctly)."
  inform "NOTE: You'll need to manually re-install your original version"
  inform "      of perl after this using 'mingw-get install perl-bin'"
  if [ "$opt_interactive" -ge 1 ]
  then
    query "Is this ok? [Y|n]"
    case "x${query_result}" in
    x[Yy][Ee][Ss]|x[Yy] ) ;;
    * ) echo -e "Quitting.\n"
        exit 1
    esac
  fi
  inform "Ok. Here we go..."
  mkdir -p ${PREFIX}/lib/perl5/${MAJOR}/html
  make -j1 install.perl INSTALLFLAGS=-f DESTDIR="" 2>&1 | tee ${logdir}/log-install.txt
  make -j1 install.man install.html DESTDIR="" 2>&1 | tee -a ${logdir}/log-install.txt
  ${abovedir}/perlrebase 2>&1 | tee ${logdir}/log-rebase-install-core.txt
}

# This function patches the installed ExtUtils::Install temporarily,
# so that ALL files associated with compiled extensions will be
# installed, even if identical files already exist at the installation
# location. In this way, we ensure that the timestamps of all files
# are update, so that our packaging scheme works as expected. As this
# operation is tightly coupled to the build procedure, we use a HERE
# document instead of a separate file for the patch itself...
#
# Used both to patch ($1 >= 0) and to un-patch ($1 < 0)
msys_cpan_install_fixup () {
  pushd / >/dev/null
  local dir=${1:-0}
  local tPatch=/tmp/msys-build-perl-patch.$$
  cat > "$tPatch" <<-"EOF"
	--- a/usr/lib/perl5/5.8/ExtUtils/Install.pm	2011-03-27 23:06:29 +0400
	+++ b/usr/lib/perl5/5.8/ExtUtils/Install.pm	2011-03-29 06:00:40 +0400
	@@ -169,7 +169,7 @@
	 		$diff++;
	 	    }
	 
	-	    if ($diff){
	+	    if (1){
	 		if (-f $targetfile){
	 		    forceunlink($targetfile) unless $nonono;
	 		} else {
	@@ -178,8 +178,8 @@
	 		}
	 		copy($sourcefile, $targetfile) unless $nonono;
	 		print "Installing $targetfile\n";
	-		utime($atime,$mtime + $Is_VMS,$targetfile) unless $nonono>1;
	-		print "utime($atime,$mtime,$targetfile)\n" if $verbose>1;
	+		#utime($atime,$mtime + $Is_VMS,$targetfile) unless $nonono>1;
	+		#print "utime($atime,$mtime,$targetfile)\n" if $verbose>1;
	 		$mode = 0444 | ( $mode & 0111 ? 0111 : 0 );
	 		chmod $mode, $targetfile;
	 		print "chmod($mode, $targetfile)\n" if $verbose>1;
EOF
  if [ "$dir" -ge 0 ]
  then
    if patch -N -s --dry-run -p1 -i ${tPatch} &> /dev/null
    then
      inform "*** Temporarily patching ExtUtils::Install"
      patch -N -p1 -i ${tPatch}
    elif patch -R -s --dry-run -p1 -i ${tPatch} &> /dev/null
    then
      inform "*** ExtUtils::Install already patched";
    fi
  else
    if patch -R -s --dry-run -p1 -i ${tPatch} &> /dev/null
    then
      inform "*** Un-patching ExtUtils::Install"
      patch -R -p1 -i ${tPatch}
    elif patch -N -s --dry-run -p1 -i ${tPatch} &> /dev/null
    then
      inform "*** ExtUtils::Install already un-patched";
    fi
  fi
  rm -f ${tPatch}
  popd >/dev/null
}

msys_bundle_install () {
  cd ${abovedir}/exts
  inform "Installing bundled extensions"
  msys_cpan_install_fixup 1
  echo

  unset PERL5LIB
  export PERL5LIB
  rm -f ${abovedir}/_logs/log-make_vendor.txt
  # xsubpp is copied as advised in http://code.activestate.com/lists/perl5-porters/78541/

  for i in $exts;
  do rm -rf ${i}; \
    rm -f ${abovedir}/_logs/log-ext-${i}.txt && \
    (tar xzf ${i}.tar.gz 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt &&	\
      (cd ${i} &&	\
        if test -f ../$i.patch; then \
          patch -b -p1 < ../$i.patch 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt; \
          find -name \*.orig -exec chmod 0444 \{\} \; ; \
        fi &&  \
        cp -f /bin/xsubpp /lib/perl5/${MAJOR}/ExtUtils/xsubpp && \
        case ${i} in \
          Module-Build-*|B-Generate-*) \
            PERL_MM_USE_DEFAULT=1 /bin/perl.exe Makefile.PL installdirs=vendor 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt && \
            make -j1 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt &&	\
	    if /usr/bin/find . -name "*.dll" 2>&1 | /usr/bin/grep -E '.' >/dev/null 2>&1 ; then \
	      ${abovedir}/perlrebase -d . 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt; \
	    fi && \
            AUTOMATED_TESTING=1 make -j1 test 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt &&	\
            make -j1 install UNINST=1 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt \
            ;; \
          *) \
            PERL_MM_USE_DEFAULT=1 /bin/perl.exe Makefile.PL INSTALLDIRS=vendor 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt && \
            make -j1 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt &&	\
            AUTOMATED_TESTING=1 make -j1 test 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt &&	\
	    if /usr/bin/find . -name "*.dll" 2>&1 | /usr/bin/grep -E '.' >/dev/null 2>&1 ; then \
	      ${abovedir}/perlrebase -d . 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt; \
	    fi && \
            make -j1 install_vendor UNINST=1 2>&1 | tee -a ${abovedir}/_logs/log-ext-${i}.txt \
            ;; \
        esac \
      )
    ); \
  done
  msys_cpan_install_fixup -1

  ## remove site configuration files
  ${abovedir}/perl-${VER}/perl -MConfig -e 'unlink("$Config{archlib}/CPAN/Config.pm")'
  ${abovedir}/perlrebase 2>&1 | tee ${logdir}/log-rebase-install-bundle.txt
}

msys_package_prep () {
  cd ${srcdir}
  inform "Preparing to package ${PKG}"
  echo
  inform "Some of the installed files are in undesired locations"
  inform "and must be moved. Also, there are some custom files"
  inform "to install, specific to this MSYS version of perl."
  inform "About to peform these changes in the /usr area."

  if [ "$opt_interactive" -ge 1 ]
  then
    query "Is this ok? [Y|n] "
    case "x${query_result}" in
    x[Yy][Ee][Ss]|x[Yy] ) ;;
    * ) echo -e "Quitting.\n"
        exit 1
    esac
  fi
  inform "Ok. Here we go..."
  
  mkdir -p ${PREFIX}/${RELDOCDIR}
  verbose /usr/bin/install -m 0755 ${abovedir}/perlrebase ${PREFIX}/bin
  verbose /usr/bin/install -m 0644 Changes* ${PREFIX}/${RELDOCDIR}
  verbose /usr/bin/install -m 0644 AUTHORS Artistic Copying README ${PREFIX}/${RELDOCDIR}
  verbose /usr/bin/install -m 0644 myconfig ${PREFIX}/${RELDOCDIR}/perl-config-summary
  cd ${abovedir}/_logs
  for f in log-*.txt
  do
    verbose /usr/bin/install -m 0644 "${abovedir}/_logs/${f}" ${PREFIX}/${RELDOCDIR}
  done
  verbose tar cv --lzma -f ${PREFIX}/${RELDOCDIR}/logs.tar.lzma ${PREFIX}/${RELDOCDIR}/log-*.txt
  cd ${abovedir}

  mkdir -p ${PREFIX}/share/doc/MSYS
  verbose /usr/bin/install -m 0644 ${abovedir}/msys-perl.RELEASE_NOTES \
        ${PREFIX}/share/doc/MSYS/${PKG}-${VER}-${BLD}-${SYS}.RELEASE_NOTES.txt

  pushd ${PREFIX} >/dev/null
  cat ${abovedir}/msys-perl-noship.list | while read F
  do
    if [ -e "$F" ]
    then
      rm -f "$F"
    fi
  done
  popd >/dev/null
}

msys_package () {
  cd ${abovedir}
  inform "Packaging ${PKG}"

  pkglog=${logdir}/log-package.txt
  newer="-newer ${abovedir}/install_timestamp"

  rm -f ${logdir}/log-package.txt
  touch ${logdir}/log-package.txt
  rm -f ${abovedir}/sep.sh
  touch ${abovedir}/sep.sh
  echo mkdir -p ./_inst/lib/perl5/${MAJOR} >>${abovedir}/sep.sh
  echo mkdir -p ./_inst/lib/perl5/vendor_perl/${MAJOR} >>${abovedir}/sep.sh
  echo mkdir -p ./_inst/lib/perl5/site_perl/${MAJOR} >>${abovedir}/sep.sh
  echo mkdir -p ./_inst/share/man/man1 >>${abovedir}/sep.sh
  echo mkdir -p ./_inst/share/man/man3 >>${abovedir}/sep.sh
    find /bin/                            -type f ${newer} -printf "mkdir -p ./_inst%h\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /share/doc/                      -type f ${newer} -printf "mkdir -p ./_inst%h\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /lib/perl5/${MAJOR}/             -type f ${newer} -printf "mkdir -p ./_inst%h\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /lib/perl5/vendor_perl/${MAJOR}/ -type f ${newer} -printf "mkdir -p ./_inst%h\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /share/man/                      -type f ${newer} -printf "mkdir -p ./_inst%h\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /bin/                            -type f ${newer} -printf "cp %p ./_inst%p\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /share/doc/                      -type f ${newer} -printf "cp %p ./_inst%p\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /lib/perl5/${MAJOR}/             -type f ${newer} -printf "cp %p ./_inst%p\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /lib/perl5/vendor_perl/${MAJOR}/ -type f ${newer} -printf "cp %p ./_inst%p\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    find /share/man/                      -type f ${newer} -printf "cp %p ./_inst%p\n" \
    | sort | uniq | tee -a ${pkglog} >>${abovedir}/sep.sh && \
    sh -x ${abovedir}/sep.sh 2>&1 | tee -a ${pkglog}

  cd ${abovedir}/_inst
  inform "Binary package:" 2>&1 | tee -a ${pkglog}
  set_cmparg "${BINPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${BINPKG} ${BIN_CONTENTS} 2>&1 | tee -a ${pkglog}

  inform "Manpage package:" 2>&1 | tee -a ${pkglog}
  set_cmparg "${MANPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${MANPKG} ${MAN_CONTENTS} 2>&1 | tee -a ${pkglog}

  inform "Documentation package:" 2>&1 | tee -a ${pkglog}
  set_cmparg "${DOCPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${DOCPKG} ${DOC_CONTENTS} 2>&1 | tee -a ${pkglog}

  inform "License package:" 2>&1 | tee -a ${pkglog}
  set_cmparg "${LICPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${LICPKG} ${LIC_CONTENTS} 2>&1 | tee -a ${pkglog}

  inform "HTML documentation package:" 2>&1 | tee -a ${pkglog}
  set_cmparg "${HTMLPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${HTMLPKG} ${HTML_CONTENTS} 2>&1 | tee -a ${pkglog}

  inform "Source package:" 2>&1 | tee -a ${pkglog}
  cd ${abovedir}
  set_cmparg "${SRCPKG}"
  tar cv${cmparg} -f ${abovedir}/${SRCPKG} \
    ${PKG}-${UPSTREAM_VER}.tar.gz \
    perl-5.8.8-ext-Win32CORE.tar.bz2 \
    exts/*.gz \
    exts/*.patch \
    patches/0001-MSys-Core-perl-code-mods.patch \
    patches/0002-MSys-Core-perl-build-system-mods.patch \
    patches/0003-MSys-Core-lib-mods-CGI.patch \
    patches/0004-MSys-Core-lib-mods-ExtUtils-MakeMaker.patch \
    patches/0005-MSys-Core-lib-mods-File.patch \
    patches/0006-MSys-Core-lib-mods-ExtUtils-Embed.patch \
    patches/0007-MSys-Core-lib-mods-Net.patch \
    patches/0008-MSys-Core-lib-mods-Pod.patch \
    patches/0009-MSys-Core-lib-mods-Test-Harness.patch \
    patches/0010-MSys-Core-lib-mods-Perl-Debugger-perl5db.patch \
    patches/0011-MSys-Extension-lib-mods-NDBM_File-ODBM_File.patch \
    patches/0012-MSys-Extension-lib-mods-SDBM_File.patch \
    patches/0013-MSys-Extension-lib-mods-POSIX.patch \
    patches/0014-MSys-Extension-lib-mods-Time-HiRes.patch \
    patches/0015-MSys-Documentation.patch \
    patches/0016-MSys-Correct-environ-handling-bug.patch \
    patches/0017-MSys-TEST-op-tests.patch \
    patches/0018-MSys-TEST-io-tests.patch \
    patches/0019-MSys-TEST-lib-tests.patch \
    patches/0020-MSys-TEST-run-tests.patch \
    patches/0021-MSys-TEST-Core-perl-mods.patch \
    patches/0022-MSys-TEST-Core-lib-mods-AnyDBM_File.patch \
    patches/0023-MSys-TEST-Core-lib-mods-ExtUtils.patch \
    patches/0024-MSys-TEST-Core-lib-mods-File-Spec.patch \
    patches/0025-MSys-TEST-Core-lib-mods-IPC.patch \
    patches/0026-MSys-TEST-Core-lib-mods-Net.patch \
    patches/0027-MSys-TEST-Core-lib-mods-User.patch \
    patches/0028-MSys-TEST-Extension-lib-mods-B.patch \
    patches/0029-MSys-TEST-Extension-lib-mods-Cwd.patch \
    patches/0030-MSys-TEST-Extension-lib-mods-DB_File.patch \
    patches/0031-MSys-TEST-Extension-lib-mods-File-Glob.patch \
    patches/0032-MSys-TEST-Extension-lib-mods-IO.patch \
    patches/0033-MSys-TEST-Extension-lib-mods-SDBM_File-GDBM_File.patch \
    patches/0034-MSys-Fix-compiling-if-you-have-paths-with-spaces-in-.patch \
    patches/0035-MSys-Fix-issue-with-trying-to-link-with-lm.patch \
    patches/0036-MSys-MallocCfg_ptr-is-really-EXT-not-extern.patch \
    patches/0037-MSys-Various-build-system-fixes-from-LRN.patch \
    patches/0038-MSys-Incorporate-Win32CORE-extension-into-libperl.patch \
    patches/0039-MSys-XSTypes-capitalization-fix.patch \
    patches/0040-MSys-Use-custom-cwd-implementations.patch \
    patches/0041-MSys-TEST-Extension-lib-mods-Net-Ping.patch \
    patches/0042-MSys-TEST-Extension-lib-mods-NDBM_File-ODBM_File.patch \
    patches/0043-MSys-TEST-Extension-lib-mods-Socket.patch \
    patches/0044-MSys-TEST-Extension-lib-mods-Net-Ping-2.patch \
    patches/0045-MSys-cygwin-Slight-improvement-in-path-canonicalizat.patch \
    patches/0046-MSys-TEST-Avoid-die-in-testsuite-due-to-symlink.patch \
    patches/0047-MSys-Workaround-fclose-success-but-errno-EBADF-issue.patch \
    patches/0048-MSys-Cygwin-Keep-usr-bin-in-PATH-for-taint.patch \
    patches/0049-MSys-Build-with-DDEBUGGING-to-enable-D-options.patch \
    rebasesome \
    perlrebase \
    Policy.sh \
    msys-perl.RELEASE_NOTES \
    msys-perl-noship.list \
    msys-build-perl 2>&1 | tee -a ${pkglog}
}

msys_prep
msys_build
msys_perl_install
msys_bundle_install
msys_check
msys_package_prep
msys_package

cd "$savedir"
