#!/bin/bash

toDomain="$1"
fromDomain="$2"

if echo "$fromDomain" | grep -q "\.xml$"; then
    fromDomain=""
    uploadedFile="$2"
    desiredFile=$(echo "$uploadedFile" | sed 's:.*/::')
    echo $desiredFile
fi

#stores path to toDomain within variable
websitePath=$(uapi --output=jsonpretty DomainInfo single_domain_data domain=$1 | jq -r '.result.data.documentroot')

#change directories to public_html folder
cd $websitePath

#if file already exists in the directory, remove it to prevent errors
if [ -f "inceptionpagecopy1.xml" ]; then
    rm -f "inceptionpagecopy1.xml"
fi

#if fromDomain is not empty
if [ ! -z "$fromDomain" ]; then
    # Remove "https://" or "http://"
    fromDomain="${fromDomain#https://}"
    fromDomain="${fromDomain#http://}"
    
    # Remove "www."
    fromDomain="${fromDomain#www.}"
    
    # Remove any path component after the domain name
    fromDomain="${fromDomain%%/*}"
    
    # Remove leading and trailing spaces
    fromDomain=$(echo "$fromDomain" | tr -d '[:space:]')
    
    # Correct IP addresses for each server
    fromIP=$(dig +short $fromDomain)
    
    fromIP=$(echo "$fromIP" | tr -d '[:space:]')
    
    if [ "$fromIP" = "67.225.142.120" ]; then
        fromIP="172.16.142.120"
    elif [ "$fromIP" = "67.225.142.95" ]; then
        fromIP="172.16.142.95"
    elif [ "$fromIP" = "67.225.142.161" ]; then
        fromIP="172.16.142.161"
    elif [ "$fromIP" = "67.225.142.212" ]; then
        fromIP="172.16.142.212"
    elif [ "$fromIP" = "67.225.142.253" ]; then
        fromIP="172.16.142.253"
    elif [ "$fromIP" = "67.225.142.252" ]; then
        fromIP="172.16.142.252"
    elif [ "$fromIP" = "172.16.142.95" ]; then
        fromIP="172.16.142.95"
    elif [ "$fromIP" = "172.16.142.161" ]; then
        fromIP="172.16.142.161"
    elif [ "$fromIP" = "172.16.142.212" ]; then
        fromIP="172.16.142.212"
    elif [ "$fromIP" = "172.16.142.253" ]; then
        fromIP="172.16.142.253"
    elif [ "$fromIP" = "172.16.142.120" ]; then
        fromIP="172.16.142.120"
    elif [ "$fromIP" = "172.16.142.252" ]; then
        fromIP="172.16.142.252"
    elif [ "$fromIP" = "52.0.54.202" ]; then
        fromIP="52.0.54.202"
    elif [ "$fromIP" = "54.88.226.218" ]; then
        fromIP="54.88.226.218"
    elif [ "$fromIP" = "54.160.76.56" ]; then
        fromIP="54.160.76.56"
    elif [ "$fromIP" = "44.223.220.152" ]; then
        fromIP="44.223.220.152"
    elif [ "$fromIP" = "44.223.213.21" ]; then
        fromIP="44.223.213.21"
    elif [ "$fromIP" = "18.214.60.67" ]; then
        fromIP="18.214.60.67"
    else 
        echo "If this IS our site, it might not be fully propagated yet on all servers. Please either try again later or download the XML file from the Exporter and import it using the old WordPress Importer."
        echo "IP Address I'm Getting: $fromIP"
    fi
    
    # Define the full path to the file to import
    fromDomainFull="https://www.${fromDomain}/inceptionpagecopy1.xml"
    fromDomainFull="$(echo "${fromDomainFull}" | tr -d '[:space:]')"
    
    fromDomainFullBackup="https://www.${fromDomain}/wp-admin/inceptionpagecopy1.xml"
    fromDomainFullBackup="$(echo "${fromDomainFullBackup}" | tr -d '[:space:]')"
    
    desiredFile="inceptionpagecopy1.xml"
    
    #check if the file exists on the target domain
    if wget --spider "$fromDomainFull"; then
        #download the file
        wget "$fromDomainFull" -O inceptionpagecopy1.xml
        #else check if file is in wp-admin folder
    elif wget --spider "$fromDomainFullBackup"; 
    then
        #download the file from there instead
        wget "$fromDomainFullBackup" -O inceptionpagecopy1.xml
    else
        echo "Could not find the exported file. Please make sure you exported it, double-check the domain you're entering, and try again."
        exit 1
    fi
fi

#if the file has been downloaded
if [ -f "$desiredFile" ]; then
    #check wp import plugin installed and active
    /usr/local/bin/php /usr/local/bin/wp plugin is-installed wordpress-importer --allow-root
    
    #if plugin not installed, install it
    if [ $? -eq 1 ]; then
        echo "installing plugin, defining variables"
        id=wordpress-importer
        fileName="plugin_copy.zip"
            #going to folder where the website exists
        echo "logging into web03"
        sshpass -p 'Inception@Broadway2023' ssh -o StrictHostKeyChecking=no templates@172.16.142.161 -p 522 << EOF
        cd /home/templates/public_html/wp-content/plugins
    
        # Check if the directory exists
        if [ -d "/home/templates/public_html/wp-content/plugins/\$id" ]; then
            zip -r /home/templates/public_html/plugin_copy.zip "$id" >/dev/null 2>&1
            if [ $? -eq 0 ]; then
                echo "WordPress Importer plugin was not installed. Working on installing it now..."
            else
                echo "Failed to create Plugin ZIP file"
            fi
        else
            echo "Directory not found: /home/templates/public_html/wp-content/plugins/\$id"
        fi
    
        exit
EOF

        echo "downloading the zip file"
        #define variables to download from Templates site
        fromIP="172.16.142.161"
        fromDomain=templates.inception-example.com
        fromDomainFull="https://www.${fromDomain}/$fileName"
        fromDomainFull="$(echo -e "${fromDomainFull}" | tr -d '[:space:]')"
        
        #download the file to our site
        wget "$fromDomainFull" -O $fileName

        if [ -e "$fileName" ]; then
            echo " "
        else
            echo
            echo "The file $fileName could not be copied. Please contact the Tech Team."
            exit 1
        fi
        
        #move the file to the plugin directory
        mv $fileName $websitePath/wp-content/plugins/$fileName
        
        #unzip the file
        unzip "$websitePath/wp-content/plugins/$fileName" -d "$websitePath/wp-content/plugins/" >/dev/null 2>&1
        
        # Check if the directory exists
        if [ -d "$websitePath/wp-content/plugins/$id" ]; then
            echo " "
        else
            echo
            echo "Issue Unzipping Plugin File - Please contact the Tech Team."
            exit 1
        fi
        
        #going to back to Templates website and removing temp file
        sshpass -p 'Inception@Broadway2023' ssh -o StrictHostKeyChecking=no templates@172.16.142.161 -p 522 << EOF
        cd /home/templates/public_html
        rm -f $fileName
        exit
EOF
    
        #remove the temp zip file
        rm -f $websitePath/wp-content/plugins/$fileName
       
        #activate the plugin on the website
        /usr/local/bin/php /usr/local/bin/wp plugin activate $id --allow-root
        echo
    fi
    
    #check importer plugin is active
    /usr/local/bin/php /usr/local/bin/wp plugin is-active wordpress-importer --allow-root
    #if not active, activate it
    if [ $? -eq 1 ]; then
        id=wordpress-importer
        echo "WordPress Importer plugin was deactivated - Working on activating it..."
        /usr/local/bin/php /usr/local/bin/wp plugin activate $id --allow-root
        echo
    fi

    #import the file onto the site
    import=$(/usr/local/bin/php /usr/local/bin/wp import "$desiredFile" --authors=skip --allow-root)

    #error handlers
    if echo "$import" | grep -q "already exists"; then
        if echo "$import" | grep -q "Processing post"; then
            post_id=$(echo "$import" | grep -oP 'Processing post #\K\d+')
            title=$(echo "$import" | grep -oP 'Processing post #\d+ \("\K[^"]+(?="\))')
            echo "Importing Post: \n$title ..."
        fi
        echo ""
        existing_posts=$(echo "$import" | grep -oP 'Post &#8220;\K[^&#]+(?=&#8221; already exists)')
        existing_pages=$(echo "$import" | grep -oP 'Page &#8220;\K[^&#]+(?=&#8221; already exists)')
        echo "One or more of the pages you attempted to import already exists on this site. The following Posts & Pages were not imported:"
        echo "$existing_posts"
        echo "$existing_pages"
        
        #if file was uploaded, remove it
        if [ ! -z "$uploadedFile" ]; then
            if rm -f "$uploadedFile"; then
                exit 1
            else
                echo "ERROR: Failed to remove file '$desiredFile'."
                exit 1
            fi
        fi
    exit 1
    fi

    if [ "$import" = "Starting export process..." ]; then
        echo "Issue with the file. Please re-export it and try again."
        exit 1
    fi
    
    #success message
    if echo "$import" | grep -q "Processing post"; then
        post_id=$(echo "$import" | grep -oP 'Processing post #\K\d+')
        title=$(echo "$import" | grep -oP 'Processing post #\d+ \("\K[^"]+(?="\))')
        echo "Imported Post: \n$title"
    fi

    #if file was uploaded, remove it
    if [ ! -z "$uploadedFile" ]; then
        if rm -f "$uploadedFile"; then
            exit 0
        else
            echo "ERROR: Failed to remove file '$desiredFile'."
            exit 1
        fi
    fi
else 
    echo "Could not find your exported file. Please make sure you exported it, double-check the domain you're entering, and try again."
    exit 1
fi