#!/bin/bash
# This script uses imapsync. Available in https://github.com/imapsync/imapsync
# Is for cronify and leave running and synchronizing new emails until you end the migration for each account.
# You can leave always running in crontab and only needs to manage the file ListFileToSync with accounts/conf to migrate (empty for none and do nothing)

ListFileToSync="Migrating.list"    # The format must be:  OriginServer;;OriginEmail;;OriginPassword;;DestinationServer;;DestinationnEmail;;DestinationPassword;;Optional1;;Optional2
                                   #   OriginServer     is the server to retrieve emails. It will connect to IMAPS port (993) (except for Optional1 or Optional2 field with Orig_Legacy)
                                   #   DestinationServer is the server to retrieve emails. It will connect to IMAPS port (993)
                                   #
                                   #  You can add two Optional fields:
                                   #   ;;Move           If you want move instead of copy to the Destination sever (This deletes in origin Server the emails copied to the Destination server)
                                   #   ;;Orig_Legacy    Will add --nossl1 --notls1 (¡It will connect to origin server at port 143 in text plain!) (To migrate old server that not allow SSL/TLS)
                                   #
                                   #   Remember, the field separator are two ;;
                                   #    Example1:  imap.server1.com;;origin@origin.com;;Pass1;;imap.server2.com;;dest@destination.com;;Pass2
                                   #    Example2:  imap.server1.com;;origin@origin.com;;Pass1;;imap.server2.com;;dest@destination.com;;Pass2;;Orig_Legacy
                                   #    Example3:  imap.server1.com;;origin@origin.com;;Pass1;;imap.server2.com;;dest@destination.com;;Pass2;;Orig_Legacy;;Move

ApplyLimitAfter=629145600          # bytes 629145600=600MB   # Apply the next Speedlimit to each thread that reach this amount of data in their sync process
SpeedLimit=52428800                # bytes 52428800=50MB/s   # Add speed limit if exceed the Limit before. This also will slow down the end of all the synchro and if you cronify very frecuency it could avoid some next launches if remain some thread running

Pausa=0.4                          # Small wait between accounts to not launch threads at the same time (Don't put high values, for example 3 seconds to sync 100 acounts will add 5 minutes of waits)

MultiThread="True"                 # "True" or other for none(secuential one per one).  With True will launch imapsync with & to leave runnind in background and simulate multithread ( Take it present the SpeedLimit )
MaxThreads=5                       # Max number of imapsync threads allowed to lauch. (Take care with use of memory. With six thread is around ~1GB)
MaxThreadTimeWait=1                # Wait time to check if there are free threads for lauch another thread. Put between 0.1 and 1.  Near ~0 could add some little charge to cpu and won't speed up (frecuency checks)

########################################################################

# Revisa si ya está en ejecución (por si se solapa al cronificar)
if pidof -x $(basename $0) > /dev/null; then
  for p in $(pidof -x $(basename $0)); do
    if [ $p -ne $$ ]; then
      echo "The $0 script is running. Exiting..."
      exit
    fi
  done
fi

touch /tmp/imapsync.pid                      # Para saber la última ejecución y crear alarma en nagios si no se lanza desde hace tiempo


for u in $(cat "${ListFileToSync}"); do      # Recorre todas las cuentas a sincronizar que estén en el fichero

    Orig_Server=$(echo "$u" | awk -F ";;" '{print $1}')
    Orig_Account=$(echo "$u" | awk -F ";;" '{print $2}')
    Orig_Pass=$(echo "$u" | awk -F ";;" '{print $3}')

    Dest_Server=$(echo "$u" | awk -F ";;" '{print $4}')
    Dest_Account=$(echo "$u" | awk -F ";;" '{print $5}')
    Dest_Pass=$(echo "$u" | awk -F ";;" '{print $6}')

    Option1=$(echo "$u" | awk -F ";;" '{print $7}')
    Option2=$(echo "$u" | awk -F ";;" '{print $8}')

    if [ "$Option1" == "Orig_Legacy" ] || [ "$Option2" == "Orig_Legacy" ]; then
        OrigOptions="--nossl1 --notls1"
    else
        OrigOptions=""
    fi

    if [ "$Option1" == "Move" ] || [ "$Option2" == "Move" ]; then
        Mover="--delete1"
    else
        Mover=""
    fi

    if [ "$MultiThread" == "True" ]; then
        imapsync --addheader --skipcrossduplicates --nolog --nofoldersizes --nofoldersizesatend --host1 ${Orig_Server} ${OrigOptions} --user1 ${Orig_Account} --password1 "${Orig_Pass}" --host2 ${Dest_Server} --user2 ${Dest_Account} --password2 "${Dest_Pass}" --maxbytespersecond ${SpeedLimit} --maxbytesafter ${ApplyLimitAfter} ${Mover} &
    else
        imapsync --addheader --skipcrossduplicates --nolog --nofoldersizes --nofoldersizesatend --host1 ${Orig_Server} ${OrigOptions} --user1 ${Orig_Account} --password1 "${Orig_Pass}" --host2 ${Dest_Server} --user2 ${Dest_Account} --password2 "${Dest_Pass}" --maxbytespersecond ${SpeedLimit} --maxbytesafter ${ApplyLimitAfter} ${Mover}
    fi

    sleep ${Pausa}

    # Antes de continuar, revisa que haya menos procesos en ejecución que MaxThread
    while [ $(ps h -C "perl /usr/bin/imapsync" | cut -d " " -f 1 | wc -l) -ge $MaxThreads ]; do
        sleep ${MaxThreadTimeWait}
    done

done


# Espero a que acaben todos los procesos que haya lanzado en segundo plano y sigan activos para que el proceso se mantenga en ejecución y no se solape con el siguiente cron
for p in $(ps h -C "perl /usr/bin/imapsync" | cut -d " " -f 1 | xargs); do  # Recorre todos los procesos que se estan lanzando de imapsync
    wait $p  # Espera que acabe cada uno de los procesos. Ojo a rotación excesiva de procesos, si reasignase numero de proceso esperaria al equivocado
done


#https://github.com/imapsync/imapsync
#https://imapsync.lamiral.info/FAQ.d/FAQ.Duplicates.txt

    # --useuid                   # Use UIDs instead of headers as a criterion to recognize messages
    # --useheader "X-SMID"       #
    # --delete2duplicates        # delete2duplicates solo funciona SIN --useuid
    # --skipcrossduplicates      # Avoid copying messages that are already copied in another folder,  good from Gmail to X when X is not also Gmail. Activated with --gmail1 unless --noskipcrossduplicates (Con mensajes sin cabeceras en borradores no funcionara)
    # --debugcrossduplicates     # Prints which messages (UIDs) are skipped with --skipcrossduplicates (and in what other folders they are).
    # --usecache                 # Use cache to speed up next syncs. Not set by default.     (No noto mejora en cuenta casi vacía de test)
    # --nousecache               # Do not use cache. Caveat(Advertencia): --useuid --nousecache creates duplicates on multiple runs.
    # --addheader                # When a message has no headers to be identified,--addheader adds a "Message-Id" header, like "Message-Id: 12345@imapsync", where 12345 is the imap UID of the message on the host1 folder.
    # --nofoldersizes            # Do not calculate the size of each folder at the beginning of the sync. Default is to calculate them
    # --nofoldersizesatend       # Do not calculate the size of each folder at the end of the sync. Default is to calculate them.
