# Usage: setup_toolchain <target|host>
setup_toolchain() {
  if [ "$1" = target ]; then
    export CC=$TARGET_CC
    export CXX=$TARGET_CXX
    export LD=$TARGET_LD
    export AS=$TARGET_AS
    export AR=$TARGET_AR
    export NM=$TARGET_NM
    export RANLIB=$TARGET_RANLIB
    export OBJCOPY=$TARGET_OBJCOPY
    export STRIP=$TARGET_STRIP
    export QMAKE=$TARGET_QMAKE
    export MOC=$TARGET_MOC
    export RCC=$TARGET_RCC
    export UIC=$TARGET_UIC
    export CPPFLAGS="$TARGET_CPPFLAGS"
    export CFLAGS="$TARGET_CFLAGS"
    export CXXFLAGS="$TARGET_CXXFLAGS"
    export ASFLAGS="$TARGET_ASFLAGS"
    export LDFLAGS="$TARGET_LDFLAGS"
    export BJAM="$ROOT/$TOOLCHAIN/bin/bjam"
    export SDL_CONFIG=$LIB_PREFIX/bin/sdl-config
    export SDLCONFIG=$LIB_PREFIX/bin/sdl-config
    export DVDREAD_CONFIG=$LIB_PREFIX/bin/dvdread-config
    export DVDNAV_CONFIG=$LIB_PREFIX/bin/dvdnav-config
    export XSLT_CONFIG=$LIB_PREFIX/bin/xslt-config
    export FREETYPE_CONFIG=$LIB_PREFIX/bin/freetype-config
    export DIRECTFB_CONFIG=$ROOT/$TOOLCHAIN/bin/directfb-config
    export LIBGCRYPT_CONFIG=$ROOT/$TOOLCHAIN/bin/libgcrypt-config
    export GPG_ERROR_CONFIG=$LIB_PREFIX/bin/gpg-error-config
    export PKG_CONFIG=$ROOT/$TOOLCHAIN/bin/pkg-config
    export PKG_CONFIG_PATH=$LIB_PREFIX/lib/pkgconfig:$LIB_PREFIX/share/pkgconfig
    export QT_MKSPECS=$LIB_PREFIX/share/qt4/mkspecs/linux-g++-openbricks
    export QMAKESPEC=$QT_MKSPECS
    export QT_PATH_INCLUDES=$LIB_PREFIX/include/qt4
    export QT_PATH_LIBS=$LIB_PREFIX/lib
  elif [ "$1" = host ]; then
    export AWK=$HOST_AWK
    export CC=$HOST_CC
    export CXX=$HOST_CXX
    export LD=$HOST_LD
    export AS=$HOST_AS
    export AR=$HOST_AR
    export NM=$HOST_NM
    export RANLIB=$HOST_RANLIB
    export OBJCOPY=$HOST_OBJCOPY
    export STRIP=$HOST_STRIP
    export CPPFLAGS="$HOST_CPPFLAGS"
    export CFLAGS="$HOST_CFLAGS"
    export CXXFLAGS="$HOST_CXXFLAGS"
    export LDFLAGS="$HOST_LDFLAGS"
    export FREETYPE_CONFIG=$ROOT/$TOOLCHAIN/bin/freetype-config
    export PKG_CONFIG=$ROOT/$TOOLCHAIN/bin/pkg-config
    export PKG_CONFIG_PATH="$ROOT/$TOOLCHAIN/lib/pkgconfig:$ROOT/$TOOLCHAIN/share/pkgconfig"
    export M4=$ROOT/$TOOLCHAIN/bin/m4
    export AUTOCONF=$ROOT/$TOOLCHAIN/bin/autoconf
    export AUTORECONF=$ROOT/$TOOLCHAIN/bin/autoreconf
    export ACLOCAL=$ROOT/$TOOLCHAIN/bin/aclocal
    export AUTOHEADER=$ROOT/$TOOLCHAIN/bin/autoheader
    export AUTOMAKE=$ROOT/$TOOLCHAIN/bin/automake
    export AUTOPOINT=$ROOT/$TOOLCHAIN/bin/autopoint
    export AUTOSCAN=$ROOT/$TOOLCHAIN/bin/autoscan
    export AUTOUPDATE=$ROOT/$TOOLCHAIN/bin/autoupdate
    export AUTOM4TE=$ROOT/$TOOLCHAIN/bin/autom4te
    export LIBTOOL=$ROOT/$TOOLCHAIN/bin/libtool
    export LIBTOOLIZE=$ROOT/$TOOLCHAIN/bin/libtoolize
    export PKG_PROG_PKG_CONFIG=$PKG_CONFIG
  fi
}

# Usage: apply_patch <package> <patch>
apply_patch() {
  get_meta $1
  echo "## Applying patch: $2"
  cat $2 | patch -d $PKG_BUILD_DIR -p1 >&$VERBOSE_OUT
}

# Usage: create_stamp <stamp_file>
create_stamp() {
  stamp_file=$1

  if [ ! -r build/config/options ]; then
    # for early packages we just touch the stamp
    touch $stamp_file
    return
  fi

  . build/config/options

  for i in `sed -n "s/^.*\(^[a-zA-Z0-9_-]*\)=.*$/\1/p" build/config/options`; do
    eval val=\$$i
    echo "STAMP_$i=\"$val"\" >> $stamp_file
  done
}

# Usage: value=`valueof <variable>`
valueof() {
  local tmp=
  local var="$1"

  eval tmp="\$$var"
  echo "$tmp"
}

# Usage: get_meta <package>
get_meta() {

  # clear PKG_* variables
  for var in `set | grep -E '^PKG_.*$' | cut -f1 -d=`; do
    [ "$var" != PKG_CONFIG -a "$var" != PKG_CONFIG_PATH ] && unset $var
  done

  # set default values
  PKG_NAME=$1
  PKG_VERSION="0.0invalid"
  PKG_REV=0
  PKG_MD5=
  PKG_SHA256=
  PKG_ARCH=any
  PKG_LICENSE=free
  PKG_PRIORITY=optional
  PKG_SECTION=misc
  PKG_SHORTDESC="$1 (autogenerated)"

  # populate variables
  . $ROOT/$CONFIG/use
  [ -r $ROOT/$PACKAGES/$1/meta ] && . $ROOT/$PACKAGES/$1/meta

  # check for platform-specific package overlay
  PLATFORM_META="$PLATFORM_PACKAGES/$1/meta"
  [ -r "$PLATFORM_META" ] && . "$PLATFORM_META"

  # check for machine-specific package overlay
  MACHINE_META="$MACHINE_PACKAGES/$1/meta"
  [ -r "$MACHINE_META" ] && . "$MACHINE_META"

  # check for flavour-specific package overlay
  FLAVOUR_META="$FLAVOUR_PACKAGES/$1/meta"
  [ -r "$FLAVOUR_META" ] && . "$FLAVOUR_META"

  case "$PKG_ARCH" in
    any) PKG_OPK_ARCH="$TARGET_SUBARCH" ;;
    all) PKG_OPK_ARCH="all" ;;
    *)   OK_ARCH=no
         for i in $PKG_ARCH; do
           if [ "$i" = "$TARGET_ARCH" ]; then
             OK_ARCH=yes
             break
           fi
         done
         if [ "$OK_ARCH" = yes ]; then
           PKG_OPK_ARCH="$TARGET_SUBARCH"
         else
           PKG_OPK_ARCH="unsupported"
         fi
         ;;
  esac

  for use in $PKG_USE; do
    if pkg_uses $PKG_NAME $use; then
      tmp=`valueof "PKG_BUILD_DEPENDS_${use}"`
      if [ -n "$tmp" ]; then
        if [ -n "$PKG_BUILD_DEPENDS" ]; then
          PKG_BUILD_DEPENDS="$PKG_BUILD_DEPENDS $tmp"
        else
          PKG_BUILD_DEPENDS="$tmp"
        fi
      fi
      tmp=`valueof "PKG_RUN_DEPENDS_${use}"`
      if [ -n "$tmp" ]; then
        if [ -n "$PKG_RUN_DEPENDS" ]; then
          PKG_RUN_DEPENDS="$PKG_RUN_DEPENDS $tmp"
        else
          PKG_RUN_DEPENDS="$tmp"
        fi
      fi
      tmp=`valueof "PKG_DEPENDS_${use}"`
      if [ -n "$tmp" ]; then
        if [ -n "$PKG_DEPENDS" ]; then
          PKG_DEPENDS="$PKG_DEPENDS $tmp"
        else
          PKG_DEPENDS="$tmp"
        fi
      fi
    fi
  done

  if [ -n "$PKG_PARENT" -a "$PKG_NO_PARENT_DEPENDS" != yes ]; then
    if [ -n "$PKG_BUILD_DEPENDS" ]; then
      PKG_BUILD_DEPENDS="$PKG_BUILD_DEPENDS $PKG_PARENT"
    else
      PKG_BUILD_DEPENDS="$PKG_PARENT"
    fi
  fi

  if [ -n "$PKG_PARENT" ]; then
    [ "$PKG_VERSION" = "0.0invalid" ] && \
      PKG_VERSION=`( get_meta $PKG_PARENT; echo $PKG_VERSION )`
    [ "$PKG_REV" = "0" ] && \
      PKG_REV=`( get_meta $PKG_PARENT; echo $PKG_REV )`
  fi

  PKG_BUILD_DIR="$BUILD/${PKG_NAME}-${PKG_VERSION}"

  if [ -n "$PKG_DEPENDS" ]; then
    if [ -n "$PKG_BUILD_DEPENDS" ]; then
      PKG_BUILD_DEPENDS="$PKG_BUILD_DEPENDS $PKG_DEPENDS"
    else
      PKG_BUILD_DEPENDS="$PKG_DEPENDS"
    fi
    if [ -n "$PKG_RUN_DEPENDS" ]; then
      PKG_RUN_DEPENDS="$PKG_RUN_DEPENDS $PKG_DEPENDS"
    else
      PKG_RUN_DEPENDS="$PKG_DEPENDS"
    fi
  fi

  if [ -n "$PKG_RUN_DEPENDS" ]; then
    PKG_OPK_DEPENDS=`echo $PKG_RUN_DEPENDS | sed 's/ /, /g'`
  else
    PKG_OPK_DEPENDS=""
  fi

  [ -z "$PKG_DEV_DEPENDS" ] && PKG_DEV_DEPENDS="$PKG_BUILD_DEPENDS"
  if [ -n "$PKG_DEV_DEPENDS" ]; then
    PKG_OPK_DEV_DEPENDS=`echo $PKG_DEV_DEPENDS | sed 's/ /, /g'`
  else
    PKG_OPK_DEV_DEPENDS=""
  fi

  PKG_OPK="${PKG_NAME}_${PKG_VERSION}-${PKG_REV}_${PKG_OPK_ARCH}.opk"
  PKG_OPK_DEV="${PKG_NAME}_${PKG_VERSION}-${PKG_REV}dev${PKG_OPK_ARCH}_${HOST_ARCH}.opk"
  PKG_DBG_OPK="${PKG_NAME}-dbg_${PKG_VERSION}-${PKG_REV}_${PKG_OPK_ARCH}.opk"
}

# Usage: type=`get_use_type <use_flag>`
get_use_type() {
  local flag=$1

  for arch in i386 x86_64 powerpc powerpc64 arm mips; do
    [ "$flag" = "$arch" ] && echo "ARCH"
  done

  for libc in uclibc eglibc glibc; do
    [ "$flag" = "$libc" ] && echo "LIBC"
  done

  return 0
}

# Usage: pkg_uses <package> <use_flag>
pkg_uses() {
  local pkg="$1"
  local flag="$2"
  local type=`get_use_type $flag`

  if [ -n "$type" ]; then
    [ "`valueof TARGET_$type`" = "$flag" ] && return 0 || return 1
  else
    # strip dashes from the package name, as they are illegal in environment
    # variable names; cf. do_package in scripts/meta2kconfig
    local var="`echo $pkg | sed 's/-//g'`_${flag}"
    local tmp

    eval tmp="\$$var"
    [ "$tmp" = yes ] && return 0 || return 1
  fi
}

# Usage: path=`kernel_path`
kernel_path() {
  ls -d $ROOT/$BUILD/linux-2*
}

# Usage: ver=`kernel_version`
kernel_version() {
  basename $(kernel_path)/.install/lib/modules/*
}

# Usage: require_glibc <package>
require_glibc() {
  if [ "$TARGET_LIBC" = uclibc ]; then
    echo "$1 requires glibc or eglibc, aborting."
    exit 1
  fi
}

# Usage: require_cxx <package>
require_cxx() {
  if [ "$TOOLCHAIN_CXX" != yes ]; then
    echo "$1 requires C++ toolchain support, aborting."
    exit 1
  fi
}

# Usage: do_qmake [options]
do_qmake () {
  $QMAKE -spec $QT_MKSPECS \
    $@ \
    QMAKE_RCC=$TARGET_RCC \
    QMAKE_UIC=$TARGET_UIC \
    QMAKE_MOC=$TARGET_MOC
}

# Usage: do_strip [bin|shlib|staticlib|kmod] <path>
do_strip() {
  local options="--remove-section=.comment --remove-section=.note"
  case "$1" in
    shlib|kmod) options="$options --strip-unneeded"; shift ;;
    staticlib)  options="$options --strip-debug"   ; shift ;;
    bin)        shift ;;
  esac

  if [ -n "$1" ]; then
    for i in $1; do
      file $i 2>&1 | grep -qv ELF && continue
      echo "Stripping $i"
      $STRIP $options $i || true
    done
  fi
}

# Usage: extract_debug_info <debug_path> <unstripped_files...>
extract_debug_info() {
  local debug_path="$1"
  shift

  for f in $*; do
    file_out=`LANG=C file $f 2>&1`
    echo $file_out | grep -qv ELF && continue
    echo $file_out | grep -qv "not stripped" && continue
    echo "Extracting debugging symbols for $f"
    basefile=`echo $f | sed 's/^.*.install//'`
    debug_file="$debug_path/$basefile"
    mkdir -p `dirname $debug_file`
    $TARGET_OBJCOPY --only-keep-debug $f $debug_file || cp -P $f $debug_file
    chmod 0644 $debug_file
    $TARGET_OBJCOPY --add-gnu-debuglink="$debug_file" $f || true
  done
}

# Usage: strip_libs <path> [debug_path]
strip_libs() {
  local tostrip="`find $1 -type f -readable -writable -name "*.so*" | grep -v \".py$\"`"
  local debug_path="$2"

  [ -n "$debug_path" ] && extract_debug_info $debug_path $tostrip
  do_strip shlib "$tostrip"

  return 0
}

# Usage: strip_bins <path> [debug_path]
strip_bins() {
  local tostrip="`find $1 -type f -readable -writable -executable`"
  local debug_path="$2"

  [ -n "$debug_path" ] && extract_debug_info $debug_path $tostrip
  do_strip bin "$tostrip"

  return 0
}

# Usage: strip_kmods <path> [debug_path]
strip_kmods() {
  local tostrip="`find $1 -type f -readable -writable -name *.ko`"
  local debug_path="$2"

  [ -n "$debug_path" ] && extract_debug_info $debug_path $tostrip
  do_strip kmod "$tostrip"

  return 0
}

# Usage: xorg_drv_configure_prepend
xorg_drv_configure_prepend() {
  incdir=${LIB_PREFIX}/include/xorg
  for f in dri.h sarea.h dristruct.h exa.h damage.h xf86Module.h; do
    incfile="$incdir/$f"
    if [ -f "$incfile" ]; then
      p=`echo "$incfile" | sed 'y%*+%pp%;s%[^_[:alnum:]]%_%g'`
      eval "export ac_cv_file_$p=yes"
    fi
  done
}

# Usage: fix_libs <path> [toolchain|sysroot|libprefix]
fix_libs () {
  local target_dir="$1"
  local prefix="$2"
  local prefix_dir

  [ -z "$target_dir" ] && exit 1
  [ -z "$prefix" ] && prefix=libprefix

  case "$prefix" in
    toolchain) prefix_dir="$ROOT/$TOOLCHAIN" ;;
    sysroot)   prefix_dir="$SYSROOT_PREFIX" ;;
    libprefix) prefix_dir="$LIB_PREFIX" ;;
  esac

  if [ -d $target_dir/usr/lib ]; then
    for i in `find $target_dir/usr/lib -name "*.la"`; do
      sed -i "s:\(['= ]\)/usr:\\1$prefix_dir:g" $i
    done
  fi

  if [ -d $target_dir/usr/lib/pkgconfig ]; then
    for i in `find $target_dir/usr/lib/pkgconfig -name "*.pc"`; do
      sed -i "s:\(['= ]\)/usr:\\1$prefix_dir:g" $i
    done
  fi

  return 0
}

# Usage: make_install [toolchain|sysroot|libprefix] [unstripped]
make_install () {
  install_dir="$PWD/.install"
  install_dir_debug="$PWD/.install-debuginfo"
  local prefix="$1"
  local is_strip="$2"

  rm -rf "$install_dir"
  mkdir -p "$install_dir"
  make DESTDIR="$install_dir" INSTALL_ROOT="$install_dir" install_root="$install_dir" INSTALLROOT="$install_dir" DIST_ROOT="$install_dir" install
  chmod -R u+w .install
  fix_libs "$install_dir" $prefix

  [ "$is_strip" = unstripped ] && return 0

  if [ "$prefix" != toolchain ]; then
    strip_libs "$install_dir" "$install_dir_debug/usr/lib/debug"
    kmod_dir="$install_dir/lib/modules/$(kernel_version)"
    if [ -d "$kmod_dir" ]; then
      rm -f $kmod_dir/build $kmod_dir/source $kmod_dir/modules.*
      strip_kmods "$kmod_dir" "$install_dir_debug/usr/lib/debug"
    fi
    for b in bin sbin usr/bin usr/sbin usr/lib/xbmc lib/udev lib/systemd usr/libexec; do
      [ -d "$install_dir/$b" ] && strip_bins "$install_dir/$b" "$install_dir_debug/usr/lib/debug"
    done
  fi

  return 0
}

do_autoconf () {
  setup_toolchain host

  ACLOCAL_INCLUDES=""
  [ -d m4 ] && ACLOCAL_INCLUDES="-I m4"

  $AUTORECONF -i -f \
    -I $ROOT/$TOOLCHAIN/share/aclocal \
    -I $ROOT/$TOOLCHAIN/share/aclocal-1.11 \
    $ACLOCAL_INCLUDES
}

# Usage: do_configure [host|target] [configure_options...]
do_configure () {
  local buildfor=target
  local buildhost=$TARGET_NAME
  local buildconf="--enable-shared --disable-static"
  local configure

  if [ "$1" = target ]; then
    buildfor=target
    buildhost=$TARGET_NAME
    buildconf="--enable-shared --disable-static"
    shift
  elif [ "$1" = host ]; then
    buildfor=host
    buildhost=$HOST_NAME
    buildconf="--enable-static --disable-shared"
    shift
  fi

  if [ -x ./configure ]; then
    configure=./configure
  elif [ -x ../configure ]; then
    configure=../configure
  else
    echo "Cannot find configure script, aborting."
    exit 1
  fi

  setup_toolchain $buildfor

  [ "$GCC_NO_LTO" = 1 ]       && do_gcc_strip_lto
  [ "$GCC_NO_GOLD" = 1 ]      && do_gcc_strip_gold
  [ "$GCC_NO_LOOP_TREE" = 1 ] && do_gcc_strip_loop_tree
  [ "$GCC_NO_GRAPHITE" = 1 ]  && do_gcc_strip_graphite
  [ "$GCC_NO_OFFSET_64" = 1 ] && do_gcc_strip_file_offset

  export CFLAGS="$CFLAGS $local_cflags"
  export CXXFLAGS="$CXXFLAGS $local_cxxflags"
  export CPPFLAGS="$CPPFLAGS $local_cppflags"
  export LDFLAGS="$LDFLAGS $local_ldflags"

  $configure --host=$buildhost \
              --build=$HOST_NAME \
              --prefix=/usr \
              --sysconfdir=/etc \
              --localstatedir=/var \
              $buildconf \
              $@
}

# Usage: do_install <target>
do_install () {
  for file in $*; do
    [ -z "$file" ] && exit 1

    dir=$(dirname $file)
    mkdir -p $INSTALL/$dir
    cp -PR .install/$file $INSTALL/$dir
  done
}

# Usage: do_installdev <target> [toolchain|sysroot|libprefix]
do_installdev () {
  local file="$1"
  local target="$2"
  local target_dir

  [ -z "$target" ] && target=libprefix

  case "$target" in
    toolchain) target_dir="$INSTALL" ;;
    sysroot)   target_dir="$INSTALL/$TARGET_NAME/sysroot" ;;
    libprefix) target_dir="$INSTALL/$TARGET_NAME/sysroot/usr/local" ;;
  esac

  [ -z "$file" ] && exit 1

  dir=`echo $(dirname $file) | sed 's/^usr//'`
  mkdir -p $target_dir/$dir
  cp -PR .install/$file $target_dir/$dir
}

do_perl_make () {
  if [ "$1" = host ]; then
    echo "****** Creating module for host perl ******"
    setup_toolchain host
    export EXPATLIBPATH="${ROOT}/${TOOLCHAIN}/lib"
    export EXPATINCPATH="${ROOT}/${TOOLCHAIN}/include"
    shift
    hostperl Makefile.PL $* \
      EXPATLIBPATH="$EXPATLIBPATH" EXPATINCPATH="$EXPATINCPATH"
  else
    setup_toolchain target
    export PERL_MM_USE_DEFAULT=1
    export PERLCONFIGTARGET="yes"
    export PERL_INC=$LIB_PREFIX/lib/perl5/5.12.3/CORE
    export PERL_LIB=$LIB_PREFIX/lib/perl5/5.12.3
    export PERL_ARCHLIB=$LIB_PREFIX/lib/perl5/5.12.3
    export PERLHOSTLIB=$ROOT/$TOOLCHAIN/lib/
    export PERL5LIB="${PERL_ARCHLIB}"
    export PERL_CMD="$ROOT/$TOOLCHAIN/bin/perl"
    export PERL_SITELIB="usr/lib/perl5/5.12.3"

    install_dir="`pwd`/.install/$PERL_SITELIB/"
    mkdir -p $install_dir
    if [ -e ./Makefile.PL ]; then
      MAKEFILEPL=Makefile.PL
    elif [ -e ./Build.PL ]; then
      MAKEFILEPL=Build.PL
    else
      echo "Cannot find PL script, aborting."
      exit 1
    fi

    $PERL_CMD $MAKEFILEPL $* \
    PERL_LIB=$PERL_LIB \
    PERL_ARCHLIB=$PERL_LIB \
    INSTALLSITELIB=/$PERL_SITELIB \
    INSTALLSITEARCH=/$PERL_SITELIB \
    INSTALLPRIVLIB=/$PERL_SITELIB \
    DESTDIR=$install_dir
    . $LIB_PREFIX/lib/perl/config.sh
    for f in `find -name Makefile.PL`; do
      f2=`echo $f | sed -e 's/.PL//'`
      sed -i -e "s:\(PERL_ARCHLIB = \).*:\1${PERL_ARCHLIB}:" \
              $f2
    done
  fi
}

do_perl_strip () {
  find .install/$PERL_SITELIB -name \*.pod -exec rm -f '{}' \;
  find .install/$PERL_SITELIB -name .packlist -exec rm -f '{}' \;
  find .install/$PERL_SITELIB -name \*.pm -or -name \*.pl | \
    xargs -r sed -i \
      -e '/^=\(head\|pod\|item\|over\|back\)/,/^=cut/d' \
      -e '/^=\(head\|pod\|item\|over\|back\)/,$d' \
      -e '/^#$/d' \
      -e '/^#[^!"'"'"']/d'
}

# Usage: systemctl_enable <unit> [root_dir]
systemctl_enable () {
  local unit_name="$1"
  local unit="/lib/systemd/system/${unit_name}"
  local target_dir="$2"

  [ -z "$target_dir" ] && target_dir=.install
  [ -f "$target_dir/$unit" ] || exit 1

  target=`grep '^WantedBy' $target_dir/$unit | cut -f2 -d=`
  if [ -n "$target" ]; then
    mkdir -p ${target_dir}/lib/systemd/system/${target}.wants
    ln -s $unit ${target_dir}/lib/systemd/system/${target}.wants/
  fi
}

do_python_strip () {
  find .install -name \*.py -exec rm -rf '{}' \;
  find .install -name \*.pyo -exec rm -rf '{}' \;
}

do_remove_werror_calls () {
  for script in Makefile.in; do
    for file in $(find . -name $script); do
      sed -i "s%-Werror%%g" $file
    done
  done
}

do_gcc_strip_lto () {
  # strip out LTO optimization from *FLAGS
  CFLAGS=$(echo $CFLAGS | sed -e "s%-flto=$CONCURRENCY_MAKE_LEVEL%%")
  CXXFLAGS=$(echo $CXXFLAGS | sed -e "s%-flto=$CONCURRENCY_MAKE_LEVEL%%")
  LDFLAGS=$(echo $LDFLAGS | sed -e "s%-flto=$CONCURRENCY_MAKE_LEVEL%%")
}

do_gcc_strip_gold () {
  # strip out GOLD linker usage
  do_gcc_strip_linker_plugin
  TARGET_LD=${TARGET_GNU_LD}
}

do_gcc_strip_linker_plugin () {
  # strip out linker plugin usage
  LDFLAGS=$(echo $LDFLAGS | sed -e "s%-fuse-linker-plugin%%")
}

do_gcc_strip_loop_tree () {
  for f in ftree-loop-distribution \
           floop-interchange floop-strip-mine floop-block; do
    CFLAGS=$(echo $CFLAGS | sed -e "s%-$f%%")
    CXXFLAGS=$(echo $CXXFLAGS | sed -e "s%-$f%%")
  done
}

do_gcc_strip_graphite () {
  CFLAGS=$(echo $CFLAGS | sed -e "s%-fgraphite-identity%%")
  CXXFLAGS=$(echo $CXXFLAGS | sed -e "s%-fgraphite-identity%%")
}

do_gcc_strip_file_offset () {
  CFLAGS=$(echo $CFLAGS | sed -e "s%-D_FILE_OFFSET_BITS=64%%")
  CXXFLAGS=$(echo $CXXFLAGS | sed -e "s%-D_FILE_OFFSET_BITS=64%%")
}

# WAF build-system
do_waf_configure () {
  local buildfor=target
  local buildhost=$TARGET_NAME

  if [ "$1" = target ]; then
    buildfor=target
    buildhost=$TARGET_NAME
    shift
  elif [ "$1" = host ]; then
    buildfor=host
    buildhost=$HOST_NAME
    shift
  fi

  setup_toolchain $buildfor

  [ "$GCC_NO_LTO" = 1 ]       && do_gcc_strip_lto
  [ "$GCC_NO_GOLD" = 1 ]      && do_gcc_strip_gold
  [ "$GCC_NO_LOOP_TREE" = 1 ] && do_gcc_strip_loop_tree
  [ "$GCC_NO_GRAPHITE" = 1 ]  && do_gcc_strip_graphite
  [ "$GCC_NO_OFFSET_64" = 1 ] && do_gcc_strip_file_offset

  export CFLAGS="$CFLAGS $local_cflags"
  export CXXFLAGS="$CXXFLAGS $local_cxxflags"
  export CPPFLAGS="$CPPFLAGS $local_cppflags"
  export LDFLAGS="$LDFLAGS $local_ldflags"

  ./waf configure \
    --prefix=/usr \
    $@
}

do_waf_build () {
  ./waf build -p -j$CONCURRENCY_MAKE_LEVEL
}

# Usage: make_install [toolchain|sysroot|libprefix] [unstripped]
do_waf_install () {
  install_dir="$PWD/.install"
  install_dir_debug="$PWD/.install-debuginfo"
  local prefix="$1"
  local is_strip="$2"

  rm -rf "$install_dir"
  mkdir -p "$install_dir"

  ./waf install --destdir="$install_dir"
  chmod -R u+w .install
  fix_libs "$install_dir" $prefix

  [ "$is_strip" = unstripped ] && return 0

  if [ "$prefix" != toolchain ]; then
    strip_libs "$install_dir" "$install_dir_debug/usr/lib/debug"
    kmod_dir="$install_dir/lib/modules/$(kernel_version)"
    if [ -d "$kmod_dir" ]; then
      rm -f $kmod_dir/build $kmod_dir/source $kmod_dir/modules.*
      strip_kmods "$kmod_dir" "$install_dir_debug/usr/lib/debug"
    fi
    for b in bin sbin usr/bin usr/sbin usr/lib/xbmc lib/udev lib/systemd usr/libexec; do
      [ -d "$install_dir/$b" ] && strip_bins "$install_dir/$b" "$install_dir_debug/usr/lib/debug"
    done
  fi

  return 0
}
