#!/bin/bash

# This script will read in the digiKam configuration file to determine the
# database location. It will then make sure that digiKam is not running and
# call "sqlite3 DATABASE 'VACUUM;" on the database, to clean up and optimize
# the tables.
# This will often lead to great performance gain and a smaller database file
# size.

# general information
username=$(whoami)
programname="digiKam"
processname="digikam"

# config file
rcdir=$(kde4-config --localprefix)share/config
rcfile="digikamrc"
rcpath=$rcdir/$rcfile

# check if config file is readable
if [ ! -e "$rcpath" ]
then
    echo "Error reading $programname's configuration file."
    echo "I searched for $rcpath, but was not able to find it."
    echo "Make sure you started $programname at least once, to generate the "
    echo "appropiate files in your home folder."
    echo "Also make sure that you are currently logged into a KDE session".
    exit 1
fi

# database
databasekey="Database File Path"
databasedir=$(cat $rcpath | grep "$databasekey" | sed -e "s/$databasekey=//")

# make sure digiKam is not running
proc="$(ps aux | grep $username | grep -v $0 | grep -w $processname | grep -v grep)"
if [ "$proc" != "" ]
then
    echo "Please make sure to shutdown $programname first."
    echo "Cleaning up the database while $programname is running might not be as safe as if the application has been shut down."
    exit 1
fi

# backup current working dir
curdir=$(pwd)

# try to enter the database directory
cd $databasedir 2&> /dev/null
if [ $? == 0 ]
then
    echo "Cleaning up $programname databases in $(pwd)"
    for db in $(find . -type f -name 'digikam*.db' -print)
    do
        echo -n "$db ... "
        sqlite3 $db "VACUUM;"
        if [ $? == 0 ]
        then
            echo "done"
        else
            echo "failed!"
            echo "sqlite3 was not able to cleanup the database."
        fi
    done
    echo "Finished";
else
    echo -e "\nI was not able to enter the database folder ($databasedir).\n"
    echo "Make sure that the variable 'Database File Path' in $rcpath "
    echo "is set correctly and that you have permissions to enter this folder."
fi

cd $curdir
