#!/bin/bash

# Postfix Dockerfile entrypoint
#
# Portions licensed to the University Corporation for Advanced Internet
# Development, Inc. ("UCAID") under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# UCAID licenses this file to you under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

OUTPUT=/dev/stdout

# Configuration details that may be injected through environment
# variables or the contents of files.

injectable_config_vars=( 
    POSTFIX_MYHOSTNAME
    POSTFIX_MYNETWORKS
    POSTFIX_RELAYHOST
)

# If the file associated with a configuration variable is present then 
# read the value from it into the appropriate variable. So for example
# if the variable COMANAGE_REGISTRY_DATASOURCE_FILE exists and its
# value points to a file on the file system then read the contents
# of that file into the variable COMANAGE_REGISTRY_DATASOURCE.

for config_var in "${injectable_config_vars[@]}"
do
    eval file_name=\$"${config_var}_FILE";

    if [ -e "$file_name" ]; then
        declare "${config_var}"=`cat $file_name`
    fi
done

# Create the /etc/mailname file
if [ -n "${POSTFIX_MYHOSTNAME}" ]; then
    MYHOSTNAME=${POSTFIX_MYHOSTNAME}
else
    MYHOSTNAME=`/bin/hostname -f`
fi

echo "${MYHOSTNAME}" > /etc/mailname
chmod 644 /etc/mailname

# Edit the postfix configuration file in place to set myhostname.
sed -i -e s@%%MYHOSTNAME%%@"${MYHOSTNAME}"@ /etc/postfix/main.cf

# Edit the postfix configuration file in place to set mynetworks.
MYNETWORKS=${POSTFIX_MYNETWORKS:-127.0.0.0/8 [::1]/128}
sed -i -e s@%%MYNETWORKS%%@"${MYNETWORKS}"@ /etc/postfix/main.cf

# Edit the postfix configuration file in place to set relayhost.
RELAYHOST=${POSTFIX_RELAYHOST:-}
sed -i -e s@%%RELAYHOST%%@"${RELAYHOST}"@ /etc/postfix/main.cf

exec /usr/lib/postfix/sbin/master -c /etc/postfix -d