#!/bin/bash

# msgUsage: show a usage message and exit
msgUsage() {
  echo "Usage: $(basename $0) <tmp-dir> <pkg-dir> <release-dir> <release-name>"
  echo "Examples:"
  echo " \$ $(basename $0) /tmp/rootfs ports/core-cross . minirootfs-XX"
  echo " \$ $(basename $0) /tmp/rootfs /pub/pkg releases crux-arm-rootfs-XX"
  exit 0
}

# msgError: show a error message and exit
msgError() {
  echo "Error, $@" 2>&1
  exit 1
}

# checkCommands: checks for command dependencies
checkCommands() {
  for cmd in sudo pkgmk tar md5sum; do
    if ! which $cmd 2>&1 >/dev/null; then
      msgError "'$cmd' is not in your \$PATH and you need it to execute this script"
    fi
  done
}

# checkVars: checks for user given arguments
#
# params:
# $1 - TMPDIR
# $2 - PKGDIR
# $3 - RELEASE_DIR
# $4 - RELEASE_NAME
checkVars() {
  [ $# -lt 1 ] && msgUsage
  [ ! -z "$1" ] && TMPDIR="$1"
  [ "$TMPDIR" = "/tmp" ] && msgError "you can't use /tmp as TMPDIR"
  [ ! -z "$2" ] && PKGDIR="$2"
  [ ! -z "$3" ] && RELEASE_DIR="$3"
  [ ! -z "$4" ] && RELEASE_NAME="$4"
  # check for directories, if not create them
  for dir in $TMPDIR $RELEASE_DIR; do
    if [ ! -d "$dir" ]; then
      install -d $dir || msgError "can't create directory $dir"
    fi
  done
  TMPDIR="$(cd $TMPDIR; pwd)"
  PKGDIR="$(cd $PKGDIR; pwd)"
  RELEASE_DIR="$(cd $RELEASE_DIR; pwd)"
  [ -z "$PACKAGES" ] && PACKAGES="$(find $PKGDIR -type f -name '*#*pkg.tar.*')"
}

# global variables
PWD_DIR="$(pwd)"
TMPDIR="$PWD_DIR/tmp"
PKGDIR="$PWD_DIR/pkg"

checkCommands
checkVars $@

echo "+ Initializating pkgutils database..."
sudo install -d -m 0755 $TMPDIR/var/lib/pkg
sudo touch $TMPDIR/var/lib/pkg/db
sudo chmod 0444 $TMPDIR/var/lib/pkg/db

pkgnum=0
echo "+ Installing packages..."
for pkg in $PACKAGES; do
  sudo pkgadd -r $TMPDIR $pkg || msgError "failed to install $pkg"
  let pkgnum=$pkgnum+1
  printf "%-3s - %s\n" $pkgnum $(basename $pkg)
done

echo "+ Creating the tarball. Please be patient..."
cd $TMPDIR && sudo tar cJf $RELEASE_DIR/$RELEASE_NAME.tar.xz * && cd -

echo "+ Creating the md5sum..."
cd $RELEASE_DIR && md5sum $RELEASE_NAME.tar.xz > $RELEASE_NAME.tar.xz.md5 && cd -

echo "+ Finished $RELEASE_DIR/$RELEASE_NAME.tar.xz ($pkgnum packages)"

sudo rm -rf $TMPDIR

# End of file
