#!/bin/bash

set -e
#set -x
#dbc_debug=1

export PATH="/sbin:/usr/sbin:$PATH"

#init for debian
#DEBHELPER#
if [ -f /usr/share/debconf/confmodule ]; then
    . /usr/share/debconf/confmodule
fi


STATE_DIR=/usr/local/var/lib/chiton
RUN_DIR=/usr/local/var/run/chiton
WEBUSER=apache
VID_DIR=$STATE_DIR/vids
BACKEND_USER=chiton
HTML_SRC_DIR=/usr/local/share/chiton/web
APACHE_CFG_DIR=/usr/local/etc/apache2/sites-available/
CFGDIR=/usr/local/etc/chiton
WEBDIR=/chiton

if [ -f /usr/share/dbconfig-common/dpkg/postinst.mysql ]; then
    . /usr/share/dbconfig-common/dpkg/postinst.mysql
    dbc_go chiton "$@" || true
    MYSQL_HOST="$dbc_dbserver"
    MYSQL_DB="$dbc_dbname"
    MYSQL_USER="$dbc_dbuser"
    MYSQL_USER_PW="$dbc_dbpass"

    if [ ! -f $CFGDIR/chiton.cfg ]; then
        chiton-install -yqk -H "$MYSQL_HOST" -d "$MYSQL_DB" -u "$MYSQL_USER" -p "$MYSQL_USER_PW"
    fi

fi

#setup the directories
if [ ! -d $STATE_DIR/compile ]; then
    mkdir -p $STATE_DIR/compile
fi

if [ ! -d $STATE_DIR/cache ]; then
    mkdir -p $STATE_DIR/cache
fi

if [ ! -d $VID_DIR ]; then
    mkdir -p $VID_DIR
fi

chown $BACKEND_USER:$BACKEND_USER  $STATE_DIR $VID_DIR $STATE_DIR/compile $STATE_DIR/cache
chmod 770 $STATE_DIR/compile $STATE_DIR/cache $VID_DIR


#restart everything...on debian
if [ "systemd" == "systemd" ]; then
    systemctl daemon-reload || true
    deb-systemd-helper enable chiton.service || true
    deb-systemd-invoke start chiton.service || true
    deb-systemd-invoke restart apache2.service || true
elif [[ "$PRE_INSTALL_PASS" != "true" ]]; then #slackware runs the script twice, first with PRE_INSTALL_PASS set to true
    #we always overwrite it, but keep the execute bit
    if [ -e /usr/local/etc/systemd/system/chiton.service ] && [ -r /usr/local/etc/systemd/system/chiton.service.new ]; then
        mv /usr/local/etc/systemd/system/chiton.service.new /usr/local/etc/systemd/system/chiton.service
        chmod +x /usr/local/etc/systemd/system/chiton.service
    else
        mv /usr/local/etc/systemd/system/chiton.service.new /usr/local/etc/systemd/system/chiton.service
    fi
fi
