#!/bin/bash

# CSV file structure:
# EMAIL_ACCOUNT EMAIL_PASSWORD_SRC EMAIL_HOST_SRC EMAIL_ADDRESS

# CSV field explanation
# EMAIL_ACCOUNT: Name of the old email account on the source server. i.e. wp1234567-mm
# EMAIL_PASSWORD_SRC: Password for the email account on the source server
# EMAIL_HOST_SRC: Hostname of the source server. i.e.  wp1234567.server-he.de
# EMAIL_ADDRESS: Primary email address for the account on the destination server. Must be unique and the domain must exist on the destination server

# General notes on CSV
# All fields in a row must be filled
# Delimiter is "€", since all other characters might be used in the passwords.
# Upper case letters may only be used in passwords

# Usage
# Clone the he_migration_cwh_fms_plesk repo from code.wartung.xyz to /tmp/
# run /tmp/he_migration_cwh_fms_plesk/update_server_plesk_migration_cwh.sh to make sure the server is setup correctly
# Save the csv, see above, to /tmp/migration_csv
# run /tmp/he_migration_cwh_fms_plesk/import_email_content.sh -f /tmp/migration_csv/MY_MAIL_CREATE.csv

# Ensure the log directory exists
mkdir -p /tmp/migration_logs/
mkdir -p /tmp/migration_logs/imapsync/

# Get the filename of current script and strip .sh from the end
SCRIPT_FILE_NAME=$(basename "$0" .sh)

# Create the log and error filenames
LOG_IMAPSYNC="/tmp/migration_logs/imapsync/"
LOG_FILE_NAME="/tmp/migration_logs/$SCRIPT_FILE_NAME.log"
ERR_FILE_NAME="/tmp/migration_logs/$SCRIPT_FILE_NAME.err"

# Print info about logging
echo "STDOUT redirected to $LOG_FILE_NAME"
echo "STDERR redirected to $ERR_FILE_NAME"

# Check if the necessary argument is provided
if [[ "$#" -lt 1 ]]; then
    echo "Usage: $0 -f <path_to_csv_file>"
    exit 1
fi

# Parse arguments
while getopts "f:" opt; do
    case $opt in
        f) CSV_FILE="$OPTARG" ;;
        *)
            echo "Invalid option: -$OPTARG"
            exit 1
            ;;
    esac
done

# Ensure the CSV file exists
if [[ ! -f "$CSV_FILE" ]]; then
    echo "Error: CSV file not found at $CSV_FILE"
    exit 1
fi

# Check if imapsync is installed
if ! imapsync -version &>/dev/null; then
    echo "Imapsync not installed. Installing ..."

	# Install required packages for imapsync
	apt update  >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME" && apt install -y libauthen-ntlm-perl libclass-load-perl libcrypt-ssleay-perl libdata-uniqid-perl libdigest-hmac-perl libdist-checkconflicts-perl libencode-imaputf7-perl libfile-copy-recursive-perl libfile-tail-perl libio-compress-perl libio-socket-inet6-perl libio-socket-ssl-perl libio-tee-perl libmail-imapclient-perl libmodule-scandeps-perl libnet-dbus-perl libnet-ssleay-perl libpar-packer-perl libreadonly-perl libregexp-common-perl libsys-meminfo-perl libterm-readkey-perl libtest-fatal-perl libtest-mock-guard-perl libtest-mockobject-perl libtest-pod-perl libtest-requires-perl libtest-simple-perl libunicode-string-perl liburi-perl libtest-nowarnings-perl libtest-deep-perl libtest-warn-perl make cpanminus  >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"

	# Clone imapsync git repo to user home
	cd ~/  >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME" && \
	git clone https://github.com/imapsync/imapsync.git >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME" 
	
	# Create symlink to /usr/bin/imapsync
	cd ~/imapsync/ >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME" && \
	ln -s ~/imapsync/imapsync /usr/bin/imapsync >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"

    echo "imapsync is now installed. Continuing with email import ..."
else
    echo "imapsync is already installed. Continuing with email import ..."
fi

# Read local IPv4
SERVER_DEST=$(hostname -I | awk '{print $1}')

# Set EMAIL_HOST_DST to local servers hostname
EMAIL_HOST_DST=$(uname -n)

# Arrays to track success and failures
SUCCESSFUL=()
FAILED=()

# Read the CSV file line by line
HEADER_PROCESSED=false
while IFS='€' read -r EMAIL_ACCOUNT EMAIL_PASSWORD_SRC EMAIL_HOST_SRC EMAIL_ADDRESS; do
    # Skip empty lines
    if [[ -z "$EMAIL_ACCOUNT" || -z "$EMAIL_ADDRESS" ]]; then
      continue
    fi

    # Skip the header line if it exists
    if [[ "$HEADER_PROCESSED" == false ]]; then
      if [[ "$EMAIL_ACCOUNT" == "EMAIL_ACCOUNT" && "$EMAIL_PASSWORD_SRC" == "EMAIL_PASSWORD_SRC" && "$EMAIL_HOST_SRC" == "EMAIL_HOST_SRC" && "$EMAIL_ADDRESS" == "EMAIL_ADDRESS" ]]; then
        HEADER_PROCESSED=true
        continue
      fi
        HEADER_PROCESSED=true
    fi

    # Determin $EMAIL_PASSWORD_DST
    EMAIL_PASSWORD_DST=$( /usr/local/psa/admin/bin/mail_auth_view | grep -w "$EMAIL_ADDRESS" | cut -d '|' -f4 | tr -d '[:space:]' )

    # Convert $EMAIL_ADDRESS to lower case
    EMAIL_ADDRESS="${EMAIL_ADDRESS,,}"

    # Run imapsync command
    echo "Syncing: $EMAIL_ACCOUNT@$EMAIL_HOST_SRC -> $EMAIL_ADDRESS@$SERVER_DEST"
    imapsync \
        --host1 "$EMAIL_HOST_SRC" --user1 "$EMAIL_ACCOUNT" --password1 "$EMAIL_PASSWORD_SRC" \
        --host2 "$SERVER_DEST" --user2 "$EMAIL_ADDRESS" --password2 "$EMAIL_PASSWORD_DST" \
        --tls1 --nossl2 --notls2 --automap --logdir $LOG_IMAPSYNC >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"

    # Check if imapsync succeeded
    if [[ $? -eq 0 ]]; then
        SUCCESSFUL+=("$EMAIL_ACCOUNT@$EMAIL_HOST_SRC -> $EMAIL_ADDRESS@$SERVER_DEST")
    else
        FAILED+=("$EMAIL_ACCOUNT@$EMAIL_HOST_SRC -> $EMAIL_ADDRESS@$SERVER_DEST")
    fi

done < "$CSV_FILE"

# Print summary
echo "Summary:"
echo "---------"
echo "Summary Report:"
echo "Successfully imported folders:"
for ITEM in "${SUCCESSFUL[@]}"; do
    echo "  - $ITEM"
done
echo "---------"
echo "Failed imports:"
for ITEM in "${FAILED[@]}"; do
    echo "  - $ITEM"
done
echo "---------"