#!/bin/bash -e

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

db_capb backup

# Validate an IPv4 address.
function valid_ip()
{
  local  ip=$1
  local  stat=1

  if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    OIFS=$IFS
    IFS='.'
    ip=($ip)
    IFS=$OIFS
    [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
      && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
    stat=$?
  fi
  return $stat
}


# Checking mysql connectivity and updating local.sh environment variables accordingly
check_mysql()
{
  STATE=0
  while [ "$STATE" -eq 0 ]; do
    db_input high alternc/mysql/host || true
    db_go
    db_get alternc/mysql/host || true
    MYSQL_HOST="$RET"
    db_input high alternc/mysql/remote_user || true
    db_go
    db_get alternc/mysql/remote_user || true
    MYSQL_USER="$RET"
    db_input high alternc/mysql/remote_password || true
    db_go
    db_get alternc/mysql/remote_password || true
    MYSQL_PASS="$RET"
    db_input high alternc/mysql/client || true
    db_go
    db_get alternc/mysql/client || true
    MYSQL_CLIENT="$RET"
    if [ "`mysql -u"$MYSQL_USER" -p"$MYSQL_PASS" -h"$MYSQL_HOST" -Bse 'SELECT "OK";' 2>/dev/null`" = "OK" ]; then
      STATE=`expr $STATE + 1`
    else
      db_input high alternc/retry_remote_mysql || true
      if [ $? -eq 30 ]; then
        db_input high alternc/remote_mysql_error || true
        db_go || true
        exit 4
      fi
      db_go
      db_get alternc/retry_remote_mysql || true
      if [ "$RET" = "false" ]; then
        db_input high alternc/remote_mysql_error || true
        db_go || true
        exit 4
      fi
    fi
  done
}

# Return the deepest existing directory in a path
function get_first_existing_dir()
{
  dir="$1"
  if [ -z "$dir" ] ; then
    return 0
  fi
  if ! test -d "$dir" ; then
    get_first_existing_dir "$(dirname "$dir")"
  else
    echo "$dir"
  fi
}


# Compute default values for local.sh
MYSQL_HOST=127.0.0.1
MYSQL_DATABASE=alternc
MYSQL_USER=sysusr
MYSQL_PASS="`perl -e 'print map{("a".."z","A".."Z",0..9)[int(rand(62))]}(1..10)' `"
MYSQL_MAIL_USER=alternc_user
MYSQL_MAIL_PASS="`perl -e 'print map{("a".."z","A".."Z",0..9)[int(rand(62))]}(1..10)' `"
MYSQL_CLIENT=localhost
FQDN="`(cat /etc/mailname 2>/dev/null || hostname -f)|tr '[:upper:]' '[:lower:]'`"
INTERNAL_IP="`env LANG=C /sbin/ip addr show|grep 'inet ' | grep -v 127.0.0.1| head -1 | sed -e 's/^.*inet \([0-9\.]*\).*$/\1/' 2>/dev/null || hostname -f`"
PUBLIC_IP="$INTERNAL_IP"
DEFAULT_MX="`cat /etc/mailname 2>/dev/null || hostname -f`"
ALTERNC_HTML="/var/www/alternc/"
ALTERNC_MAIL="/var/mail/alternc"
ALTERNC_LOGS="/var/log/alternc/sites/"
NS1_HOSTNAME="$FQDN"
NS2_HOSTNAME="$FQDN"
HOSTING="AlternC"
SQLBACKUP_TYPE="rotate"
SQLBACKUP_OVERWRITE="no"
QUEST_STATE=1

while [ "$QUEST_STATE" != 0 -a "$QUEST_STATE" != 14 ]; do
  case "$QUEST_STATE" in
  1)
	if [ -r /etc/alternc/my.cnf ]; then  
		MYSQL_USER=$(cat /etc/alternc/my.cnf |grep "^user"|sed -r 's/user="(.*)"/\1/');  
		MYSQL_PASS=$(cat /etc/alternc/my.cnf |grep "^password"|sed -r 's/password="(.*)"/\1/'); 
		MYSQL_DATABASE=$(cat /etc/alternc/my.cnf |grep "^database"|sed -r 's/database="(.*)"/\1/'); 
		MYSQL_HOST=$(cat /etc/alternc/my.cnf |grep "^host"|sed -r 's/host="(.*)"/\1/'); 
                db_set alternc/mysql/host "$MYSQL_HOST"
                db_set alternc/mysql/db "$MYSQL_DATABASE"
                db_set alternc/mysql/user "$MYSQL_USER"
                db_set alternc/mysql/password "$MYSQL_PASS"
	fi

    if [ -r /etc/alternc/local.sh ]; then
      # source the current config
      . /etc/alternc/local.sh
      # and push it into debconf (its values have priority over anything!)
      db_set alternc/hostingname "$HOSTING"
      db_set alternc/desktopname "`echo $FQDN | tr '[:upper:]' '[:lower:]'`"
      db_set alternc/public_ip "$PUBLIC_IP"
      db_set alternc/internal_ip "$INTERNAL_IP"
      db_set alternc/ns1 "$NS1_HOSTNAME"
      db_set alternc/ns2 "$NS2_HOSTNAME"
      db_set alternc/default_mx "$DEFAULT_MX"
      db_set alternc/alternc_html "$ALTERNC_HTML"
      db_set alternc/alternc_mail "$ALTERNC_MAIL"
      db_set alternc/alternc_logs "$ALTERNC_LOGS"
      db_set alternc/monitor_ip "$MONITOR_IP"
      db_set alternc/default_mx2 "$DEFAULT_SECONDARY_MX"
      db_set alternc/mysql/client "$MYSQL_CLIENT"
      db_set alternc/sql/backup_type "$SQLBACKUP_TYPE"
      db_set alternc/sql/backup_overwrite "$SQLBACKUP_OVERWRITE"
      db_set alternc/mysql/alternc_mail_user "$MYSQL_MAIL_USER"
      db_set alternc/mysql/alternc_mail_password "$MYSQL_MAIL_PASS"
    fi
    # upgrade <= 3.0 to >= 3.1
    if [ "x$ALTERNC_LOC" != "x" ]; then
      ALTERNC_HTML="$ALTERNC_LOC/html"
      ALTERNC_MAIL="$ALTERNC_LOC/mail"
      db_set alternc/alternc_html "$ALTERNC_HTML"
      db_set alternc/alternc_mail "$ALTERNC_MAIL"
    fi

    # We ask for the hosting name and the FQDN
    db_get alternc/hostingname
    if [ -z "$RET" ]; then
      db_set alternc/hostingname "$HOSTING"
      db_input high alternc/hostingname || true
    fi
  ;;
  2)
    # Get the FQDN
    db_get alternc/desktopname
    if [ -z "$RET" ]; then
      db_set alternc/desktopname "$FQDN"
      db_input high alternc/desktopname || true
    fi
    # Ensure that the FQDN is lowercase (Fixes #1405)
    db_get alternc/desktopname
    db_set alternc/desktopname "`echo $RET | tr '[:upper:]' '[:lower:]'`"
  ;;
  3)
    # Ask for the public and private ip
    db_get alternc/public_ip
    if [ -z "$RET" ]; then
        db_set alternc/public_ip "$PUBLIC_IP"
    fi
    STATE=0
    while [ $STATE -eq 0 ]; do
      db_input high alternc/public_ip || true
      db_go
      db_get alternc/public_ip
      ip="$RET"
      if valid_ip $ip ; then
        if [ $(echo $ip |egrep '(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1)$') ]; then
          db_input high alternc/use_private_ip || true
          db_go
          db_get alternc/use_private_ip
          if [ "$RET" = "true" ]; then
            STATE=1
          else
            db_reset alternc/use_private_ip || true
            db_fset alternc/use_private_ip "seen" "false" || true
          fi
        else
          STATE=1
        fi
      else
        STATE=1
      fi
    done
  ;;
  4)
    # Private IP
    db_get alternc/internal_ip
    if [ -z "$RET" ]; then
        db_set alternc/internal_ip "$INTERNAL_IP"
    fi

    STATE=0
    while [ $STATE -eq 0 ]; do
      db_input high alternc/internal_ip || true
      db_go
      db_get alternc/internal_ip
      ip="$RET"
      if  valid_ip $ip ; then
        STATE=1
      fi
    done
  ;;
  5)
    # Ask for the DNS servers
    db_get alternc/ns1
    if [ -z "$RET" ]; then
      db_set alternc/ns1 "$NS1_HOSTNAME"
      db_input high alternc/ns1 || true
    fi
  ;;
  6)
    db_get alternc/ns2
    if [ -z "$RET" ]; then
      db_set alternc/ns2 "$NS2_HOSTNAME"
      db_input high alternc/ns2 || true
    fi
  ;;
  7)
    db_get alternc/default_mx
    if [ -z "$RET" ]; then
      db_set alternc/default_mx "$DEFAULT_MX"
      db_input high alternc/default_mx || true
    fi
  ;;
  8)
    if [ "`mysql --defaults-file=/etc/mysql/debian.cnf -Bse 'SELECT "OK";' 2>/dev/null`" = "OK" ]; then
      db_input critical alternc/use_local_mysql || true
    fi
  ;;
  9)
    db_get alternc/use_local_mysql
    if [ "$RET" != "true" ]; then
      db_input critical alternc/use_remote_mysql || true
    fi
  ;;
  10)
    db_get alternc/use_remote_mysql
    if [ "$RET" == "true" ]; then
      # User want to use a remote server
      check_mysql
    fi
  ;;
  11)
    # We need to set the alternc_location here because we have to test for quotas and acls

    db_get alternc/alternc_html
    if [ -z "$RET" ]; then
      db_set alternc/alternc_html $ALTERNC_HTML
      db_input high alternc/alternc_html || true
    fi
    db_get alternc/alternc_html

    ALTERNC_HTML="$RET"
    # Checking acl and quota activation.
    basedir=`get_first_existing_dir "$ALTERNC_HTML"`;
    MOUNT_POINT=$(df -P ${basedir} | tail -n 1 | awk '{print $6}')
    # Get the first existing dir
    aclcheckfile="$basedir/test-acl"
    touch "$aclcheckfile"
    setfacl -m u:root:rwx "$aclcheckfile" || (
      test -e "$aclcheckfile" && rm -f "$aclcheckfile" || true
      db_input high alternc/acluninstalled || true
      db_go || true
      exit 2
    )
    test -e "$aclcheckfile" && rm -f "$aclcheckfile" || true

    quota -gA -f $MOUNT_POINT || (
      db_get alternc/quotauninstalled
      if [ -z "$RET" ]; then
        db_input critical alternc/quotauninstalled || true
        db_go
        db_set alternc/quotauninstalled "false" || true
      fi
    )
  ;;
  12)
    db_get alternc/alternc_mail
    if [ -z "$RET" ]; then
      db_set alternc/alternc_mail $ALTERNC_MAIL
      db_input high alternc/alternc_mail || true
    fi
  ;;
  13)
    db_get alternc/alternc_logs
    if [ -z "$RET" ];then
      db_set alternc/alternc_logs $ALTERNC_LOGS
      db_input high alternc/alternc_logs || true
    fi
  ;;
  esac
  if db_go; then
    QUEST_STATE=$(($QUEST_STATE + 1))
  else
    QUEST_STATE=$(($QUEST_STATE - 1))
  fi
done

if [ -r /etc/alternc/my.cnf ]; then
  # make mysql configuration available as shell variables
  # to convert from .cnf to shell syntax, we:
  # * match only lines with "equal" in them (/=/)
  # * remove whitespace around the = and add a left quote operator ' (;s)
  # * add a right quote operator at the end of line (;s)
  # * convert mysql variables into our MYSQL_ naming convention (;s)
  # * print the result (;p)
  eval `sed -n -e "/=/{s/ *= *\"\?/='/;s/\"\?\$/'/;s/host/MYSQL_HOST/;s/user/MYSQL_USER/;s/password/MYSQL_PASS/;s/database/MYSQL_DATABASE/;p}" /etc/alternc/my.cnf`
fi

if [ -r /etc/alternc/my_mail.cnf ]; then
  # make mysql configuration available as shell variables
  # to convert from .cnf to shell syntax, we:
  # * match only lines with "equal" in them (/=/)
  # * remove whitespace around the = and add a left quote operator ' (;s)
  # * add a right quote operator at the end of line (;s)
  # * convert mysql variables into our MYSQL_ naming convention (;s)
  # * print the result (;p)
  eval `sed -n -e "/=/{s/ *= *\"\?/='/;s/\"\?\$/'/;s/host/MYSQL_HOST/;s/user/MYSQL_MAIL_USER/;s/password/MYSQL_MAIL_PASS/;s/database/MYSQL_DATABASE/;p}" /etc/alternc/my_mail.cnf`
fi

db_get alternc/monitor_ip
if [ -z "$RET" ]; then
  db_set alternc/monitor_ip "$MONITOR_IP"
fi

db_get alternc/default_mx2
if [ -z "$RET" ]; then
  db_set alternc/default_mx2 "$DEFAULT_SECONDARY_MX"
fi

db_get alternc/mysql/host
if [ -z "$RET" ]; then
  db_set alternc/mysql/host "$MYSQL_HOST"
fi

# Even if we asked the question concerning the database earlier in the process
# Those calls are needed to pass the variable of remote sql server to AlternC
db_get alternc/mysql/db
if [ -z "$RET" ]; then
  db_set alternc/mysql/db "$MYSQL_DATABASE"
fi

db_get alternc/mysql/user
if [ -z "$RET" ]; then
  db_get alternc/mysql/remote_user
  if [ -z "$RET" ]; then
    db_set alternc/mysql/user "$MYSQL_USER"
  else
    db_set alternc/mysql/user "$RET"
  fi
fi

db_get alternc/mysql/password
if [ -z "$RET" ]; then
  db_get alternc/mysql/remote_password
  if [ -z "$RET" ]; then
    db_set alternc/mysql/password "$MYSQL_PASS"
  else
    db_set alternc/mysql/password "$RET"
  fi
fi

db_get alternc/mysql/client
if [ -z "$RET" ]; then
  db_set alternc/mysql/client "$MYSQL_CLIENT"
fi

db_get alternc/sql/backup_type
if [ -z "$RET" ]; then
  db_set alternc/sql/backup_type "$SQLBACKUP_TYPE"
fi

db_get alternc/sql/backup_overwrite
if [ -z "$RET" ]; then
  db_set alternc/sql/backup_overwrite "$SQLBACKUP_OVERWRITE"
fi

db_get alternc/mysql/alternc_mail_user
if [ -z "$RET" ]; then
  db_set alternc/mysql/alternc_mail_user "$MYSQL_MAIL_USER"
fi

db_get alternc/mysql/alternc_mail_password
if [ -z "$RET" ]; then
  db_set alternc/mysql/alternc_mail_password "$MYSQL_MAIL_PASS"
fi

db_input low alternc/default_mx2 || true
db_input low alternc/mysql/host || true
db_input low alternc/mysql/db || true
db_input low alternc/mysql/user || true
db_input low alternc/mysql/password || true
db_input low alternc/mysql/alternc_mail_password || true
db_input low alternc/mysql/alternc_mail_user || true
db_input low alternc/mysql/client || true
db_input low alternc/sql/backup_type || true
db_input low alternc/sql/overwrite || true
db_input low alternc/monitor_ip || true
db_input low alternc/slaves || true
db_go

# vim: et sw=4
