#!/bin/sh -x

if [ "/root" != "$HOME" ];then
  echo "You need to build as root!"
  exit 1
fi

#SRCDIR=wvc54g_v1025
SRCDIR=wvc54g-EU
TOOLS=dl/$SRCDIR/toolchain.tgz
SRCTAR=dl/$SRCDIR/$SRCDIR.src.tgz

test -d /opt || mkdir -p /opt
test -L /opt/Cadenux || ln -sf /usr/src/cross/wvc/opt/Cadenux/ /opt/Cadenux
test -d opt/ || tar xvzf $TOOLS
test -d $SRCDIR/ || tar xzf $SRCTAR
test -f $SRCDIR/SOURCE/Makefile.orig || {
  patch -b -d $SRCDIR -p1 < 001-compilefix-kubuntu-$SRCDIR.patch || exit
  patch  -d $SRCDIR -p1 < 002-wvc-add-olsrd-$SRCDIR.patch || exit
  cp -av freifunk-addons.$SRCDIR/* $SRCDIR/
}
if [ ! -f $SRCDIR/SOURCE/linux/.depend ]; then
  cd $SRCDIR/SOURCE
  . ./setenv EN
  cd -
  cd $SRCDIR/SOURCE/linux
  make oldconfig
  make dep
  cd -
fi
if [ ! -d $SRCDIR/SOURCE/fs/apps/olsrd-90e58c149597 ];then
  tar -C $SRCDIR/SOURCE/fs/apps -xvzf dl/90e58c149597.tar.gz
  cd $SRCDIR/SOURCE/fs/apps
  patch -p1 -d olsrd-90e58c149597 < 101-olsrd-assert-struct-sizes-for-arm.patch
  patch -p1 -d olsrd-90e58c149597 < 103-olsrd-moodfix.patch
  patch -p1 -d olsrd-90e58c149597 < 109-olsrd-winversion.patch
  patch -p1 -d olsrd-90e58c149597 < 137-olsrd-192.168.1.1.patch
  patch -p1 -d olsrd-90e58c149597 < 139-olsrd-magicarprefresh.patch
  patch -p1 -d olsrd-90e58c149597 < 140-olsrd-optimize-size.patch
  patch -p1 -d olsrd-90e58c149597 < 900-olsrd-cadenux.patch
  patch -p1 -d olsrd-90e58c149597 < 910-olsrd-static-nameservice-copy.patch
  patch -p1 -d olsrd-90e58c149597 < 920-olsrd-static-nameservice.patch
  patch -p1 -d olsrd-90e58c149597 < 930-olsrd-olsrprintf-for-old-compilers.patch
  cd -
fi
if [ ! -f $SRCDIR/SOURCE/FW/WVC54G.bin ];then
  cd $SRCDIR/SOURCE
  . ./setenv EN
  make
  cd -
fi

FTPDIR=/srv/ftp/upload/wvc
if [ -d $FTPDIR/ ]; then
  # This is my upload directory
  cp -avu *.patch *.sh *.txt flashwvc freifunk-addon* $SRCDIR/SOURCE/FW/WVC54G.bin $FTPDIR/
  (cd $FTPDIR;md5sum $(find -maxdepth 1 -type f -not -name md5sum.asc)>md5sum.asc)
fi

#echo "To repeat, cd into $SRCDIR/SOURCE and call '. ./setenv' and 'make'."
