#!/bin/sh
run() {
  echo "$*"
  "$@"
}

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
}

all() {
  system=`uname -s`
  run mkdir -p out .redo
  run cp -fr static/* out/
  for source in templates/*.gpp templates/*/*.gpp templates/*/*/*.gpp
  do
    if ! file_state $source
      then
        out=`echo $source | cut -f -2 -d "." | sed -e "s/templates/out/"`
        echo "env INCLUDE_PATH=./include ./gpp.awk $source > $out"
        env INCLUDE_PATH=./include ./gpp.awk $source > $out
    fi
  done
  echo "find . | cpio -H newc -o > /tmp/website.cpio"
  find . | cpio -H newc -o > /tmp/website.cpio
  run mv -f /tmp/website.cpio out/
}

clean() {
  run rm -fr out .redo
}

dist() {
  test -d out || all

  which rsync > /dev/null
  if test $? -ne 0
    then
      echo Error: remote sync is unavailable >&2
      exit 1
  fi
  printf "Password for stone.home: "
  read RSYNC_PASSWORD
  export RSYNC_PASSWORD
  run rsync -a --delete out/ rsync://stone.home/website/
}

if test $# -gt 0
  then
    if ! `type $1 | grep -q function\$`
      then
        echo Error: unknown verb: $1 >&2
        exit 1
    fi
    eval $@
else
  all
fi
