#! /bin/sh
# postinst maintainer script for zoneminder-db package

set -e

# Source the debconf stuff
. /usr/share/debconf/confmodule

mysql_update() {

    # Source the dbconfig stuff
    . /usr/share/dbconfig-common/internal/mysql

    # Update the password of the hard-coded default 'admin' account
    test -z $ADMIN_PASSWORD || dbc_mysql_exec_command "UPDATE Users SET Password = password('$ADMIN_PASSWORD') WHERE Username = 'admin';" || true

    # Update the database version
    dbc_mysql_exec_command "UPDATE Config SET Value = '$DB_VERSION' WHERE Name = 'ZM_DYN_DB_VERSION';" || true
}

if [ -f /usr/share/dbconfig-common/dpkg/postinst ]; then

    # Set the first version in which dbconfig-common was introduced in the package
    dbc_first_version="1.28.0"

    # Set the database type
    dbc_dbtypes="mysql"

    # Source the dbconfig-common stuff
    . /usr/share/dbconfig-common/dpkg/postinst
fi

# Do this when the package is installed, upgraded or reconfigured
if [ "$1" = "configure" ] || [ "$1" = "reconfigure" ]; then

    # Install sql database create file for dbconfig
    # (needed at first package installation)
    if [ ! -f /usr/share/dbconfig-common/data/zoneminder/install/mysql ]; then
        install -m 644 /usr/share/zoneminder/db/zm_create.sql \
          /usr/share/dbconfig-common/data/zoneminder/install/mysql
        # Remove unneeded sql requests
        # dbconfig will create the underlying database
        sed -i "/^ *CREATE DATABASE /d" \
          /usr/share/dbconfig-common/data/zoneminder/install/mysql
        sed -i "/^ *USE /d" \
          /usr/share/dbconfig-common/data/zoneminder/install/mysql
    fi

    # Symlink sql update files for dbconfig (needed when upgrading the package)
    for sqlfile in /usr/share/zoneminder/db/zm_update-*.sql; do
        lnk=`echo $sqlfile | sed "s/^\/usr\/share\/zoneminder\/db\/zm_update-\(.*\)\.sql/\1/"`
        if [ ! -L /usr/share/dbconfig-common/data/zoneminder/upgrade/mysql/$lnk ]; then
            ln -sf $sqlfile \
              /usr/share/dbconfig-common/data/zoneminder/upgrade/mysql/$lnk
        fi
    done || true

    # Create the underlying database and populate it
    # dbconfig will take care of applying any updates which are newer than the
    # previously installed version
    dbc_go zoneminder $@

    # Get the password of ZoneMinder user 'admin' from debconf
    db_get zoneminder/admin_password
    ADMIN_PASSWORD=$RET

    # Remove the password from debconf database
    test -z $ADMIN_PASSWORD || db_reset zoneminder/admin_password || true

    # Get the lastest database version from dbconfig upgrade folder
    DB_VERSION=$(ls -rv /usr/share/dbconfig-common/data/zoneminder/upgrade/$dbc_dbtypes | head -1)

    # Update the default admin account and database version
    mysql_update
fi

#DEBHELPER#

exit 0
