#! /bin/bash -e

# NOTE: should be invoked as either:
#    ./msys-build-make make-VER.tar.bz2
#    which will unpack the "pristine" source distribution, make it, 
#    and begin the build,
# OR, as
#    ../msys-build-make
#    where the current working directory is the unpacked and makeed
#    source distribution.

### hardcode PKG and tarball 
export PKG=make
export VER=3.81
export BLD=3
export SYS=msys
_sysver=$(uname -r)
export SYSVER=${_sysver%%\(*}
FULLPKG=${PKG}-${VER}-${BLD}-${SYS} # not sysver
SRCDIR_=${PKG}-${VER}
RELDOCDIR=share/doc/${PKG}/${VER}
BINPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-bin.tar.lzma
LANGPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-lang.tar.lzma
LICPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-lic.tar.lzma
DOCPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-doc.tar.lzma
SRCPKG=${PKG}-${VER}-${BLD}-${SYS}-${SYSVER}-src.tar.lzma
BIN_CONTENTS="bin"
LANG_CONTENTS="share/locale"
LIC_CONTENTS="${RELDOCDIR}/COPYING"
DOC_CONTENTS="--exclude ${RELDOCDIR}/COPYING
	share/doc share/info share/man/man1"

# 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=" --use-compress-program=xz" ;;
        *tar.gz | *tgz ) cmparg="z" ;;
        *              ) cmparg="" ;;
        esac
}

specific_patchlevel=
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 == 3 ))
        then
          error patch "patch ${patchfile_name} will not apply";
        else
          patchlevel=`expr $patchlevel + 1`;
          continue;
        fi
      fi
    done
  done
}
export -f do_patch


if [ "x" != "x$1" ]; then
  if [ -d "$1" ]; then
    savedir="$PWD"
    cd "$1"
    srcdir="$PWD"
  elif [ -f "$1" ]; then
    case "$1" in
    *.tar.bz2 ) srcdir=`echo $1 | sed -e 's/\.tar\.bz2$//'`
                unpack=tbz
                savedir="$PWD" ;;
    *.tar.gz  ) srcdir=`echo $1 | sed -e 's/\.tar\.gz$//'`
                unpack=tgz
                savedir="$PWD" ;;
    *.zip     ) srcdir=`echo $1 | sed -e 's/\.zip$//'`
                unpack=zip
                savedir="$PWD" ;;
    *.tar.lzma ) srcdir=`echo $1 | sed -e 's/\.tar\.lzma$//'`
                unpack=tlz
                savedir="$PWD" ;;
    *.tar.xz )  srcdir=`echo $1 | sed -e 's/\.tar\.xz$//'`
                unpack=txz
                savedir="$PWD" ;;
    * ) error "Bad src directory specified: $1" ;;
    esac
  else
    error "Bad src directory specified: $1"
  fi
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

if [ -n "$unpack" ] ; then
  case "$unpack" in
  tbz ) inform "unpacking $1" ; tar xjf $1 ;;
  tgz ) inform "unpacking $1" ; tar xzf $1 ;;
  zip ) inform "unpacking $1" ; unzip -q $1 ;;
  tlz ) inform "unpacking $1" ; tar --lzma -xf $1 ;;
  txz ) inform "unpacking $1" ; tar --use-compress-program=xz -xf $1 ;;
  * ) error "unknown pack format" ;;
  esac
  if [ -n "${SRCDIR_}" ]; then
    if [ ! -d "${SRCDIR_}" ]; then
      echo "src package $1 does not unpack into assumed srcdir $SRCDIR_"
      exit 1
    fi
    srcdir=`cd ${SRCDIR_} && pwd`
  fi
  if [ ! -d "$srcdir" ]; then
    echo "src package $1 does not unpack into assumed srcdir $srcdir"
    exit 1
  fi

  cd ${srcdir}
  chmod -R u+w *
  specific_patchlevel=2 do_patch ${savedir}/01-make-3.81-2-cygwin.patch
  specific_patchlevel=2 do_patch ${savedir}/02-make-3.81-dos-path.patch
  specific_patchlevel=2 do_patch ${savedir}/03-make-3.81-case_preserve.patch
  specific_patchlevel=2 do_patch ${savedir}/04-make-3.81-msys.patch
  cd ${savedir}
  srcdir=`cd $srcdir; pwd`
fi

abovedir=`cd ${srcdir}/..; pwd`
PREFIX=/usr
opt_flags="-O3 -fno-unit-at-a-time -s -march=i386 -mtune=i686"
export CFLAGS=${CFLAGS:-"${opt_flags}"}
export CPPFLAGS="${CPPFLAGS} -D__CYGWIN__"
export CXXFLAGS=${CXXFLAGS:-"${opt_flags}"}
export F77FLAGS=${F77FLAGS:-"${opt_flags}"}
export GCJFLAGS=${GCJFLAGS:-"${opt_flags}"}
export LDFLAGS="${LDFLAGS} -Wl,--enable-auto-import"

# NO SPACES!!
export PATH=`pwd`:/bin:/usr/local/bin:/mingw/bin:/c/WINDOWS/system32:/c/WINDOWS

mkdir -p ${abovedir}/_build
builddir=${abovedir}/_build
mkdir -p ${abovedir}/_inst
instdir=${abovedir}/_inst
cd ${builddir}


msys_conf_prep() {
  inform "Preparing ${PKG}"
  cd ${srcdir}
  autoreconf -fvi
  cd ${builddir}
}

msys_conf () {
  confargs="--prefix=${PREFIX} \
	--datarootdir=\${prefix}/share --docdir=\${prefix}/${RELDOCDIR}
	--sbindir=\${prefix}/sbin --libexecdir=\${prefix}/sbin \
	--sysconfdir=/etc --localstatedir=/var \
	--with-libiconv-prefix=/usr --with-libintl-prefix=/usr"

  ${srcdir}/configure --srcdir=${srcdir} ${confargs} \
	CFLAGS="${CFLAGS}" \
	CPPFLAGS="${CPPFLAGS}" \
	CXXFLAGS="${CXXFLAGS}" \
	LDFLAGS="${LDFLAGS}"

  for f in `find . -name "Makefile"`
  do
    cat "$f" | sed -e 's:/libintl\.a:/libintl.dll.a:g' \
      -e 's:/libiconv\.a:/libiconv.dll.a:g' \
      > "${f}.new" && \
    mv "${f}.new" "${f}"
  done
}

msys_build () {
  inform "Building ${PKG}"
  make
}

msys_check () {
  inform "Testing ${PKG}: Expect '8 Tests in 3 Categories Failed'"
  inform "    These are unavoidable, and have to do with the /usr == /"
  inform "    issue, the lack of symlink support under MSYS, and the"
  inform "    case-insensitive behavior of the win32 filesystem with"
  inform "    regards to Makefile vs. makefile"
  (make -k check 2>&1 || /bin/true) | tee ${builddir}/${PKG}-check.log
}

msys_install () {
  inform "Installing ${PKG}"
  make install DESTDIR=${instdir}

  verbose mkdir -p ${instdir}${PREFIX}/${RELDOCDIR}
  verbose cp -p ${srcdir}/ChangeLog \
	${srcdir}/AUTHORS \
	${srcdir}/COPYING \
	${srcdir}/NEWS \
	${srcdir}/README \
	${srcdir}/README.W32 ${instdir}${PREFIX}/${RELDOCDIR}

  verbose rm -f ${instdir}${PREFIX}/share/info/dir

cat > ${instdir}${PREFIX}/share/man/man1/make.1 <<-"EOF"
	.TH make 1 MSYS "29 Sep 2007" "make man page"

	.SH NAME
	make
	.SH DESCRIPTION
	This is a case-preserving version of GNU make. While the
	win32 file systems encountered when using MSYS software
	are invariably case-INsensitive, some users prefer a
	GNU `make' that itself is case-sensitive -- this
	version of make is a compromise which exploits the
	case-preserving aspect of win32 file systems. It considers
	.B all
	.R targets as fundamentally case-insensitive, but first
	attempts to resolve them as case-sensitive and falls back
	to the case-insensitive behaviour only if the case-sensitive
	match remains unresolved.
EOF

  verbose /usr/bin/install -d -m 755 ${instdir}${PREFIX}/share/doc/MSYS
  verbose /usr/bin/install -m 644 ${abovedir}/msys-make.RELEASE_NOTES \
	${instdir}${PREFIX}/share/doc/MSYS/${PKG}-${VER}-${BLD}-${SYS}.RELEASE_NOTES.txt
}

msys_package () {
  inform "Packaging ${PKG}"
  cd ${instdir}${PREFIX}

  set_cmparg "${BINPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${BINPKG} ${BIN_CONTENTS}

  set_cmparg "${LANGPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${LANGPKG} ${LANG_CONTENTS}

  set_cmparg "${LICPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${LICPKG} ${LIC_CONTENTS}

  set_cmparg "${DOCPKG}"
  tar cv${cmparg} --hard-dereference -f ${abovedir}/${DOCPKG} ${DOC_CONTENTS}


  cd ${abovedir}
  set_cmparg "${SRCPKG}"
  tar cv${cmparg} -f ./${SRCPKG} \
    ${PKG}-${VER}.tar.bz2 \
    01-make-3.81-2-cygwin.patch \
    03-make-3.81-case_preserve.patch \
    02-make-3.81-dos-path.patch \
    04-make-3.81-msys.patch \
    msys-make.RELEASE_NOTES \
    msys-build-make
}

msys_conf_prep
msys_conf
msys_build
msys_check
msys_install
msys_package

cd "$savedir"

