#!/bin/bash

### Include ymclibnettools
. /usr/lib/lib-fliwi/ymc-networktools.bash

postfix_dir="/etc/postfix"
target_file=$postfix_dir"/mail-server-standalone.main.cf.fliwi"


### Get the public hostname
mail_hostname=''
ip=$(ymc_get_primary_ip_for_network wan || ymc_get_primary_ip_for_network www)
if [ $? -eq 0 ]; then
  auto_public_hostname=$(ymc_get_ptr_full_hostname_for_ip $ip)
  if [ $? -eq 0 ]; then
    mail_hostname=$auto_public_hostname
  fi
fi
if [ "$mail_hostname" == '' ]; then
  echo "WARNING: Failed to get the systems public hostname - falling back to the local full hostname" 1>&2
  echo "         Mails to remote destination will most likely be dropped!" 1>&2
  ### Use the systems long hostname as an fallback
  fallback_mail_hostname=$(ymc_get_local_full_hostname)
  if [ $? -eq 0 ]; then
    mail_hostname=$fallback_mail_hostname
  fi
fi
if [ "$mail_hostname" == '' ]; then
  echo "ERROR: Could not determine a valid full hostname" 1>&2
  exit 1
else
  echo "INFO: Setting $mail_hostname as the systems mail name"
  echo $mail_hostname > /etc/mailname
fi

additional_mail_service_ips=""
for possible_mail_service_name in $(fliwi-get-my-services | grep mail-server)
do
  additional_inet_interface_ip=$(gethostip -d $possible_mail_service_name)
  if [ $? -eq 0 ] && \
     [ "$additional_inet_interface_ip" != "" ]; then
    additional_mail_service_ips=', '$additional_inet_interface_ip
  fi
done


echo "# Dynamic main.cf file for postfix(1) generated by $(basename $0)" > $target_file
echo "#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN" >> $target_file

echo 'myorigin = /etc/mailname' >> $target_file
echo 'myhostname = '$mail_hostname >> $target_file
echo 'smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)' >> $target_file
echo 'biff = no' >> $target_file
echo 'append_dot_mydomain = no' >> $target_file
echo 'delay_warning_time = 4h' >> $target_file
echo 'readme_directory = no' >> $target_file

echo 'alias_maps = hash:/etc/aliases' >> $target_file
echo 'alias_database = hash:/etc/aliases' >> $target_file
echo 'mydestination = $myhostname, localhost.cluster, localhost' >> $target_file

echo 'relayhost = ' >> $target_file
echo 'mynetworks = 127.0.0.0/8' >> $target_file
echo 'mailbox_size_limit = 0' >> $target_file
echo 'message_size_limit = 0' >> $target_file

echo 'recipient_delimiter = +' >> $target_file
echo 'inet_interfaces = 127.0.0.1, '$(ymc_get_primary_ip_for_network lan)$additional_mail_service_ips >> $target_file
echo 'mailbox_command = procmail -a "$EXTENSION"' >> $target_file
echo 'inet_protocols = ipv4' >> $target_file
echo 'smtpd_recipient_restrictions = permit_mynetworks,reject_unauth_destination' >> $target_file

echo 'smtpd_client_restrictions =' >> $target_file
echo '    permit_mynetworks' >> $target_file
echo '    reject_unauth_pipelining' >> $target_file


