#!/bin/sh -e

HTS_USER=hts

. /usr/share/debconf/confmodule
db_version 2.0

case "$1" in
configure)

   if ! getent passwd $HTS_USER >/dev/null; then
        echo >&2 "Creating user: $HTS_USER..."
        adduser --quiet --system --group --shell /bin/bash $HTS_USER
   fi

   HTS_HOME=`getent passwd $HTS_USER | cut -d':' -f6`

   mkdir -p "${HTS_HOME}/.hts/tvheadend"
   chown ${HTS_USER}:${HTS_USER} "${HTS_HOME}/.hts"
   chown ${HTS_USER}:${HTS_USER} "${HTS_HOME}/.hts/tvheadend"

   HTS_SUPERUSERCONF="${HTS_HOME}/.hts/tvheadend/superuser"
   rm -f "${HTS_SUPERUSERCONF}"
   touch "${HTS_SUPERUSERCONF}"
   chmod 600 "${HTS_SUPERUSERCONF}"
   chown ${HTS_USER}:${HTS_USER} "${HTS_SUPERUSERCONF}"

   echo >>"${HTS_SUPERUSERCONF}" "{"

   if db_get tvheadend/admin_username; then
       echo >>"${HTS_SUPERUSERCONF}" '"username": "'$RET'",'
   fi

   if db_get tvheadend/admin_password; then
       echo >>"${HTS_SUPERUSERCONF}" '"password": "'$RET'"'
   fi
    
   echo >>"${HTS_SUPERUSERCONF}" "}"
   ;;
esac

db_stop

#DEBHELPER#

exit 0
