#!/bin/bash

set -e

POSTGRESQL_DATA_DIR=/var/lib/postgresql/xivouc/11

DAYS_OF_HISTORY=7

list_packages_with_filter() {
    filter="$1"
    aptitude -q -F '%p' --disable-columns search "$filter"
}

migrate_pgxivocc_94_to_11() {
    update_replication_state_sql="""
        UPDATE replication_state
        SET val=(
            SELECT COALESCE (
                (SELECT id FROM cel
                    WHERE eventtime < (SELECT now() - interval '$DAYS_OF_HISTORY days')
                    ORDER BY id DESC
                    LIMIT 1
                ),
                0
            )
        )
        WHERE name='cel';
        """

    echo "Migrating xivouc database"

    xivocc-dcomp stop pgxivocc
    # remove container and anonymous volume with db data
    xivocc-dcomp rm -f pgxivocc

    mkdir -p $POSTGRESQL_DATA_DIR
    chmod 700 $POSTGRESQL_DATA_DIR

    # move replication state back to have call history
    psql -U postgres asterisk -c "$update_replication_state_sql"
}

is_xivouc_installed=$(list_packages_with_filter '?installed?name("^xivouc$")' > /dev/null; echo $?)

if dpkg --compare-versions "$XIVO_VERSION_INSTALLED" "<<" "2020.13.00" \
    && [ $is_xivouc_installed -eq 0 ]; then

    migrate_pgxivocc_94_to_11
fi
