#!/bin/bash

toplevel=`pwd`
version="2.4.1"

usage() {
  echo "makeworld version $version"
  echo "usage: $0 [options] <destdir> <category> [category] ..."
  echo "options:"
  echo "  -c, --clean      Clean up work files after build"
  echo "  -s, --syncdeps   Install missing dependencies with pacman"
  echo "  -b, --builddeps  Build missing dependencies from source"
  echo "  -d, --nodeps     Skip all dependency checks"
  echo "  -i, --install    Install package after successful build"
  echo "  -f, --force      Overwrite existing packages"
  echo "  -h, --help       This help"
  echo
  echo "  where <category> is one or more directory names under the ABS root"
  echo "  eg: makeworld -c /packages base lib editors"
  echo
  echo "  this should be run from the toplevel directory of ABS (usually /usr/abs)"
}

if [ $# -lt 2 -o "$1" = "--help" -o "$1" = "-h" ]; then
  usage
  exit 1
fi

MAKEPKG_OPTS=
for arg in $*; do
  case $arg in
    --clean)     MAKEPKG_OPTS="$MAKEPKG_OPTS -c" ;;
    --install)   MAKEPKG_OPTS="$MAKEPKG_OPTS -i" ;;
    --syncdeps)  MAKEPKG_OPTS="$MAKEPKG_OPTS -s" ;;
    --builddeps) MAKEPKG_OPTS="$MAKEPKG_OPTS -b" ;;
    --nodeps)    MAKEPKG_OPTS="$MAKEPKG_OPTS -d" ;;
    --force)     MAKEPKG_OPTS="$MAKEPKG_OPTS -f" ;;
    --*)
      usage
      exit 1
      ;;
    -*)
      while getopts "cisbdf-" opt; do
        case $opt in
        c) MAKEPKGS_OPTS="$MAKEPKGS_OPTS -c" ;;
        i) MAKEPKGS_OPTS="$MAKEPKGS_OPTS -i" ;;
        s) MAKEPKGS_OPTS="$MAKEPKGS_OPTS -s" ;;
        b) MAKEPKGS_OPTS="$MAKEPKGS_OPTS -b" ;;
        d) MAKEPKGS_OPTS="$MAKEPKGS_OPTS -d" ;;
        f) MAKEPKGS_OPTS="$MAKEPKGS_OPTS -f" ;;
        -)
          OPTIND=0
          break
          ;;
        esac
      done
      ;;
    *)
      dest=$arg
      shift
      break
      ;;
  esac
  shift
  if [ "$dest" != "" ]; then
    break;
  fi
done

if [ "$dest" = "" ]; then
  usage
  exit 1
fi

sd=`date +"[%b %d %H:%M]"`

for category in $*; do
  for port in `find $toplevel/$category -type d -maxdepth 1 -mindepth 1 | sort`; do
    cd $port
    if [ -f PKGBUILD ]; then
      . PKGBUILD
      buildstatus=0
      if [ ! -f $dest/$pkgname-$pkgver-$pkgrel.pkg.tar.gz ]; then
        makepkg $MAKEPKG_OPTS -w $dest 2>>$toplevel/makepkg.log
        if [ $? -gt 0 ]; then
          buildstatus=2
        else
          buildstatus=1
        fi
      fi
      d=`date +"[%b %d %H:%M]"`
      echo -n "$d  " >>$toplevel/build.log
      case $buildstatus in
        0) echo "$pkgname already built -- skipping" >>$toplevel/build.log ;;
        1) echo "$pkgname was built successfully" >>$toplevel/build.log ;;
        2) echo "$pkgname build failed" >>$toplevel/build.log ;;
      esac
    fi
  done
done
ed=`date +"[%b %d %H:%M]"`

echo "makeworld complete." >>$toplevel/build.log
echo "  started:  $sd" >>$toplevel/build.log
echo "  finished: $ed" >>$toplevel/build.log

