#!/bin/bash

# CSV file structure:
# SUBSCRIPTION DOMAIN TYPE PHP_HANDLER EMAIL_SERVICE DNS_MANAGEMENT DIR_SOURCE IGNORE

# CSV field explanation
# SUBSCRIPTION: must be an existing subscription for subdomains or aliases
# DOMAIN: Name of the Domain to add. Only sub-part for subdomains
# TYPE: Not used in this script. Only in CSV, since the same CSV is also used for the create subscription script
# PHP_HANDLER: Not used in this script. Only in CSV, since the same CSV is also used for the create subscription script
# EMAIL_SERVICE: Not used in this script. Only in CSV, since the same CSV is also used for the create subscription script
# DNS_MANAGEMENT: Not used in this script. Only in CSV, since the same CSV is also used for the create subscription script
# DIR_SOURCE: relativ path to the web_root of this website, relativ from the user_root on the source server
# IGNORE: Folders in the websites web_root, that should be ignored during magration, since they might contain content of another vhost. seperated by ',''

# General notes on CSV
# Delimiter is '€', since other charackters might be used in $DIR_SOURCE or $IGNORE

# 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
# Rsync the content of the source docroot directly into /tmp/migration_webspace/
# run /tmp/he_migration_cwh_fms_plesk/import_webspace_plesk_content -f /tmp/migration_csv/MY_WEBSPACE_IMPORT.csv -w 1234567

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

# 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_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"

# Function to print usage
usage() {
    echo "Usage: $0 -f <csv_file> -w <wpid>"
    exit 1
}

# Parse command line arguments
while getopts "f:w:" opt; do
    case ${opt} in
        f ) CSV_FILE=$OPTARG ;;
        w ) WPID=$OPTARG ;;
        * ) usage ;;
    esac
done

# Check if required arguments are provided
if [[ -z "$CSV_FILE" || -z "$WPID" ]]; then
    usage
fi

# Define TMP_DIR
TMP_DIR="/tmp/migration_webspace"

# Create log dir
mkdir -p /tmp/migration_logs/

# Arrays for tracking success and failures
SUCCESSFUL=()
FAILED=()

# Read CSV file line by line
HEADER_PROCESSED=false
while IFS='€' read -r SUBSCRIPTION DOMAIN TYPE PHP_HANDLER EMAIL_SERVICE DNS_MANAGEMENT DIR_SOURCE IGNORE; do
    # Skip empty lines
    if [[ -z "$SUBSCRIPTION" || -z "DOMAIN" || -z "DIR_SOURCE"  ]]; then
        continue
    fi
    # Skip the header line if it exists
    if [[ "$HEADER_PROCESSED" == false ]]; then
        if [[ "$SUBSCRIPTION" == "SUBSCRIPTION" && "$DOMAIN" == "DOMAIN" && "$TYPE" == "TYPE" && "$PHP_HANDLER" == "PHP_HANDLER" && "$EMAIL_SERVICE" == "EMAIL_SERVICE" && "$DNS_MANAGEMENT" == "DNS_MANAGEMENT" && "$DIR_SOURCE" == "DIR_SOURCE" && "$IGNORE" == "IGNORE" ]]; then
            HEADER_PROCESSED=true
            continue
        fi
        HEADER_PROCESSED=true
    fi

    if [[ "$TYPE" != "alias" ]]; then

        # Define destination path
        if [[ "$DOMAIN" == "$SUBSCRIPTION" ]]; then
            DIR_DST="/var/www/vhosts/$SUBSCRIPTION/httpdocs/"
        else
            DIR_DST="/var/www/vhosts/$SUBSCRIPTION/$DOMAIN.$SUBSCRIPTION/"
        fi
        # Create destination directory if not exists
        mkdir -p "$DIR_DST" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
        # Define source path on new server
        DIR_DST_SOURCE="$TMP_DIR$DIR_SOURCE"

        # Convert ignore list to an array
        IFS=',' read -ra IGNORE_FOLDERS <<< "$IGNORE" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"

        # Rsync command to move files excluding ignored folders
        RSYNC_EXCLUDES=""
        for FOLDER in "${IGNORE_FOLDERS[@]}"; do
            RSYNC_EXCLUDES+="--exclude=$FOLDER "
        done
        echo "Starting RSYNC to move files from "$TMP_DIR" to "$DIR_DST"."
        rsync -av --remove-source-files $RSYNC_EXCLUDES "$DIR_DST_SOURCE" "$DIR_DST" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
        EXIT_CODE=$?
        if [[ $EXIT_CODE -eq 0 ]]; then
            SUCCESSFUL+=("Successful rsync $DIR_DST_SOURCE to $DIR_DST")
        else
            FAILED+=("Failed rsync $DIR_DST_SOURCE to $DIR_DST")
        fi
        echo "RSYNC from "$TMP_DIR" to "$DIR_DST" finished."
        # Correct permissions
        echo "Fixing permissions for "$DIR_DST"."
        # Get the current owner of /var/www/vhosts/$SUBSCRIPTION/
        USER=$(stat -c "%U" "/var/www/vhosts/$SUBSCRIPTION/")
        # Change ownership and permissions
        chown -R "$USER":psacln "$DIR_DST" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
        find "$DIR_DST" -type d -exec chmod 755 {} + >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
        find "$DIR_DST" -type f -exec chmod 644 {} + >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
        echo "Fixing permissions for "$DIR_DST" done."

        # Search for files containing the old database credentials
        echo "Searching for files with database credentials ... and writing to /tmp/migration_logs/db_credentials_wp"$WPID".log"
        echo "Searching for files with dbu-user ... and writing to /tmp/migration_logs/dbu_user_wp"$WPID".log"
        echo "Searching for files with old generic domains ... and writing to /tmp/migration_logs/generic_domain_wp"$WPID".log"
        echo "Searching for files with old docroot and user_tmp ... and writing to /tmp/migration_logs/generic_domain_wp"$WPID".log"
        find "$DIR_DST" -type f -print0 | while IFS= read -r -d $'\0' FILE; do
            grep -nE "db$WPID|dbu$WPID|wp$WPID.server-he.de|webpack.hosteurope.de|/is/htdocs/wp$WPID|/is/htdocs/user_tmp/wp$WPID" "$FILE" | while IFS=: read -r LINENUM LINE; do
                if [[ "$LINE" == *"db$WPID"* ]]; then
                        echo "$LINENUM $FILE ${LINE:0:80}" >> /tmp/migration_logs/db_credentials_wp"$WPID".log
                elif [[ "$LINE" == *"dbu$WPID"* ]]; then
                        echo "$LINENUM $FILE ${LINE:0:80}" >> /tmp/migration_logs/dbu_user_wp"$WPID".log
                elif [[ "$LINE" == *"wp$WPID.server-he.de"* ]]; then
                        echo "$LINENUM $FILE ${LINE:0:80}" >> /tmp/migration_logs/generic_domain_wp"$WPID".log
                elif [[ "$LINE" == *"webpack.hosteurope.de"* ]]; then
                        echo "$LINENUM $FILE ${LINE:0:80}" >> /tmp/migration_logs/generic_domain_wp"$WPID".log
                elif [[ "$LINE" == *"/is/htdocs/wp$WPID"* ]]; then
                        echo "$LINENUM $FILE ${LINE:0:80}" >> /tmp/migration_logs/old_docroot_user_tmp_wp"$WPID".log
                elif [[ "$LINE" == *"/is/htdocs/user_tmp/wp$WPID"* ]]; then
                        echo "$LINENUM $FILE ${LINE:0:80}" >> /tmp/migration_logs/old_docroot_user_tmp_wp"$WPID".log
                fi
            done
        done
        echo "Search complete. Results written to"
        echo "/tmp/migration_logs/db_credentials_wp"$WPID".log"
        echo "/tmp/migration_logs/dbu_user_wp"$WPID".log"
        echo "/tmp/migration_logs/generic_domain_wp"$WPID".log"
        echo "/tmp/migration_logs/generic_domain_wp"$WPID".log"
    else
        FAILED+=("Invalid domain type $TYPE" for $DOMAIN)
    fi
done < "$CSV_FILE"


# Create .tgz from remaining files
tar -czf "/root/webspace_migration_unused_wp"$WPID".tgz" "$TMP_DIR" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"

# Ensure $DIR_SOURCE is within /tmp
if [[ "$TMP_DIR" == /tmp/* ]]; then
    echo "Removing directory: $TMP_DIR"
    rm -rf "$TMP_DIR"
else
    echo "Error: DIR_SOURCE is not within /tmp. Aborting."
    exit 1
fi

# Print summary
echo "Summary of file moves:"
echo "Successful Moves:"
for ITEM in "${SUCCESSFUL[@]}"; do
    echo "- $ITEM"
done
echo "Failed Moves:"
for ITEM in "${FAILED[@]}"; do
    echo "- $ITEM"
done