#!/bin/bash

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

desiredFile=$1.xml

#going to folder where the website exists
sshpass -p 'Inception@Broadway2023' ssh -o StrictHostKeyChecking=no templates@54.160.76.56 -p 22 "
    cd /home/templates/dental.templates.inception-example.com &&
    wp export --post__in=$2 --post_type=fl-theme-layout,fl-builder-template,page,post --filename_format=$desiredFile --max_file_size=-1
"
cd $websitePath

#define variables to download from IM10 site
fromIP="54.160.76.56"
fromDomain=dental.templates.inception-example.com
fromDomainFull="https://${fromDomain}/$desiredFile"
fromDomainFull="$(echo -e "${fromDomainFull}" | tr -d '[:space:]')"

# Check if the file exists on the target domain
if wget --spider "$fromDomainFull"; then
    # Download the file
    wget "$fromDomainFull" -O "$desiredFile"
# Else check if file is in wp-admin folder
elif wget --spider "$fromDomainFullBackup"; then
    # Download the file from there instead
    wget "$fromDomainFullBackup" -O "$desiredFile"
else
    echo "Could not find the exported file. Please try again."
    exit 1
fi

#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 [[ $(echo $?) == 1 ]]; then
    id=wordpress-importer
    fileName="plugin_copy.zip"
        #going to folder where the website exists
    sshpass -p 'Inception@Broadway2023' ssh -o StrictHostKeyChecking=no templates@54.160.76.56 -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
    #define variables to download from Templates site
    fromIP="54.160.76.56"
    fromDomain=templates.inception-example.com
    fromDomainFull="https://${fromDomain}/$fileName"
    fromDomainFull="$(echo -e "${fromDomainFull}" | tr -d '[:space:]')"
    
    #download the file to our site
    curl --resolve "$fromDomain":443:"$fromIP" -o $fileName "$fromDomainFull" &> /dev/null;
    
    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@54.160.76.56 -p 22 << 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 [[ $(echo $?) == 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=$(/usr/local/bin/php /usr/local/bin/wp import $desiredFile --authors=skip --allow-root)

rm -f $desiredFile

#going to folder where the website exists
sshpass -p 'Inception@Broadway2023' ssh -o StrictHostKeyChecking=no templates@54.160.76.56 -p 22 << EOF
    cd /home/templates/dental.templates.inception-example.com
    rm -f $desiredFile
    exit
EOF

#error handlers
if [[ "$import" == *"already exists"* ]]; then
    while read -r line; do
      if [[ $line == "Processing post"* ]]; then
        post_id=$(echo "$line" | grep -oP '#\K\d+')
        title=$(echo "$line" | grep -o '".*"' | sed 's/"//g')
        echo "Importing ID #$post_id: $title ..."
      fi
    done <<< "$import"
    echo ""
    existing_posts=$(echo "$import" | grep -oP 'Post &#8220;\K[^&#]+(?=&#8221; already exists)')
    types=Posts
    if [[ -z $existing_posts ]]; then
    existing_posts=$(echo "$import" | grep -oP 'Page &#8220;\K[^&#]+(?=&#8221; already exists)')
    types=Pages
    if [[ -z $existing_posts ]]; then
        existing_posts=$(echo "$import" | grep -oP 'Template &#8220;\K[^&#]+(?=&#8221; already exists)')
        types=Templates
    fi
    fi
    echo "One or more of the $types you attempted to import already exists on this site. The following $types were not imported:"
    echo "$existing_posts"
    exit 1
fi

if [[ "$import" == "Starting export process..." ]]; then
    echo "Could Not Find Template File."
    exit 1
fi

echo "Templates Imported Successfully!"
exit 0
