#!/bin/bash
ulimit -s unlimited
shopt -s extglob

# Mplayer.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter for ARMedslack.
#
# Copyright 2006, 2007, 2008, 2010, 2011 Eric Hameleers, Eindhoven, NL
# All rights reserved.
#
#   Permission to use, copy, modify, and distribute this software for
#   any purpose with or without fee is hereby granted, provided that
#   the above copyright notice and this permission notice appear in all
#   copies.
#
#   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS AND COPYRIGHT HOLDERS AND THEIR
#   CONTRIBUTORS 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.

###
#/etc/mplayer/mplayer.conf:
# vo=x11
# ao=alsa
###

# Record toolchain & other info for the build log:
slackbuildinfo

# Versions from the original MPlayer.SlackBuild:
PKGNAM=MPlayer
#BRANCH=${BRANCH:-1.3}        # leave empty if you want to build MPlayer trunk
#PKGVERSION=${BRANCH}_${VERSION} # so the package becomes MPlayer-1.1_blah-arm-1.txz
PKGVERSION=${VERSION} # We'll take what ever version is in Slackware's package file name.

# Paths to skeleton port's source & real Slackware source tree:
slackset_var_cwds

# Temporary build locations:
export TMPBUILD=$TMP/build-$PKGNAM
export PKG=$TMP/package-$PKGNAM
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD

# MPlayer build Logs etc are written here:
OUTPUT=$TMPBUILD/logs-out
mkdir -vpm755 $OUTPUT

DOCS="AUTHORS Changelog Copyright LICENSE README VERSION DOCS/HTML DOCS/tech"

DEFSKIN=${DEFSKIN:-"Blue"}  # Download more skins at the following url:
SKINVER=${SKINVER:-"1.13"}   # http://www.mplayerhq.hu/design7/dload.html

# Available languages: all cs de en es fr hu it pl ru zh_CN
LANGUAGES="en,de,es,fr"

# Doesn't work on ARM:
# --enable-runtime-cpudetection is failing on 32-bit, so we'll set -march=i586
# manually after ./configure.
#EXTRACONFIGUREOPTIONS="--enable-runtime-cpudetection"
EXTRACONFIGUREOPTIONS=""

# Where the WIN32 codecs are expectedfor instance
CODECSDIR=/usr/lib${LIBDIRSUFFIX}/codecs

# -- PATENT ALERT! --
# MPLayer can be built with AMR audio encoders
# (needed for FLV and .3GP videos) but these libraries are 'contaminated'
# with patents from 3GPP.
# Also, the AAC encoder has patent issues.
# You can build these patended algorithms into ffmpeg, and if you are an
# ordinary end user, no one will bother you for using them.
# For the binaries based on this SlackBuild that I distribute, it is a
# different story. I am not allowed to distribute binary packages that
# incorporate patented code. So here you go. My Slackware package was
# built with "USE_PATENTS=NO" i.e. without using
# the faac, AMR and dvdcss libraries.
# ---------------------------------------------------------------------------
USE_PATENTS=${USE_PATENTS:-"NO"}

OSDFONTS="LiberationSans-Regular.ttf \
          Arialuni.ttf arial.ttf \
          DejaVuSans.ttf Vera.ttf"

# Where do we look for sources?
SRCDIR=$CWD

SOURCE[0]="$SRCDIR/${PKGNAM}-${VERSION}.tar.!(*sign|*asc|*sig)"
SRCURL[0]=""

# The default skin to use (we need to add at least one)
SOURCE[1]="$SRCDIR/${DEFSKIN}-${SKINVER}.tar.!(*sign|*asc|*sig)"
SRCURL[1]="http://www.mplayerhq.hu/MPlayer/skins/${DEFSKIN}-${SKINVER}.tar.!(*sign|*asc|*sig)"

# Extract source:
echo "Extracting the source archive(s) for $PKGNAM..."
tar xvvf ${SOURCE[0]}
cd ${PKGNAM}*/ || exit 1
slackhousekeeping

# Determine what X we're running (the modular X returns the prefix
# in the next command, while older versions stay silent):
XPREF=$(pkg-config --variable=prefix x11) || true
[ "$XPREF" == "" ] && XPREF='/usr/X11R6'

# Remove support for patent encumbered and possibly illegal code:
if [ "$USE_PATENTS" != "YES" ]; then
   DO_PATENTED="--disable-libopencore_amrnb \
               --disable-libopencore_amrwb"
else
   DO_PATENTED=""
fi

# fix building against samba 4
zcat $SRCDIR/include-samba-4.0.patch.gz | patch -p1 --verbose || exit 1

# Patch to only use pld instruction on CPUs that support it.
# ARMedslack patch by Jim Hawkins.
#patch --verbose -p1 < $PORTCWD/sources/disable_arm_pld_instruction.diff || failpatch

echo "Building ..."
# MPlayer wants to automatically determine compiler flags,
# so we don't provide CFLAGS:
#  --extra-ldflags="-lharfbuzz -lfreetype" \
./configure \
   --prefix=/usr \
   --mandir=/usr/man \
   --confdir=/etc/mplayer \
   --enable-gui \
   --enable-menu \
   --enable-vdpau \
   --disable-arts \
   --disable-ossaudio \
   --disable-bitmap-font \
   --disable-ffmpeg_a \
   --codecsdir=${CODECSDIR} \
   --language="${LANGUAGES}" \
   ${EXTRACONFIGUREOPTIONS} \
   ${DO_PATENTED} || exit 1

# So that MPlayer does not report "UNKNOWN" as its version:
echo $VERSION > VERSION
make $NUMJOBS || make || exit 1

# Set -march/-mtune manually since runtime cpu detection causes a compile error
# on 32-bit x86:
if [ "$ARCH" = "i586" ]; then
  sed -i "s/march=native/march=i586/g" config.mak
  sed -i "s/mtune=native/mtune=generic/g" config.mak
fi

# Install:
make DESTDIR=$PKG install || exit 1

# Build the html documentation (not all languages are available):
if [ "$LANGUAGES" = "all" ]; then
  # make html-chunked
  make html-single
else
  for i in $(echo $LANGUAGES | tr , ' ') ; do
    # make html-chunked-$i ;
    make html-single-$i ;
  done
fi

# Prepare the configfile:
mkdir -p $PKG/etc/mplayer
cp -fav etc/example.conf $PKG/etc/mplayer/mplayer.conf.new

# Install our default skin:
cd $PKG/usr/share/mplayer/skins
tar xvvf ${SOURCE[1]}
chown -R root:root *
chmod -R u+w,go+r-w,a+X-s *
ln -s ${DEFSKIN} default
cd -

# Add this to the doinst.sh:
mkdir -p $PKG/install
cat <<EOINS >> $PKG/install/doinst.sh
# Handle the incoming configuration files:
config() {
  for infile in \$1; do
    NEW="\$infile"
    OLD="\`dirname \$NEW\`/\`basename \$NEW .new\`"
    # If there's no config file by that name, mv it over:
    if [ ! -r \$OLD ]; then
      mv \$NEW \$OLD
    elif [ "\`cat \$OLD | md5sum\`" = "\`cat \$NEW | md5sum\`" ]; then
      # toss the redundant copy
      rm \$NEW
    fi
    # Otherwise, we leave the .new copy for the admin to consider...
  done
}
# Installing a bitmap font is considered deprecated; use a TTF font instead.
# We try to link to an installed TTF font at install time.
# Configure a default TrueType font to use for the OSD :
if [ ! -f usr/share/mplayer/subfont.ttf ]; then
  for font in ${OSDFONTS}; do
    if [ -f .${XPREF}/lib${LIBDIRSUFFIX}/X11/fonts/TTF/\${font} ]; then
      ( cd usr/share/mplayer/
        ln -sf ${XPREF}/lib${LIBDIRSUFFIX}/X11/fonts/TTF/\${font} subfont.ttf
      )
      break
    fi
  done
fi

# Prepare the new configuration file
config etc/mplayer/mplayer.conf.new

# Update the desktop database:
if [ -x usr/bin/update-desktop-database ]; then
  chroot . /usr/bin/update-desktop-database usr/share/applications 1> /dev/null 2> /dev/null
fi

# Update hicolor theme cache:
if [ -e usr/share/icons/hicolor/icon-theme.cache ]; then
   if [ -x usr/bin/gtk-update-icon-cache ]; then
     chroot . /usr/bin/gtk-update-icon-cache /usr/share/icons/hicolor >/dev/null 2>&1
   fi
fi

# Update the mime database:
if [ -x usr/bin/update-mime-database ]; then
  chroot . /usr/bin/update-mime-database usr/share/mime >/dev/null 2>&1
fi

EOINS

# Add documentation:
mkdir -p $PKG/usr/doc/$PKGNAM-$PKGVERSION
cp -a $DOCS $PKG/usr/doc/$PKGNAM-$PKGVERSION || true
cp -a $SRCDIR/$(basename $0) $PKG/usr/doc/$PKGNAM-$PKGVERSION/$PKGNAM.SlackBuild
mv $PKG/usr/doc/$PKGNAM-$PKGVERSION/HTML $PKG/usr/doc/$PKGNAM-$PKGVERSION/html
# Save a sample of all configuration files:
for i in etc/*.conf ; do
  cp $i $PKG/usr/doc/$PKGNAM-$PKGVERSION/$(basename $i)-sample
done
# Save a transcript of all configured options for this specific build:
if [ -n $OUTPUT/configure-${PKGNAM}.log ]; then
  cat $OUTPUT/configure-${PKGNAM}.log \
    | sed -n "/^Config files successfully generated/,/^'config.h' and 'config.mak' contain your configuration options./p" \
    > $PKG/usr/doc/$PKGNAM-$PKGVERSION/${PKGNAM}.configuration
fi
find $PKG/usr/doc -type f -exec chmod 644 {} \;

# Add a package description:
mkdir -p $PKG/install
cat $SRCDIR/slack-desc > $PKG/install/slack-desc
if [ -f $SRCDIR/doinst.sh ]; then
  cat $SRCDIR/doinst.sh >> $PKG/install/doinst.sh
fi

# Apply generic Slackware packaging policies:
cd $PKG
slackstripall   # strip all .a archives and all ELFs
slack_delete_lafiles # delete usr/lib{,64}/*.la
#slackstriprpaths     # strip rpaths
slackgzpages -i # compress man & info pages and delete usr/info/dir
slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs

export VERSION=$PKGVERSION
export SLACKPACKAGE=$PKGNAM-$VERSION-$ARCH-$BUILD.txz

slackmp         # run makepkg -l y -c n

# Perform any final checks on the package:
cd $PKG
slackhlinks     # search for any hard links
