#!/bin/bash
#-- xulrunner for Slackware --
# Build script by Phantom X <megaphantomx at bol.com.br>
# Suggested usage: $ xulrunner.SlackBuild 2>&1 | tee build.log
#--
# Copyright 2008, 2009, 2010, 2011 Phantom X, Goiania, Brazil..
# Copyright 2006 Martijn Dekker, Groningen, Netherlands.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# http://www.mozilla.org/projects/xulrunner/

PACKAGER_ID=${PACKAGER_ID:-$USER}
PACKAGER=${PACKAGER:-$USER@$HOSTNAME}

# Set YES for native build with gcc >= 4.2
SB_NATIVE=${SB_NATIVE:-NO}

# Set to YES to replicate slackbuild and patches
SB_REP=${SB_REP:-YES}

CWD=$(pwd)
TMP=${TMP:-/tmp}
if [ ! -d ${TMP} ]; then
  mkdir -p ${TMP}
fi

PNAME=firefox
NAME=xulrunner
PKG=${PKG:-${TMP}/package-${NAME}}

VERSION=${VERSION:-1.9.2.16}
FFVER="3.6"
if [ "$(echo ${VERSION} | cut -d . -f4)" ] ;then
  PVER="${FFVER}.$(echo ${VERSION} | cut -d . -f4)"
else
  PVER="${FFVER}"
fi
VERSION_INTERNAL="$(echo ${VERSION} | cut -d . -f1-3)"
SLKDIST=${SLKDIST:-Slackware}
SLKVER=${SLKVER:-$(awk '{print $2}' /etc/slackware-version)}
if [ "${SB_NATIVE}" = "YES" ] ;then
  ARCH=${ARCH:-$(uname -m)}
else
  ARCH=${ARCH:-x86_64}
fi
if [ "${ARCH}" = "x86_64" ] ;then
  SLKTARGET=${SLKTARGET:-x86_64}
else
  SLKTARGET=${SLKTARGET:-i486}
fi
SLKDTARGET=${SLKDTARGET:-slackware}
BUILD=${BUILD:-1}
NJOBS=${NJOBS:-$(( $(getconf _NPROCESSORS_ONLN) + 1 ))}
DOCDIR=${PKG}/usr/doc/${NAME}-${VERSION}
SBDIR=${PKG}/usr/src/slackbuilds/${NAME}
PKGDEST=${PKGDEST:-${CWD}}
PKGFORMAT=${PKGFORMAT:-txz}
PKGNAME=${NAME}-$(echo ${VERSION} | tr - . )-${ARCH}-${BUILD}${PACKAGER_ID}

# Set to YES to build with gnome libraries support, including libnotify.
SB_GNOME=${SB_GNOME:-NO}

DATE=$(LC_ALL=C date +%d-%b-%Y)

# Set default mail application
SB_DMAIL=${SB_DMAIL:-/usr/bin/thunderbird}

SRCDIR=mozilla-${VERSION_INTERNAL}
SRCARCHIVE=${PNAME}-${PVER}.source.tar.bz2
SSRCARCHIVE=${SRCARCHIVE}.asc

DL_PROG=${DL_PROG:-wget}
DL_TO=${DL_TO:-5}
DL_OPTS=${DL_OPTS:-"--timeout=${DL_TO}"}
MOZ_MIRROR=${MOZ_MIRROR:-http://releases.mozilla.org/pub}
DL_URL="${MOZ_MIRROR}/mozilla.org/${PNAME}/releases/${PVER}/source"

# if source is not present, download in source rootdir if possible
for file in ${SRCARCHIVE} ${SSRCARCHIVE} ;do
  test -r ${CWD}/${file} || ${DL_PROG} ${DL_OPTS} ${DL_URL}/${file} || exit 1
done

if [ "${SB_NATIVE}" = "YES" ] ;then
  SLKCFLAGS="-O2 -march=native -mtune=native ${SB_ECFLAGS} -pipe"
else
  case "${ARCH}" in
    i[3-6]86)    SLKCFLAGS="-O2 -march=${ARCH} -mtune=i686"
                 ;;
    x86_64)      SLKCFLAGS="-O2 -fPIC"
                 ;;
    s390|*)      SLKCFLAGS="-O2"
                 ;;
  esac
fi
if [ "${ARCH}" = "x86_64" ] ;then
  LIBDIRSUFFIX="64"
  SLKCFLAGS="${SLKCFLAGS} -fPIC"
else
  LIBDIRSUFFIX=""
fi

if [ -d ${PKG} ]; then
  # Clean up a previous build
  rm -rf ${PKG}
fi
mkdir -p ${PKG}

cd ${TMP}
rm -rf ${SRCDIR}
tar -xvf ${CWD}/${SRCARCHIVE} || exit 1
cd ${SRCDIR} || exit 1

chmod -R u+w,go+r-w,a-s .

if [ -r ${CWD}/apply-patches.sh ]; then
  . ${CWD}/apply-patches.sh || exit 1
fi

# Add Slackware to custom dists (fix some web user agent recognizing scripts)
[ "${SLKDIST}" = "Slackware" ] || export SLKDIST="${SLKDIST} (Slackware)"

rm -f .mozconfig
cat ${CWD}/${NAME}-mozconfig > .mozconfig || exit 1

if [ "${SB_GNOME}" = "YES" ] ;then
  # This needs gnome support
  echo "ac_add_options --enable-libnotify" >> .mozconfig || exit 1
else
  echo "ac_add_options --disable-gnomeui" >> .mozconfig || exit 1
  echo "ac_add_options --disable-gnomevfs" >> .mozconfig || exit 1
  sed -i \
    -e '/MOZ_ENABLE_GCONF=/s|=1|=|g'\
    -e '/MOZ_ENABLE_GNOMEVFS=/s|=1|=|g' \
    -e '/MOZ_ENABLE_LIBGNOME=/s|=1|=|g' \
    configure || exit 1
fi

echo "ac_add_options --build=${SLKTARGET}-${SLKDTARGET}-linux" >> .mozconfig || exit 1
echo "ac_add_options --host=${SLKTARGET}-${SLKDTARGET}-linux" >> .mozconfig || exit 1
echo "ac_add_options --target=${SLKTARGET}-${SLKDTARGET}-linux" >> .mozconfig || exit 1

INTERNAL_GECKO=${VERSION_INTERNAL}

INTERNAL_APP_NAME=${NAME}-${INTERNAL_GECKO}
MOZ_APP_DIR=/usr/lib${LIBDIRSUFFIX}/${INTERNAL_APP_NAME}

INTERNAL_APP_SDK_NAME=${NAME}-sdk-${INTERNAL_GECKO}
MOZ_APP_SDK_DIR=/usr/lib${LIBDIRSUFFIX}/${INTERNAL_APP_SDK_NAME}

# Mozilla builds with -Wall with exception of a few warnings which show up
# everywhere in the code; so, don't override that.
MOZ_OPT_FLAGS="$(echo ${SLKCFLAGS} | sed -e 's/-O./-Os/;s/-Wall//') -D_FORTIFY_SOURCE=2"

export CFLAGS="${MOZ_OPT_FLAGS}"
export CXXFLAGS="${MOZ_OPT_FLAGS}"

export PREFIX='/usr'
export LIBDIR="/usr/lib${LIBDIRSUFFIX}"

export LDFLAGS="-Wl,-rpath,${MOZ_APP_DIR} ${LDFLAGS}"
make -f client.mk build STRIP="/bin/true" MOZ_MAKE_FLAGS="-j${NJOBS}" || exit 1

DESTDIR=${PKG} make install || exit 1

mkdir -p ${PKG}/${MOZ_APP_DIR} \
         ${PKG}/usr/share/idl/${INTERNAL_APP_SDK_NAME} \
         ${PKG}/usr/include/${INTERNAL_APP_SDK_NAME}
install -p dist/sdk/bin/regxpcom ${PKG}/${MOZ_APP_DIR}/ || exit 1

mkdir -p ${PKG}{/usr/lib${LIBDIRSUFFIX},/usr/bin,/usr/share/applications}

# set up our default preferences
sed \
  -e "s,XUL_SLK_DIST,${SLKDIST},g;s,XUL_SLK_VR,${SLKVER},g" \
  ${CWD}/${NAME}-chinfo-default-prefs.js > slk-default-prefs

# set up default homepage and mail app
cat >> slk-default-prefs << EOF
pref("network.protocol-handler.app.mailto", "${SB_DMAIL}");
EOF
mkdir -p ${PKG}/${MOZ_APP_DIR}/defaults/pref
install -m0644 slk-default-prefs \
               ${PKG}/${MOZ_APP_DIR}/defaults/pref/all-slackware.js || exit 1
rm -f slk-default-prefs

# Start script install
rm -f ${PKG}/usr/bin/${NAME}
zcat ${CWD}/${NAME}.sh.in.gz | sed \
    -e "s,XULRUNNER_VERSION,${VERSION_INTERNAL},g" > \
     ${PKG}/usr/bin/${NAME} || exit 1
chmod 0755 ${PKG}/usr/bin/${NAME}

rm -f ${PKG}${MOZ_APP_DIR}/${NAME}-config

( cd ${PKG}${MOZ_APP_DIR}/chrome
  find . -name "*" -type d -maxdepth 1 -exec rm -rf {} \;
)

# Prepare devel
mkdir -p ${PKG}/usr/include/${INTERNAL_APP_SDK_NAME}
mkdir -p ${PKG}/usr/share/idl/${INTERNAL_APP_SDK_NAME}
mkdir -p ${PKG}/usr/lib${LIBDIRSUFFIX}/pkgconfig

cp -rL dist/include/* \
       ${PKG}/usr/include/${INTERNAL_APP_SDK_NAME}/ || exit 1

# Link pc files (for compatibility with 1.9.1)
ln -s libxul.pc \
  ${PKG}/usr/lib${LIBDIRSUFFIX}/pkgconfig/libxul-unstable.pc || exit 1
ln -s libxul-embedding.pc \
  ${PKG}/usr/lib${LIBDIRSUFFIX}/pkgconfig/libxul-embedding-unstable.pc || exit 1

# Fix multilib devel conflicts...
unset mozbits
if [ "${ARCH}" = "x86_64" ] ;then
  export mozbits=64
else
  export mozbits=32
fi

function install_file() {
genheader=$*
mv ${genheader}.h ${genheader}${mozbits}.h
cat > ${genheader}.h << EOF
// This file exists to fix multilib conflicts
#if defined(__x86_64__) || defined(__ia64__) || defined(__s390x__) || defined(__powerpc64__)
#include "${genheader}64.h"
#else
#include "${genheader}32.h"
#endif
EOF
}

if [ "${mozbits}" ] ;then
( cd ${PKG}/usr/include/${INTERNAL_APP_SDK_NAME}
  install_file "mozilla-config"
)

( cd ${PKG}/usr/include/${INTERNAL_APP_SDK_NAME}
  install_file "jsautocfg"
)

( cd ${PKG}/usr/include/${INTERNAL_APP_SDK_NAME}
  install_file "js-config"
)
fi

install -p -c -m 755 dist/bin/xpcshell \
  dist/bin/xpidl \
  dist/bin/xpt_dump \
  dist/bin/xpt_link \
  ${PKG}/${MOZ_APP_DIR}/

rm -rf ${PKG}/usr/include/${INTERNAL_APP_NAME}
rm -rf ${PKG}/usr/share/idl/${INTERNAL_APP_NAME}

rm -rf ${PKG}${MOZ_APP_SDK_DIR}/include
ln -s  ../../include/${INTERNAL_APP_SDK_NAME} \
       ${PKG}${MOZ_APP_SDK_DIR}/include

rm -rf ${PKG}${MOZ_APP_SDK_DIR}/idl
ln -s  ../../share/idl/${INTERNAL_APP_SDK_NAME} \
       ${PKG}${MOZ_APP_SDK_DIR}/idl

rm -rf ${PKG}${MOZ_APP_SDK_DIR}/sdk/include
ln -s  ../../../include/${INTERNAL_APP_SDK_NAME} \
       ${PKG}${MOZ_APP_SDK_DIR}/sdk/include

rm -rf ${PKG}${MOZ_APP_SDK_DIR}/sdk/idl
ln -s  ../../../share/idl/${INTERNAL_APP_SDK_NAME} \
       ${PKG}${MOZ_APP_SDK_DIR}/sdk/idl

find ${PKG}/usr/include -type f -name "*.h" | xargs chmod 644
find ${PKG}/usr/share/idl -type f -name "*.idl" | xargs chmod 644

rm -rf ${PKG}${MOZ_APP_SDK_DIR}/bin
ln -s  ../${INTERNAL_APP_NAME} \
       ${PKG}${MOZ_APP_SDK_DIR}/bin

rm -rf ${PKG}${MOZ_APP_SDK_DIR}/lib
ln -s  sdk/lib \
       ${PKG}${MOZ_APP_SDK_DIR}/lib

rm -rf ${PKG}${MOZ_APP_SDK_DIR}/sdk/lib/*.so
( cd ${PKG}${MOZ_APP_DIR} 
  for i in *.so; do
    ln -s ../../../${INTERNAL_APP_NAME}/${i} ${PKG}${MOZ_APP_SDK_DIR}/sdk/lib/${i}
  done
)

unset GREARCH
[ "${ARCH}" = "x86_64" ] && GREARCH=64

MOZILLA_GECKO_VERSION=$(./config/milestone.pl --topsrcdir=.)
mv ${PKG}/etc/gre.d/${MOZILLA_GECKO_VERSION}".system.conf" \
   ${PKG}/etc/gre.d/gre${GREARCH}.conf
chmod 644 ${PKG}/etc/gre.d/gre${GREARCH}.conf

mkdir -p ${PKG}/etc/ld.so.conf.d
cat > ${PKG}/etc/ld.so.conf.d/${NAME}-${ARCH}.conf <<EOF
${MOZ_APP_DIR}
EOF

# Use the system hunspell dictionaries
rm -rf ${PKG}${MOZ_APP_DIR}/dictionaries
ln -s ../../share/myspell ${PKG}${MOZ_APP_DIR}/dictionaries

find ${PKG} | xargs file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null

mkdir -p ${PKG}/usr/man/man1
zcat ${CWD}/${NAME}.1.gz > \
     ${PKG}/usr/man/man1/${NAME}.1 || exit 1

# Copy over the LICENSE
install -p -c -m 644 LICENSE ${PKG}/${MOZ_APP_DIR}/

# ghost files
touch ${PKG}/${MOZ_APP_DIR}/components/compreg.dat
touch ${PKG}/${MOZ_APP_DIR}/components/xpti.dat

rmdir -p ${PKG}/usr/share/applications

# Add a documentation directory:
mkdir -p ${DOCDIR}
cp -a \
  LICENSE ${CWD}/ChangeLog.SB \
  ${DOCDIR}/
find ${DOCDIR}/ -type d -print0 | xargs -0 chmod 0755
find ${DOCDIR}/ -type f -print0 | xargs -0 chmod 0644

# Compress and link manpages, if any:
if [ -d ${PKG}/usr/share/man ]; then
  mv ${PKG}/usr/share/man ${PKG}/usr/man
  rmdir ${PKG}/usr/share
fi
if [ -d ${PKG}/usr/man ]; then
  ( cd ${PKG}/usr/man
    for manpagedir in $(find . -type d -name "man*") ; do
      ( cd ${manpagedir}
        for eachpage in $( find . -type l -maxdepth 1) ; do
          ln -s $( readlink ${eachpage} ).gz ${eachpage}.gz
          rm ${eachpage}
        done
        gzip -9 *.?
        # Prevent errors
        rm -f *.gz.gz
      )
    done
  )
fi

mkdir -p ${PKG}/install
cat ${CWD}/slack-desc > ${PKG}/install/slack-desc
cat ${CWD}/slack-required > ${PKG}/install/slack-required

cat > ${PKG}/install/doinst.sh <<EOF
# Figure out our root directory
ROOTDIR=\$(pwd)
unset CHROOT
if test "\${ROOTDIR}" != "/"; then
  CHROOT="chroot \${ROOTDIR} "
  ROOTDIR="\${ROOTDIR}/"
fi
if [ -f usr/lib${LIBDIRSUFFIX}/${INTERNAL_APP_NAME}/components/compreg.dat ] ;then
  \${CHROOT} rm -f /usr/lib${LIBDIRSUFFIX}/${INTERNAL_APP_NAME}/components/compreg.dat 1> /dev/null 2> /dev/null
fi
if [ -f usr/lib${LIBDIRSUFFIX}/${INTERNAL_APP_NAME}/components/xpti.dat ] ;then
  \${CHROOT} rm -f /usr/lib${LIBDIRSUFFIX}/${INTERNAL_APP_NAME}/components/xpti.dat 1> /dev/null 2> /dev/null
fi

EOF

sed -i "s|_PACKAGER|${PACKAGER}|g; s|_BUILD_DATE|${DATE}|g" \
       ${PKG}/install/slack-desc

if [ "${SB_REP}" = "YES" ] ;then
  # Replicate slackbuild and patches
  mkdir -p ${SBDIR}/patches
  install -m0644 ${CWD}/slack-desc ${CWD}/slack-required ${CWD}/ChangeLog.SB \
                 ${CWD}/apply-patches.sh ${CWD}/${NAME}*mozconfig*  \
                 ${CWD}/{*.sh.in,*.1,}.gz ${CWD}/*.js ${CWD}/${NAME}.spec \
                 ${SBDIR}/
  install -m0755 ${CWD}/${NAME}.SlackBuild \
                 ${SBDIR}/${NAME}.SlackBuild
  install -m0644 ${CWD}/patches/*.* \
                 ${SBDIR}/patches/
fi

# Build package:
set +o xtrace        # no longer print commands upon execution

ROOTCOMMANDS="set -o errexit -o xtrace ; cd ${PKG} ;
  /bin/chown --recursive root:root .  ;"

ROOTCOMMANDS="${ROOTCOMMANDS}
  /sbin/makepkg --linkadd y --chown n ${PKGDEST}/${PKGNAME}.${PKGFORMAT} "

if test ${UID} = 0; then
  eval ${ROOTCOMMANDS}
  set +o xtrace
elif test "$(type -t fakeroot)" = 'file'; then
  echo -e "\e[1mEntering fakeroot environment.\e[0m"
  echo ${ROOTCOMMANDS} | fakeroot
else
  echo -e "\e[1mPlease enter your root password.\e[0m (Consider installing fakeroot.)"
  /bin/su -c "${ROOTCOMMANDS}"
fi

# Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
  echo "Cleaning..."
  if [ -d ${TMP}/${SRCDIR} ]; then
    rm -rf ${TMP}/${SRCDIR} && echo "${TMP}/${SRCDIR} cleanup completed"
  fi
  if [ -d ${PKG} ]; then
    rm -rf ${PKG} && echo "${PKG} cleanup completed"
  fi
  rmdir ${TMP} && echo "${TMP} cleanup completed"
fi
exit 0
