#!/bin/bash

# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

closeDatabase() {
	# Run VACUUM to reclaim space and defragment the database before closing
	echo 'vacuum;' >&3
	# Tell sqlite3 to exit cleanly
	echo .quit >&3
	(( debug )) && echo -n "Waiting for SQLite to terminate... "
	# Close the debug tee fd if it was opened (debug level > 2)
	(( debug > 2 )) && exec 5>&-
	# Wait for the sqlite3 background process to fully exit
	wait $db_pid
	(( debug )) && echo OK
	# Close the write end of the SQLite input FIFO (FD 3)
	exec 3>&-
	# Close the read end of the SQLite output FIFO (FD 4)
	exec 4<&-
}
