#!/bin/sh

. config/options

PKG_DIR=`find $PACKAGES -type d -name $1`

if [ -z "$1" ]; then
  echo "usage: $0 package_name"
  exit 1
fi

$SCRIPTS/get $1

mkdir -p $BUILD

[ ! -d $SOURCES/$1 -a ! -d $PKG_DIR/sources ] && exit 0

mkdir -p $STAMPS/$1
STAMP=$STAMPS/$1/unpack

[ -f $STAMP -a -f $PKG_DIR/need_unpack ] && $PKG_DIR/need_unpack $@
for patch in $PKG_DIR/patches/*; do
  if [ $patch -nt $STAMP ]; then
    rm -f $STAMP
    break
  fi
done
[ -f $STAMP ] && exit 0

printf "%${INDENT}c UNPACK   $1\n" >&$SILENT_OUT
export INDENT=$((${INDENT:-1}+$INDENT_SIZE))

rm -rf $BUILD/$1[-_][0-9]*
rm -rf $BUILD/$1[-_]r[0-9]*
rm -rf $BUILD/$1[-_]cvs*
rm -rf $BUILD/$1[-_]svn*
rm -rf $BUILD/$1[-_]git*

if [ -f $PKG_DIR/url ]; then
  $SCRIPTS/extract $1 "$1*.tar.bz2" $BUILD
  $SCRIPTS/extract $1 "$1*.tar.gz"  $BUILD
  $SCRIPTS/extract $1 "$1*.tgz"     $BUILD
fi

if [ -d $PKG_DIR/sources ]; then
  [ ! -d $BUILD/$1* ] && mkdir -p $BUILD/$1
  cp -PRf $PKG_DIR/sources/* $BUILD/$1*/
fi

for i in $PKG_DIR/patches/*.diff*; do
  if [ -f $i ]; then
    PATCH=`basename $i`
    PT=`echo $PATCH | sed 's/.*\.\(.*\)$/\1/'`
    if [ "$PT" != diff -a "$PT" != "$TARGET_ARCH" -a "$PT" != "$TARGET_PLATFORM" ]; then
      echo "## Skipping patch: $i"
      continue;
    else
      echo "## Applying patch: $i"
      cat $i | patch -d `echo $BUILD/$1* | cut -f1 -d\ ` -p1 >&$VERBOSE_OUT
    fi
  fi
done

$SCRIPTS/fixconfigtools $BUILD/$1*

[ -f $PKG_DIR/unpack ] && $PKG_DIR/unpack $@ >&$VERBOSE_OUT

rm -f $STAMPS/$1/build
. $PROJECT_DIR/$PROJECT/options
for i in `sed -n "s/^\([^#].*\)=\".*$/\1/p" $PROJECT_DIR/$PROJECT/options | grep -v "#"`; do
  eval val=\$$i
  echo "STAMP_$i=\"$val"\" >> $STAMP
done
