#!/bin/bash

### tls.may.sh
### ----------
### This script look at tls errors into maillog and generate an entry into tls_policy
### so next time server in error send its traffic unencrypted
### Job removes older entries automatically after defined timee


### INSTALL

# Put this script for example in /batch/tls.may.sh and chmod 775

# Put this policy line in main.cf
# smtp_tls_policy_maps = hash:/etc/postfix/tls_policy

# Schedule this script every 15 minutes or when you want like this
# crontab -e
# # tls.may.sh - deactivate tls from unsupported server for some time
# */15 * * * * /batch/tls.may.sh


### PARAMETERS

# My own domain
mydomain=gruppocomet.it

# Maillog file path
flog=/var/log/maillog

# tls_policy path
ftls=/etc/postfix/tls_policy

# Postfix command binaries
postdir=/usr/sbin

# Entry clean after seconds (864.000 = 10 days)
dsec=864000


### EXECUTION

# Touch policy file if not exist
if [ ! -f $ftls ]
then
 touch $ftls
fi

# Generate timestampa and init zero new counter
ts=$(date +%s)
a=0

# Search server name in tls error with sort unique (Cannot start TLS: handshake failure)
shopt -s lastpipe
grep -e '@.*Cannot start TLS: handshake failure' $flog | sed -e 's/.*@\(.*\)>.*/\1/' | sort | uniq | while read -r line
do
 # Exclude local names and unknown
 if [ "$line" != "localhost" ] && [ "$line" != "unknown" ] && [[ $line != *$mydomain ]]
 then
  # echo "Test $line"
  # Insert line is not already present in policy
  if  ! ( grep "^$line " $ftls ) > /dev/nul
  then
   echo "Insert $line"
   #echo "$line none # $ts" >> $ftls (comment unsupported in postfix map files)
   echo "$line none" >> $ftls
   a=$((a+1))
  fi
 fi
done

# Compile & reload postfix if some found
if [ $a -ne 0 ]
then
 echo "Inserted $a hosts entries into $ftls, postmap & reload"
 sleep 1; $postdir/postmap $ftls
 sleep 1; $postdir/postfix reload
fi

# (comment unsupported in postfix map files)

## Clean older elements
#a=0
#while read line; do
# set -- ${line/#/ }
# hostname=$1
# fts=$4
# # echo $hostname $fts
# ((diff = ts - fts))
# ### echo $hostname $fts $diff
# if ((diff >= $dsec)); then
#  # echo "$hostname - timestamp older then $dsec seconds , deleting"
#  sed -i "/$hostname/d" $ftls ; sleep 1
#  a=$((a+1))
# fi
#done < $ftls
#
## Compile & reload postfix if some removed
#if [ $a -ne 0 ]
#then
# echo "Removed $a hosts entries from $ftls that are older than $dsec seconds"
# sleep 1; $postdir/postmap $ftls
# sleep 1; $postdir/postfix reload
#fi


