#! /bin/sh

set -e

# Load debconf
. /usr/share/debconf/confmodule


is_initial_configuration() {
    # Plain installation
    if [ "$1" = configure ] && [ -z "$2" ]; then
        return 0
    fi
    # Configuration via dpkg-reconfigure
    if [ "$1" = reconfigure ] || [ "$DEBCONF_RECONFIGURE" ]; then
        return 0
    fi
    return 1
}


validate_initial_config() {
  local invalid
  invalid=""
 
  # Make sure the passwords match
  local pass1 pass2
  db_get qpidd/password1
  pass1="$RET"
  db_get qpidd/password2
  pass2="$RET"
  
  if [ "$pass1" != "$pass2" ]; then
    db_fset qpidd/password1 seen false
    db_fset qpidd/password2 seen false
    invalid=true

    db_input high qpidd/password_mismatch
  fi

  if [ "$invalid" ]; then 
    return 1
  else
    return 0
  fi
}


query_initial_config() {
  while true; do
    db_input high qpidd/password1 || true
    db_input high qpidd/password2 || true
    db_go || true

    if validate_initial_config; then
      break
    fi
  done
}

# Create an initial directory on fresh install
if is_initial_configuration "$@"; then
	query_initial_config
fi

db_go || true

exit 0
