#!/bin/bash
#==============================================================================
# description       : Installs and configures Opendkim including DKIM-key activation script.
# author            : Joachim
# email             : joachim.coessens@team.blue
#==============================================================================

if [[ $1 == "-v" ]]; then
    echo "Version: 2.1"
    exit 0
else

function install_dkim() {
#Installing Opendkim

echo "Installing and configuring opendkim"

        apt update
        apt-get install -y opendkim opendkim-tools

echo "Installing Opendkim finished"
echo
echo "Updating opendkim.conf"

# Update /etc/opendkim.conf

# Port 8892
        #sed -i 's|^\s*#\?Socket\s*inet:8892@localhost|Socket inet:8892@localhost|' /etc/opendkim.conf
        #sed -i 's|^\s*Socket\s*local:/var/run/opendkim/opendkim.sock|#Socket local:/var/run/opendkim/opendkim.sock|' /etc/opendkim.conf

# Port 8891
        sed -i 's|^\s*Socket\s*local:/run/opendkim/opendkim.sock|#Socket local:/run/opendkim/opendkim.sock|' /etc/opendkim.conf
        sed -i 's|^\s*#\?Socket\s*inet:8891@localhost|Socket inet:8891@localhost|' /etc/opendkim.conf


#Creating extra DKIM config files
        mkdir -p /etc/opendkim
        touch /etc/opendkim/SigningTable
        touch /etc/opendkim/TrustedHosts
        touch /etc/opendkim/KeyTable
	chown -R opendkim:opendkim /etc/opendkim/

# Define the configuration lines to be added
CONFIG_LINES="
ExternalIgnoreList      refile:/etc/opendkim/TrustedHosts
InternalHosts           refile:/etc/opendkim/TrustedHosts
KeyTable                refile:/etc/opendkim/KeyTable
SigningTable            refile:/etc/opendkim/SigningTable
"

# Function to add a line if it does not already exist
        add_line_if_not_exists() {
            local file=$1
            local line=$2
            grep -qxF "$line" "$file" || echo "$line" | tee -a "$file" > /dev/null
        }

# Path to the opendkim configuration file
OPENDKIM_CONF="/etc/opendkim.conf"


# Iterate over each line in CONFIG_LINES and add it to the file if it does not exist
while IFS= read -r line; do
    add_line_if_not_exists "$OPENDKIM_CONF" "$line"
done <<< "$CONFIG_LINES"

# Append DKIM configurations to /etc/postfix/main.cf if they do not already exist
POSTFIX_CONFIG_LINES="
# OPENDKIM
milter_protocol = 2
milter_default_action = accept
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891
"

POSTFIX_CONF="/etc/postfix/main.cf"

# Iterate over each line in POSTFIX_CONFIG_LINES and add it to the file if it does not exist
while IFS= read -r line; do
    add_line_if_not_exists "$POSTFIX_CONF" "$line"
done <<< "$POSTFIX_CONFIG_LINES"


# Append DKIM configurations to /etc/opendkim/TrustedHosts if they do not already exist
TRUSTEDHOSTS_CONFIG_LINES="
127.0.0.1
localhost
192.168.0.1/24
"

TRUSTEDHOSTS_CONF="/etc/opendkim/TrustedHosts"

# Iterate over each line in TRUSTEDHOSTS_CONFIG_LINES and add it to the file if it does not exist
while IFS= read -r line; do
    add_line_if_not_exists "$TRUSTEDHOSTS_CONF" "$line"
done <<< "$TRUSTEDHOSTS_CONFIG_LINES"

echo "Opendkim setup finished"

echo "Setting up the DKIM activation script"

touch /home/domain.log

echo '#!/bin/bash

domain=`cat /home/domain.log`
for i in $domain

do

mkdir -p /etc/opendkim/keys/$i
cd /etc/opendkim/keys/$i/
/usr/sbin/opendkim-genkey -b 1024 -s mail-out -d $i
chown -R opendkim:opendkim /etc/opendkim/keys/$i/

###/etc/opendkim/SigningTable
echo "*@$i mail-out._domainkey.$i" >> /etc/opendkim/SigningTable

###/etc/opendkim/KeyTable
echo "mail-out._domainkey.$i $i:mail-out:/etc/opendkim/keys/$i/mail-out.private" >> /etc/opendkim/KeyTable

cat /etc/opendkim/keys/$i/mail-out.txt

done

/bin/systemctl reload opendkim' > /usr/local/bin/opendkim-key.sh


chmod +x /usr/local/bin/opendkim-key.sh

echo "Setup DKIM activation script finished"

echo "Reloading Postfix"
/bin/systemctl reload postfix
echo "Restarting Opendkim"
/bin/systemctl restart opendkim

echo "Checking services"

echo -e "\n"

echo "###########################################################################"
systemctl -q is-active postfix.service  && \
echo -e "\033[32m Postfix is running \033[0m" || \
echo -e "\033[31m Postfix is not running - please investigate! \033[0m"

systemctl -q is-active opendkim.service  && \
echo -e "\033[32m Opendkim is running \033[0m" || \
echo -e "\033[31m Opendkim is not running - please investigate! \033[0m"
lsof -i tcp:8891
echo
echo "###########################################################################"
echo -e "\033[32m Add DKIM domains in /home/domain.log and run /usr/local/bin/opendkim-key.sh \033[0m"
echo "###########################################################################"


}



#Check if Opendkim is allready installed

opendkim_status=$(apt-cache policy opendkim | grep "Installed: (none)")

if [[ -z $opendkim_status ]]; then
        echo "Opendkim is allready installed, are you sure you want to continue? This might overwrite current settings."

        read -p "Do you wish to continue? (Y/n): " choice

        if [[ "$choice" == "Y" || "$choice" == "y" ]]; then
            # Install DKIM
                install_dkim
        else
            # Cancel the script
            echo "Script canceled."
            #exit 1
        fi
else
install_dkim

fi
fi
