#!/bin/sh

path() {
if [ "$system" = NetBSD ]
  then
    fpc_target="i386-netbsd"
    if [ -z "$PREFIX" ]
      then PREFIX="/usr/pkg"
    fi
elif [ "$system" = Linux ]
  then
    if [ "$(uname -m)" = "armv"* ]
      then fpc_target="arm-linux"
    else
      fpc_target="i386-linux"
    fi
    if [ -z "$PREFIX" ]
      then PREFIX="/usr"
    fi
fi
}

hash_file() {
  if test "$system" = NetBSD
    then
      cksum -a md5 "$1" | cut -f 4 -d " "
      return
  fi
  md5sum "$1" | cut -f 1 -d " "
}

file_state() {
  meta_file=.redo/`echo "$1" | tr "/" "+"`

  if test "$system" = NetBSD
    then timestamp=`stat -f %m "$1"`
  else
    timestamp=`stat -c %Y "$1"`
  fi

  if test -f $meta_file
    then
      old_timestamp=`head -n 1 $meta_file`

      if test $timestamp -eq $old_timestamp
        then return 0
      fi
      old_hash=`tail -n 1 $meta_file`

      hash=`hash_file "$1"`
      if test $hash = $old_hash
        then return 0
      fi
  else
    hash=`hash_file "$1"`
  fi
  printf "%s\n%s\n" $timestamp $hash > $meta_file
  return 1
}

system=`uname -s`

build() {
  path
  CFLAGS="-nostdinc -I $PREFIX/include/libfndn -I ../include -fno-builtin -fno-stack-protector -fno-pie -std=c89 -Wall -Wno-main -Wpedantic $CFLAGS"

  mkdir -p .redo
  for source in ball line rectangle inform
  do
    if ! file_state ${source}.c
      then
        "${CC:-cc}" $CFLAGS -c -o ${source}.o ${source}.c
        "${LD:-ld}" -e start -o $source ${source}.o ../libgraph.a $PREFIX/lib/start.o $PREFIX/lib/libfndn.a
    fi
  done
}

clean() {
  rm -fr ball inform line rectangle *.o .redo
}

if test -z $1
  then
    build
    exit $?
fi
"$@"
