#!/bin/bash

set -e
#set -x
#dbc_debug=1
#init for debian
#DEBHELPER#

if [ -f /usr/share/debconf/confmodule ]; then
    . /usr/share/debconf/confmodule
    if [[ "$1" == "purge" || "$1" == "db_purge" ]]; then
        db_purge || true
    fi
fi

if [ -f /usr/share/dbconfig-common/dpkg/postrm.mysql ]; then
    . /usr/share/dbconfig-common/dpkg/postrm.mysql
    dbc_go chiton "$@" || true
fi

rm -rf /usr/local/var/lib/chiton/cache/* 2>&1 > /dev/null || true
rm -rf /usr/local/var/lib/chiton/compile/* 2>&1 > /dev/null || true
rmdir /usr/local/var/lib/chiton/cache/ 2>&1 > /dev/null || true
rmdir /usr/local/var/lib/chiton/compile/ || true

if [[ "$1" == "purge" || "$1" == "db_purge" ]]; then
    # We are deleting all our files
    rm -f /usr/local/var/run/chiton/chiton.pid 2>&1 > /dev/null || true
    rm -f /usr/local/var/run/chiton/chiton.sock 2>&1 > /dev/null || true
    rmdir /usr/local/var/run/chiton 2>&1 > /dev/null || true
    rmdir /usr/local/var/lib/chiton/cache/ 2>&1 > /dev/null || true
    rmdir /usr/local/var/lib/chiton/compile/ 2>&1 > /dev/null || true
    rm -rf /usr/local/var/lib/chiton/vids/ || true
    rmdir /usr/local/var/lib/chiton || true

    if [ "no" != "no" ]; then
        rm -f no/apache-chiton.conf || true
    fi

    #I don't think this can ever happen on debian, but it's here for completness
    if [ "xapache" != "xno" ]; then
        #append an include line to apache
        if [ -f "apache" ] && [ ! grep "$APACHE_CFG_DIR/apache-chiton.conf" "apache" ]; then
            sed -i -e 's,# Enable Chiton NVR,,' \
                -e "s,Include $APACHE_CFG_DIR/apache-chiton.conf,,"  apache
        fi
    fi

    rm -f /usr/local/etc/apache2/sites-available//apache-chiton.conf || true
    rm -f /usr/local/etc/chiton/chiton.cfg /usr/local/etc/chiton/config.php || true
    rm -f /usr/local/etc/chiton/chiton.cfg.orig /usr/local/etc/chiton/config.php.orig || true
    rmdir /usr/local/etc/chiton || true
fi

if [ -d /usr/local/var/lib/chiton/ ]; then
    rmdir /usr/local/var/lib/chiton/ &> /dev/null || true
fi

if [ -r /usr/local/var/run/chiton/chiton.sock ]; then
    if ! fuser /usr/local/var/run/chiton/chiton.sock  &> /dev/null ; then
        rm -f /usr/local/var/run/chiton/chiton.sock
    fi
fi
rmdir /usr/local/var/run/chiton &> /dev/null || true

#we install it as a .new so we need to delete the main file too
if [[ "systemd" = "sysv" ]]; then
    if ! [ -r /usr/local/etc/systemd/system/chiton.service.new ]; then #if the .new still exists, it's because this is an upgrade
        rm -f /usr/local/etc/systemd/system/chiton.service || true
    fi
fi
