#!/bin/bash
#
# Showtime configure shared functions
#
# Copyright (c) 2005-2008 Andreas Öman
#
# Based on FFmpeg's configure script:
#
# Copyright (c) 2000-2002 Fabrice Bellard
# Copyright (c) 2005-2008 Diego Biurrun
# Copyright (c) 2005-2008 Mans Rullgard
#

TOPDIR=`pwd`
BUILD=${CONFIGURE_POSTFIX}
TMPDIR=${TOPDIR}/tmp
GLW_DEFAULT_SKIN="default"
DEFAULT_LOGTARGET=""
LIBSPOTIFY_VERSION="12.1.51"

CONFIG_LIST="
 libasound
 libpulse
 libfreetype
 libpthread
 zlib
 dvd
 dvd_linux
 dvd_wii
 cdda
 cddb
 glw
 glw_frontend_x11
 glw_frontend_wii
 glw_frontend_ps3
 glw_frontend_cocoa
 glw_backend_opengl
 glw_backend_gx
 glw_backend_rsx
 glw_backend_opengl_es
 gu
 libogc
 spotify
 libspotify_load_runtime
 lirc
 stdin
 release
 avahi
 appleremote
 bonjour
 nvctrl
 libgme
 libxss
 libxv
 serdev
 openssl
 polarssl
 librtmp
 libx11
 libxext
 locatedb
 spotlight
 vdpau
 spidermonkey
 libxxf86vm
 libxrandr
 libsidplay2
 httpserver
 timegm
 inotify
 fsevents
 realpath
 trex
 emu_thread_specifics
 ps3_vdec
 libfontconfig
 readahead_cache
 sqlite_vfs
 sqlite_locking
 sqlite_internal
 libav
 vda
 tlsf
 airplay
 webpopup
 valgrind
"

cleanup() {
    rm -rf $TMPDIR
}

die() {
    cleanup
    echo "Configure failed"
    exit 1
}

die_invalid_opt() {
    echo "Invalid option: $1"
    die
}

die_cause() {
    echo "$1"
    die
}

set_all(){
    value=$1
    shift
    for var in $*; do
        eval $var=$value
    done
}

enable(){
    set_all yes $*
}

disable(){
    set_all no $*
}


enabled(){
    eval test "x${!1}" = "xyes"
}

disabled(){
    eval test "x${!1}" = "xno" -o "x${!1}" = "x"
}

toupper(){
    echo "$@" | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
}

is_in(){
    value=$1
    shift
    for var in $*; do
        [ $var = $value ] && return 0
    done
    return 1
}

print_config(){
    pfx=$1
    header=$2
    makefile=$3
    shift 3
    for cfg; do
        ucname="`toupper $cfg`"
        if enabled $cfg; then
            echo "#define ${pfx}${ucname} 1" >> $header
            echo "#define ENABLE_${ucname} 1" >> $header
            echo "${pfx}${ucname}=yes" >> $makefile
        else
            echo "#define ENABLE_${ucname} 0" >> $header
        fi
    done
}

cp_if_changed(){
    cmp -s "$1" "$2" || cp -f "$1" "$2"
}

download_file() {
    local __resultvar=$2
    local URL_HASH=`echo "$1" | shasum  | awk '{print $1}'`
    mkdir -p ${TOPDIR}/.downloadcache
    local DLPATH=${TOPDIR}/.downloadcache/${URL_HASH}
    if [ ! -f "${DLPATH}" ]; then
	echo "Downloading $1"
	curl -f -L -o "${DLPATH}" "$1" || die_cause "Unable to download file" 
    else
	echo "Found in cache: $1"
    fi
    eval $__resultvar="$DLPATH"
}



common_help(){
  echo "Usage: configure [options]"
  echo "Options: [defaults in brackets after descriptions]"
  echo
  echo "Standard options:"
  echo "  --help                   Print this message"
  echo "  --with-libav=PREFIX      Path to where libav is installed."
  echo "                           By default Showtime will build libav itself."
  echo "  --build=BUILD            Build in build.BUILD [build.$BUILD]"
  echo "  --jobs=N                 Allow N jobs at once"
  echo "  --release                Stage for release"
  echo "  --cleanbuild             Erase builddir before configuring"
  echo "  --ccache                 Enable use of ccache"
  echo "  --extra-cflags           Extra cflags"
  echo "  --extra-ldflags          Extra ldflags"
  echo ""
  echo "Platform specific options:"
}




common_opt(){
  case "$1" in

  --with-libav=*) LIBAV_PATH="$2"
  ;;

  --build=*) BUILD="$2"
  ;;
  --extra-cflags=*) EXTRA_CFLAGS="$2"
  ;;
  --extra-ldflags=*) EXTRA_LDFLAGS="$2"
  ;;

  --enable-?*|--disable-?*)
  eval $(echo "$1" | sed 's/--/action=/;s/-/ option=/;s/-/_/g')
  if is_in $option $CONFIG_LIST; then
      $action $option
  else
      die_invalid_opt $1
  fi
  ;;

  --jobs=*)
  ;;

  --cleanbuild) enable cleanbuild
  ;;

  --ccache) CC="ccache $CC"
  ;;

  --release) enable release
  ;;
  *)
  die_invalid_opt $1
  esac
}


setup_env(){
    BUILDDIR=build.${BUILD}

    if enabled cleanbuild; then
	echo "Cleaning builddir: ${BUILDDIR}"
	rm -rf ${BUILDDIR}
    fi

    mkdir -p ${BUILDDIR}
    BUILDDIR=`cd ${BUILDDIR} && pwd`

    CONFIG_H=${BUILDDIR}/config.h.tmp
    CONFIG_MAK=${BUILDDIR}/config.mak.tmp
    CONFIG_DEF=${TOPDIR}/config.default

    mkdir -p ${BUILDDIR}
    
    # Create a tmpdir used during configure
    mkdir -p ${TMPDIR}
    TMPDIR=`cd ${TMPDIR} && pwd`
    
    # Create config.mak
    cat > ${CONFIG_MAK} << EOF 
# Automatically generated by configure, do not edit
CONFIGURE_ARGS=$@
TOPDIR=$TOPDIR
OS=$OS
CONFIGURE_POSTFIX=$CONFIGURE_POSTFIX
CFLAGS_cfg += ${EXTRA_CFLAGS}
LDFLAGS_cfg += ${EXTRA_LDFLAGS}
EOF
   
    # Create config.h
    cat > ${CONFIG_H} << EOF 
/* Automatically generated by configure, do not edit */
#define CONFIGURE_ARGS "$@"
#define SHOWTIME_DEFAULT_UI "${DEFAULT_UI}"
#define SHOWTIME_DEFAULT_LOGTARGET "${DEFAULT_LOGTARGET}"
EOF

    # Create config.default
    cat > ${CONFIG_DEF} << EOF 
# Automatically generated by configure, do not edit
BUILD ?= $BUILD
EOF


}

enable libav

libav_setup() {
    if disabled libav; then
        disable dvd
        disable librtmp
        return
    fi

    if [ "x${LIBAV_PATH}" != "x" ]; then
	return
    fi


    status=`git submodule status ext/libav | cut -b 1`
    echo "Updating libav, submodule status = $status"
    git submodule update --init ext/libav
    echo "Configuring libav..."
    
    LIBAV_BUILD_DIR=${BUILDDIR}/libav/build
    LIBAV_INSTALL_DIR=${BUILDDIR}/libav/install

    [ "$status" = "+" ] && echo "Cleaning libav build dir" && rm -rf "${LIBAV_BUILD_DIR}"
    mkdir -p "${LIBAV_BUILD_DIR}"
    mkdir -p "${LIBAV_INSTALL_DIR}"

    LIBAV_COMMON_FLAGS="--disable-encoders --disable-bsfs --disable-filters --disable-muxers --disable-devices --disable-demuxer=rtp --disable-protocol=rtp --disable-bzlib --disable-decoder=twinvq --disable-decoder=snow --disable-decoder=cavs --enable-encoder=png --disable-avconv --disable-avprobe --disable-avfilter"

    (cd ${LIBAV_BUILD_DIR} && ${TOPDIR}/ext/libav/configure ${LIBAV_ARCH_FLAGS} ${LIBAV_COMMON_FLAGS} --prefix=${LIBAV_INSTALL_DIR} --extra-cflags="${LIBAV_CFLAGS} ${EXTRA_CFLAGS}" --extra-ldflags="${LIBAV_LDFLAGS} ${EXTRA_LDFLAGS}" --cc="${CC}") || die

    LIBAV_PATH=${LIBAV_INSTALL_DIR}
    echo >>${CONFIG_MAK} "LIBAV_BUILD_DIR=${LIBAV_BUILD_DIR}"
    echo >>${CONFIG_MAK} "LIBAV_INSTALL_DIR=${LIBAV_INSTALL_DIR}"

    echo >>${CONFIG_MAK} "STAMPS += build.${BUILD}/libav.stamp"
    rm -f "build.${BUILD}/libav.stamp"
}


#
#
#
rtmpdump_setup() {
    status=`git submodule status ext/rtmpdump | cut -b 1`
    echo "Updating rtmpdump, submodule status = $status"
    git submodule update --init ext/rtmpdump
}



#
#
#
zlib_setup()
{
    ZLIB_VER="1.2.3"
    download_file http://commondatastorage.googleapis.com/nativeclient-mirror/nacl/zlib-${ZLIB_VER}.tar.gz zlibtarball

    ZLIB_SRC_DIR=${BUILDDIR}/zlib-${ZLIB_VER}
    ZLIB_INSTALL_DIR=${BUILDDIR}/zlib/install

    tar -x -C "${BUILDDIR}" -f "${zlibtarball}"
    mkdir -p "${ZLIB_INSTALL_DIR}"

    (cd ${ZLIB_SRC_DIR} && \
        CC=${TOOLCHAIN}gcc AR="${TOOLCHAIN}ar -r" RANLIB=${TOOLCHAIN}ranlib \
        ./configure --static --prefix=${ZLIB_INSTALL_DIR})
    
    (cd ${ZLIB_SRC_DIR} && make install)

    echo >>${CONFIG_MAK} "CFLAGS_cfg += -I${ZLIB_INSTALL_DIR}/include"
    echo >>${CONFIG_MAK} "LDFLAGS_cfg += -L${ZLIB_INSTALL_DIR}/lib"
}


#
#
#
bzip2_setup()
{
    BZIP2_VER="1.0.6"
    download_file http://www.bzip.org/${BZIP2_VER}/bzip2-${BZIP2_VER}.tar.gz bzip2tarball

    BZIP2_SRC_DIR=${BUILDDIR}/bzip2-${BZIP2_VER}
    BZIP2_INSTALL_DIR=${BUILDDIR}/bzip2/install

    tar -x -C "${BUILDDIR}" -f "${bzip2tarball}"
    mkdir -p "${BZIP2_INSTALL_DIR}"

    sed -i s#^CC=gcc\$#CC=${TOOLCHAIN}gcc# ${BZIP2_SRC_DIR}/Makefile
    sed -i s#^AR=ar\$#AR=${TOOLCHAIN}ar# ${BZIP2_SRC_DIR}/Makefile
    sed -i s#^RANLIB=ranlib\$#RANLIB=${TOOLCHAIN}ranlib# ${BZIP2_SRC_DIR}/Makefile

    echo >>${CONFIG_MAK} "BZIP2_BUILD_DIR=${BZIP2_SRC_DIR}"
    echo >>${CONFIG_MAK} "BZIP2_INSTALL_DIR=${BZIP2_INSTALL_DIR}"
    echo >>${CONFIG_MAK} "STAMPS += build.${BUILD}/bzip2.stamp"
    rm -f "build.${BUILD}/bzip2.stamp"

    echo >>${CONFIG_MAK} "CFLAGS_cfg += -I${BZIP2_INSTALL_DIR}/include"
    echo >>${CONFIG_MAK} "LDFLAGS_cfg += -L${BZIP2_INSTALL_DIR}/lib"

}



#
#
#
freetype_setup()
{
    FREETYPE_VER="2.4.9"

    download_file http://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPE_VER}.tar.gz freetypetarball

    FREETYPE_SRC_DIR=${BUILDDIR}/freetype-${FREETYPE_VER}
    FREETYPE_BUILD_DIR=${BUILDDIR}/freetype/build
    FREETYPE_INSTALL_DIR=${BUILDDIR}/freetype/install

    tar -x -C "${BUILDDIR}" -f "${freetypetarball}"
    mkdir -p "${FREETYPE_BUILD_DIR}"
    mkdir -p "${FREETYPE_INSTALL_DIR}"

    
    (cd ${FREETYPE_BUILD_DIR} && \
        CC=${TOOLCHAIN}gcc AR=${TOOLCHAIN}ar RANLIB=${TOOLCHAIN}ranlib \
        ${FREETYPE_SRC_DIR}/configure \
        $1 \
	--prefix=${FREETYPE_INSTALL_DIR} \
	--enable-static=yes \
	--enable-shared=no)

    echo >>${CONFIG_MAK} "FREETYPE_BUILD_DIR=${FREETYPE_BUILD_DIR}"
    echo >>${CONFIG_MAK} "STAMPS += build.${BUILD}/freetype.stamp"
    rm -f "build.${BUILD}/freetype.stamp"

    echo >>${CONFIG_MAK} "CFLAGS_cfg += -I${FREETYPE_INSTALL_DIR}/include -I${FREETYPE_INSTALL_DIR}/include/freetype2"
    echo >>${CONFIG_MAK} "LDFLAGS_cfg += -L${FREETYPE_INSTALL_DIR}/lib -lfreetype -lbz2"
}






#
# Do final common stuff
#
finalize() {

    if enabled libav; then
	echo >>${CONFIG_MAK} "CFLAGS_cfg += -I${LIBAV_PATH}/include"
	echo >>${CONFIG_MAK} "LDFLAGS_cfg += -L${LIBAV_PATH}/lib -lavresample -lswscale -lavformat -lavcodec -lavutil"
    fi

    if enabled polarssl; then
	echo "Using built-in polarssl"
	echo >>${CONFIG_MAK} "CFLAGS_cfg += -DUSE_POLARSSL"
    fi


    # Generate default skin path for GLW
    if enabled glw; then
	echo >>${CONFIG_MAK} "BUNDLES+=glwskins/${GLW_DEFAULT_SKIN}"
	echo >>${CONFIG_H} "#define SHOWTIME_GLW_DEFAULT_SKIN \""${GLW_DEFAULT_SKIN}"\""
    fi

    # Generate resource path for GU
    if enabled gu; then
	echo >>${CONFIG_MAK} "BUNDLES+=guresources"
    fi

    # Fonts
    echo >>${CONFIG_MAK} "BUNDLES+=resources/fonts"
    
    # SVG icons
    echo >>${CONFIG_MAK} "BUNDLES+=resources/svg"

    # Languages
    echo >>${CONFIG_MAK} "BUNDLES+=lang"

    # sqlite
    if enabled sqlite_vfs; then
	echo >>${CONFIG_MAK} "SQLITE_CFLAGS_cfg += -DSQLITE_OS_OTHER=1 -DSQLITE_DEFAULT_LOCKING_MODE=1"
    fi

    if enabled sqlite_locking; then
	echo >>${CONFIG_MAK} "SQLITE_CFLAGS_cfg += -DSQLITE_MUTEX_NOOP"
    fi

    if enabled sqlite_internal; then
	echo >>${CONFIG_MAK} "CFLAGS_cfg += -Iext/sqlite"
    fi

    # Release tag
    if enabled release; then
	echo >>${CONFIG_MAK} "CFLAGS_dbg = -DNDEBUG -D_NDEBUG"
    else
	echo >>${CONFIG_MAK} "CFLAGS_dbg = -DJS_GC_ZEAL -DDEBUG=1"
    fi

    cat >> ${CONFIG_MAK} << EOF 
LDFLAGS_cfg += -lz -lm
EOF
  
    # Generate config files
    print_config CONFIG_ ${CONFIG_H} ${CONFIG_MAK} $CONFIG_LIST

    cp_if_changed ${CONFIG_H} ${BUILDDIR}/config.h
    cp_if_changed ${CONFIG_MAK} ${BUILDDIR}/config.mak
    rm -f ${CONFIG_H} ${CONFIG_MAK}

    cleanup
}
