#!/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
configgroup="Album Settings"
databasekey="Database File Path"
configfile="digikamrc"
databasedir=$(kreadconfig --file $configfile --group "$configgroup" --key "$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 shutdown $programname first."
    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
