#!/bin/bash
#
# rpmdb helper script for
# converting and/or rebuilding rpm database 
# chkconfig: 23456 85 15
# description: convert/rebuild rpm database

### BEGIN INIT INFO
# Provides: rpmdb-rc
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO
# Source function library.
. /etc/rc.d/init.d/functions
# See how we were called.
#Supported types are ndb or sqlite
rpm_db_type=ndb
macro_file=/usr/lib/rpm/macros

case "$1" in
  start)
        gprintf "Rebuild rpm database: "
        if [ -f /var/lock/subsys/rpmdb-rc ] ; then
                echo
                gprintf "This script is intended to run only at boot time..."
                echo
                exit 1
        fi
        sed -i "$(awk '/_db_backend/{print NR}' $macro_file) c \%_db_backend  $rpm_db_type"  $macro_file
        /usr/bin/rpmdb --rebuilddb
        echo
        touch /var/lock/subsys/rpmdb-rc
        ;;
  stop)
        gprintf "Prepare to rebuild/convert RPM databse: "
        ps -ef | grep synaptic | grep -v grep | grep -v rc.d | awk '{print $2}' | uniq | xargs kill 1> /dev/null 2>&1
        ps -ef | grep apt-get | grep -v grep | grep -v rc.d | awk '{print $2}' | uniq | xargs kill 1> /dev/null 2>&1
        ps -ef | grep dnf5 | grep -v grep | grep -v rc.d | awk '{print $2}' | uniq | xargs kill 1> /dev/null 2>&1
        rm -f /var/lock/subsys/rpmdb-rc
        echo
        ;;
  restart)
        $0 stop
        $0 start
        ;;
  *)
        gprintf "Usage: %s {start|stop|restart}\n" "$0"
        exit 1
esac

exit 0
