#!/bin/bash

#-------------------------------------------------------------------
# Copyright (c) since 2015, Axigen Messeging. All rights reserved.
# For feedback and/or bugs in this script, please send an e-mail to:
#   "AXIGEN Team" <team@axigen.com>
#-------------------------------------------------------------------

#
# Rev: 2017052501 - Ioan Indreias: Minor improvments (logging, working directory, lftp call)
# Rev: 2017030301 - Florin Burada: Fix detection for redirect rules
# Rev: 2015081701 - Florin Burada: Initial version
#

FTPUSER="admin"                                 # admin user with Backup rights
FTPPASS="axigen-admin"                          # admin password
HOST="127.0.0.1"                                # ftp hostname/IP
PORT="21"                                       # ftp port


### Please do not modify anything below this line ###

DOMAIN=$1 
WORKDIR=$(mktemp -d -p /var/tmp 2>/dev/null)    # temporary work folder
WORKFILE="tmp.txt"                              # temporaty work file
FILE_DATE=$(date +"%Y_%m_%d")                   # output csv file
CSV_FILE="$FILE_DATE-$DOMAIN.csv"

if [ -z "$DOMAIN" ]; then
  cat << EOF

Usage: $(basename $0) <domain_name>

Note: this script depends on LFTP - please use your local package manager to install it"

This script will connect to your Axigen server on one of your FTP listeners and extract
the forward and redirect rules configured for all accounts of a specific domain.

In order to configure the script for your environment please update the following variables:
	FTPUSER
	FTPPASS
	HOST
	PORT

The output will be saved in CSV format, with the following fields:
	EMAIL,RULE TYPE,RULE NAME,ACTION,STATUS
where:
	RULE TYPE = User   >>  rule set by user
	RULE TYPE = Admin  >>  rule set by admin

	STATUS = 1   >>  rule is enabled
	STATUS = 0   >>  rule is disabled

EOF
  exit 1
fi

info=$(which lftp 2>&1)
if [ $? -gt 0 ]
then
  echo
  echo "Error: LFTP not found - please install it and try again!"
  exit 1
fi

if [ ! -d "$WORKDIR" ]; then
  WORKDIR=/var/tmp/$(basename $0).$$
  mkdir -p "$WORKDIR"
fi

TMP_FILE="$WORKDIR/$WORKFILE"
ACCOUNTS_FILE="$WORKDIR/accounts.txt"
LFTP_CMDS="set net:max-retries 3; set net:reconnect-interval-base 1; set net:timeout 10; open -u $FTPUSER,$FTPPASS -p $PORT $HOST"

lftp -c "$LFTP_CMDS; ls domains/$DOMAIN/accounts > \"$WORKDIR/$WORKFILE\"; exit"
if [ $? -gt 0 ]
then
  echo
  echo "Error: LFTP could not retrieve domain '$DOMAIN' accounts from host '$HOST' on port '$PORT'"
  exit 11
fi

awk 'NF>1{print $NF}' "$WORKDIR/$WORKFILE" > "$ACCOUNTS_FILE"
rm -f "$WORKDIR/$WORKFILE"

lftp -c "$LFTP_CMDS;
	cd domains/$DOMAIN/accounts/;
	mget */w*.sieve -d -O $WORKDIR;
        exit"
	
echo "EMAIL,RULE TYPE,RULE NAME,ACTION,STATUS" > $CSV_FILE

while read -r ACCOUNT
do
	if [ -f $WORKDIR/$ACCOUNT/wmFilter.sieve ]; then
		grep "forward*\s\"\|redirect*\s\s\"\|redirect*\s\:\|^##Filter" $WORKDIR/$ACCOUNT/wmFilter.sieve | tee -a "$TMP_FILE.wmf" |
	    while read -r tmpline
	    do
	        FIRST_WORD=`echo $tmpline | awk '{ print $1 }'`
		SECOND_WORD=`echo $tmpline | awk '{ print $2 }'`
	        if [ "$FIRST_WORD" = "##Filter" ];  then
			FILTER_TYPE="User"
			NUME_FILTRU=`echo $tmpline |  awk -F"name=" '{print $2}' | awk -F'"' '{print $2}'`  
			STATUS=`echo $tmpline | awk -F"enabled=" '{print $2}' | awk '{print $1}'`		
		else 
			if [ "$FIRST_WORD" = "forward" ];  then 
				ACTIUNE=`echo $tmpline | awk '{print $2}' | awk '{print $1}'`
				echo "$ACCOUNT@$DOMAIN,$FILTER_TYPE,$NUME_FILTRU,forward to $ACTIUNE,$STATUS" 	
			else
                       	if [ "$FIRST_WORD" = "redirect" ];  then
					if [ "$SECOND_WORD" = ":copy" ];  then 
                                               ACTIUNE=`echo $tmpline | awk '{print $3}' | cut -d ";" -f 1`
                                              echo "$ACCOUNT@$DOMAIN,$FILTER_TYPE,$NUME_FILTRU,redirect to $ACTIUNE,$STATUS" 
					else
                                		ACTIUNE=`echo $tmpline | awk '{print $2}' | cut -d ";" -f 1` 
	                                	echo "$ACCOUNT@$DOMAIN,$FILTER_TYPE,$NUME_FILTRU,redirect to $ACTIUNE,$STATUS"   
					fi
				fi
			fi		
		fi
	    done
	fi

	if [ -f $WORKDIR/$ACCOUNT/waFilter.sieve ]; then
               grep "forward*\s\"\|redirect*\s\s\"\|redirect*\s\:\|^##Filter" $WORKDIR/$ACCOUNT/waFilter.sieve | tee -a "$TMP_FILE.waf" |
            while read -r tmpline
            do
                FIRST_WORD_ADM=`echo $tmpline | awk '{ print $1 }'`
		SECOND_WORD=`echo $tmpline | awk '{ print $2 }'`
                if [ "$FIRST_WORD_ADM" = "##Filter" ];  then
                        FILTER_TYPE="Admin"
                        NUME_FILTRU=`echo $tmpline | awk -F"name=" '{print $2}' | awk -F'"' '{print $2}'`
			STATUS=`echo $tmpline | awk -F"enabled=" '{print $2}' | awk '{print $1}'`
                else
                        if [ "$FIRST_WORD_ADM" = "forward" ];  then
                                ACTIUNE=`echo $tmpline | awk '{print $2}'` 
                                echo "$ACCOUNT@$DOMAIN,$FILTER_TYPE,$NUME_FILTRU,forward to $ACTIUNE,$STATUS" 	
               		else
                        	if [ "$FIRST_WORD_ADM" = "redirect" ];  then
                                        if [ "$SECOND_WORD" = ":copy" ];  then   
                                                ACTIUNE=`echo $tmpline | awk '{print $3}' | cut -d ";" -f 1`
                                                echo "$ACCOUNT@$DOMAIN,$FILTER_TYPE,$NUME_FILTRU,redirect to $ACTIUNE,$STATUS" 
                                        else
                                                ACTIUNE=`echo $tmpline | awk '{print $2}' | cut -d ";" -f 1`
                                                echo "$ACCOUNT@$DOMAIN,$FILTER_TYPE,$NUME_FILTRU,redirect to $ACTIUNE,$STATUS"   
                                        fi

                        	fi
			fi
                fi
	    done
	fi

done < "$ACCOUNTS_FILE" | grep "forward\|redirect" | sed 's/"//g' >> $CSV_FILE

if [ -z "$DEBUG_MODE" ]; then
	rm -rf "$WORKDIR"
else
	echo "Debug info: all data have been saved in $WORKDIR"
fi

if [ $(cat "$CSV_FILE" | wc -l) -gt 1 ]
then
  echo "Domain: $DOMAIN Data: $CSV_FILE"
else
  echo "Domain: $DOMAIN Data: no-rules-detected"
fi
