#!/bin/bash

PATH=`dirname $_`:$PATH

if [ -f ~/.config/darktable/darktablerc ]
then
  # get dbfile from darktablerc
  dbfile=$(cat ~/.config/darktable/darktablerc | grep -E "^database=" | cut -f2 -d'=')
else
  # get dbfile from gconf
  dbfile=$(gconftool-2 --get /apps/darktable/database)
fi
# if it doesn't contain an absolute path, prepend the std dir
echo $dbfile | grep '^/' > /dev/null || dbfile=~/.config/darktable/$dbfile
# if commandline switch is given, override:
echo $* | grep '\-\-library' >/dev/null && dbfile=$(echo $* | sed -e 's/^.*--library //' -e 's/ .*//')

if [ -w /dev/shm ]
then
  echo "[$0] copying $dbfile to ram disk"
  rm -f /dev/shm/darktable-faster.db
  cp -f $dbfile /dev/shm/darktable-faster.db
  # last argument overrides previous --library statement:
  darktable $@ --library /dev/shm/darktable-faster.db
  # terminated for whatever reason, db will be consistent (hopefully)
  echo "[$0] copying back to $dbfile"
  cp /dev/shm/darktable-faster.db $dbfile
else
  echo "[$0] ERROR: /dev/shm has to be writable!"
  echo "[$0] calling darktable regularly."
  darktable $@
fi
