#!/bin/sh

set -e

# Source debconf library.
. /usr/share/debconf/confmodule


# Choose to configure Apache webserver
db_input high hoteldruid/configure-apache || true
db_go || true

RESTRICT_LOCAL=0
# Choose to restart Apache webserver
db_get hoteldruid/configure-apache
if [ "$RET" = "true" ]; then
  db_input high hoteldruid/restrict-localhost || true
  db_input medium hoteldruid/restart-webserver || true
  db_go || true
  db_get hoteldruid/restrict-localhost
  if [ "$RET" = "true" ]; then
    RESTRICT_LOCAL=1
  fi
fi

# Ask username and password for HotelDruid administrator
if [ -e "/var/lib/hoteldruid/data/dati_connessione.php" ]; then
  db_set hoteldruid/administrator-username ""
else
  db_input high hoteldruid/administrator-username || true
  db_go || true
  db_get hoteldruid/administrator-username
  if [ -n "$RET" ]; then
    CHECK=$(echo $RET | grep "[^A-Za-z0-9]") || true
    if [ -n "$CHECK" ]; then
      db_set hoteldruid/administrator-username ""
    else
      PASS_MATCH=''
      while [ ! "$PASS_MATCH" ]; do
        set +e
        db_input high hoteldruid/administrator-password
        EXIT_CODE=$?
        set -e
        if [ $EXIT_CODE -ne 0 ]; then
          # Don't unset username in case the script is called twice during configuration
          #db_set hoteldruid/administrator-username ""
          PASS_MATCH=1
        else
          db_go || true
          db_get hoteldruid/administrator-password
          # Don't activate login with non-interactive installation
          if [ $RESTRICT_LOCAL -eq 1 ] && [ -z "$RET" ]; then
            PASS_LENGTH=4
          else
            # Password with only a sequence of numbers
            PASS_LENGTH=$(echo -n $RET | wc -c) || true
            CHECK=$(echo "01234567890" | grep "$RET") || true
            if [ -n "$CHECK" ]; then
              PASS_LENGTH=0
            fi
            # Password with only one repeated character
            CHECK=$(echo $RET | cut -c1-1) || true
            CHECK=$(echo $RET | sed -r "s/$CHECK//g") || true
            if [ -z "$CHECK" ]; then
              PASS_LENGTH=0
            fi
          fi
          if [ $PASS_LENGTH -lt 4 ]; then
            db_reset hoteldruid/administrator-password
            db_input high hoteldruid/administrator-weakpass || true
            db_go || true
          else
            PASS1=$RET
            db_input high hoteldruid/confirm-password || true
            db_go || true
            db_get hoteldruid/confirm-password
            if [ "$PASS1" = "$RET" ]; then
              PASS_MATCH=1
            else
              db_reset hoteldruid/administrator-password
              db_input high hoteldruid/administrator-failpass || true
              db_go || true
            fi
            db_reset hoteldruid/confirm-password
          fi
        fi
      done
    fi
  fi
fi
