#!/bin/bash

set -e
#set -x
#export DEBCONF_DEBUG=developer

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
VIDEOGROUP=video
RENDERGROUP=render

#init for debian
#DEBHELPER#
if [ -f /usr/share/debconf/confmodule ]; then
    . /usr/share/debconf/confmodule
fi
#no dbconfig in preinst
#stop the service if it's running
if [ "@inittype" == "systemd" ]; then
    if [ -f /usr/local/etc/systemd/system/chiton.service ]; then
        deb-systemd-invoke stop chiton.service
    fi
fi


#add our user
if ! getent passwd $BACKEND_USER > /dev/null ; then
    echo "Adding the user $BACKEND_USER"
    useradd $BACKEND_USER -d $STATE_DIR -r -U
fi

#add the webserver to our group
if ! id -Gn $BACKEND_USER | grep -wqE "\b$WEBUSER\b" > /dev/null ; then
    usermod -a -G $BACKEND_USER $WEBUSER
fi

#and the render user
if getent group $RENDERGROUP > /dev/null ; then
    if ! id -Gn $BACKEND_USER | grep -wqE "\b$RENDERGROUP\b" > /dev/null ; then
        usermod -a -G $RENDERGROUP  $BACKEND_USER
    fi
fi

if getent group $VIDEOGROUP > /dev/null ; then
    if ! id -Gn $BACKEND_USER | grep -wqE "\b$VIDEOGROUP\b" > /dev/null ; then
        usermod -a -G $VIDEOGROUP $BACKEND_USER
    fi
fi

rm -f /usr/local/var/lib/chiton/cache/*.php /usr/local/var/lib/chiton/compile/*.php 2>&1 > /dev/null || true

# Apperently this is deprecated
#if [ -f /usr/share/dbconfig-common/dpkg/preinst.mysql ]; then
#    . /usr/share/dbconfig-common/dpkg/preinst.mysql
#    dbc_go chiton "$@"
#fi
