#!/bin/sh -e
# postinst script for ola

conffile="/etc/default/ola"

update_config_file() {
  db_field=$1
  config_field=$2

  RET=false
  db_get $db_field
  if [ -n "$RET" ] ; then
    if grep -q "^$config_field" $conffile ; then
      # keep any admin changes, while replacing the variable content
      sed "s/^[ ]*$config_field=\".*\"/$config_field=\"$RET\"/" < $conffile > $conffile.new && 
      mv $conffile.new $conffile
    else
      echo "$config_field=\"$RET\"" >> $conffile
    fi
  fi
}

# Source debconf library -- we have a Depends line
# to make sure it is there...
. /usr/share/debconf/confmodule
db_version 2.0

case "$1" in
  configure)
  if [ -f $conffile ] ; then
    sed -i -e 's/^[ ]*DAEMON/RUN_DAEMON/g' $conffile
  else
    cat << EOF > $conffile
# Defaults for ola initscript (/etc/init.d/ola)
# This is a POSIX shell fragment

# [automatically edited by postinst, do not change line format ]

# ola daemon switch. If set to true, olad will run.
RUN_DAEMON="true"
EOF
  fi

  update_config_file ola/daemon RUN_DAEMON

  db_stop
  ;;

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

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

#create the olad user, add it to groups
getent passwd olad > /dev/null || adduser --system --no-create-home olad
getent group olad > /dev/null || addgroup --system olad
groups olad | grep dialout > /dev/null || adduser olad dialout
groups olad | grep plugdev > /dev/null || adduser olad plugdev

# setup the config dir
CONF_DIR=/var/lib/ola
if [ ! -d ${CONF_DIR} ]; then
  mkdir -p ${CONF_DIR};
  chown -R olad:olad ${CONF_DIR};
  chmod g+s ${CONF_DIR};
fi;


# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
