#!/bin/sh

set -e

NAME=wcs
DAEMON=/usr/bin/wcsctl
USER=$NAME
GROUP=$NAME
CONFIG_DIR=/etc/wcs
CONFIG_FILE=/etc/wcs/wcs.cfg
MANAGE_SCRIPT="/usr/bin/$NAME-manage"

# Read config file if it is present.
if [ -r /etc/default/$NAME ]
then
  . /etc/default/$NAME
fi

if [ $CONFIG_FILE ]; then
    COMMAND="$DAEMON -f $CONFIG_FILE"
else
    COMMAND="$DAEMON"
fi

case "$1" in
  configure)

    # make sure the administrative user exists
    if ! getent passwd $USER >/dev/null; then
      adduser --disabled-password  --quiet --system \
        --no-create-home --home /var/lib/$NAME \
        --gecos "$NAME user" --group $USER
    fi
    # ensure dirs ownership
    chown $USER:$GROUP /var/log/$NAME
    chown $USER:$GROUP /var/lib/$NAME
    chown $USER:$GROUP /var/lib/$NAME/collectstatic

    # create a secret file
    SECRET_FILE=$CONFIG_DIR/secret
    if [ ! -f $SECRET_FILE ]; then
        echo -n "Generating Django secret..." >&2
        cat /dev/urandom | tr -dc [:alnum:]-_\!\%\^:\; | head -c70 > $SECRET_FILE
        chown root:$GROUP $SECRET_FILE
        chmod 0440 $SECRET_FILE
    fi

  ;;

  triggered)
    su -s /bin/sh -c "$COMMAND hobo_deploy --redeploy" $USER
    su -s /bin/sh -c "$MANAGE_SCRIPT collectstatic" $USER
    exit 0
  ;;

  abort-upgrade|abort-remove|abort-deconfigure)
  ;;

  *)
    echo "postinst called with unknown argument \`$1'" >&2
    exit 1
  ;;
esac

#DEBHELPER#

exit 0
