#!/bin/sh
# Filename:      db-to-fai
# Purpose:       convert output of grml-live's sqlite database for use within FAI
# Authors:       grml-team (grml.org)
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2 or any later version.
################################################################################

if [ -z "$2" ] ; then
  echo "Usage: $0 /path/to/grml-live.db <build-id>"
  exit 1
fi

DB="$1"
BUILD_ID="$2"

if ! [ -r "$DB" ] ; then
  echo "Error: can not access database ${DB}.">&2
  bailout 1
fi

TMPFILE=$(mktemp)

bailout() {
  rm -f "$TMPFILE"
  [ -n "$1" ] && exit "$1" || exit 0
}

# get information from db:
if ! echo "select package,version FROM packages, build WHERE build.id = $BUILD_ID AND packages.build = build.id and status = 'ii';" | sqlite3 $DB > $TMPFILE ; then
   echo "Error retrieving values from database ${DB}." >&2
   bailout 1
else
   # make sure we god some matches:
   if ! grep -q '^[a-zA-Z]*' "$TMPFILE" ; then
      echo "No packages retrieved from build id $BUILD_ID - wrong id?" >&2
      bailout 1
   fi

   # write fai header and package information to stdout:
   echo "# package list of build $BUILD_ID from database $DB:"
   echo "PACKAGES install"
   awk -F\| '{print $1"="$2}' "$TMPFILE"
fi

# clean exit:
bailout

## END OF FILE #################################################################
