#!/bin/bash

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

# CSV field explanation
# SUBSCRIPTION: Name of the Domain. For Subdomains only the base domain i.e for test.he.de only he.de
# DOMAIN: Name of the Domain to add. For Subdomains only the sub-part domain i.e for test.he.de only test
# TYPE: can be domain, subdomain or alias.
# PHP_HANDLER: 81 82 83 84
# EMAIL_SERVICE: default is yes for domains, can be set to no. Is ignored for subdomains an aliases
# DNS_MANAGEMENT: default is yes for domains, can be set to no. Is ignored for subdomains an aliases
# DIR_SOURCE: Not used in this script. Only in CSV, since the same CSV is also used for the actual import script 
# IGNORE: Not used in this script. Only in CSV, since the same CSV is also used for the actual import script

# General notes on CSV
# All fields in a row must be filled, except IGNORE
# 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
# run /tmp/he_migration_cwh_fms_plesk/create_subscription_plesk_domains.sh -f /tmp/migration_csv/MY_SUBSCRIPTION_CREATE.csv

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

# 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

# Making sure CSV files formatting is correct
echo "Checking $CSV_FILE for BOM, CRLF and Empty Lines"
    # Remove BOM (Byte Order Mark) from $CSV_FILE
    sed -i '1s/^\xEF\xBB\xBF//' "$CSV_FILE"

    # Remove CRLF (Windows Line Endings) from $CSV_FILE
    sed -i 's/\r$//' "$CSV_FILE"

    # Remove empty lines
    sed -i '/^$/d' "$CSV_FILE"
echo "Done converting $CSV_FILE"

# Initialize summary arrays
SUCCESSFUL=()
FAILED=()

# Function to generate a random password
generate_password() {
  tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}

# Check if the server has shared IPv4 and IPv6
echo "Checking for shared IPv4 and shared IPv6"
SHARED_IPV4=$(plesk bin ipmanage --ip_list | awk '$2 == "S" {print $3}' | grep '\.' | cut -d ':' -f2 | cut -d '/' -f1)
SHARED_IPV6=$(plesk bin ipmanage --ip_list | awk '$2 == "S" {print $3}' | awk -F: '{sub($1 ":", ""); print}' | grep ':' | cut -d'/' -f1)

if [[ -z "$SHARED_IPV4" || -z "$SHARED_IPV6" ]]; then
    echo "Error: Server does not have both shared IPv4 and IPv6 addresses."
    exit 1
fi

# Read CSV and process each 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 "TYPE"  ]]; 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

  # Determine action based on domain type
  case "$TYPE" in
      domain)

        # Check if the subscription already exists
        if plesk bin subscription --info "$DOMAIN" &>/dev/null; then
            echo "Subscription for $DOMAIN already exists. Skipping."
            FAILED+=("$DOMAIN: Already exists")
            continue
        fi

        # Clear password variable
        LOGIN_PASSWORD=""

        # Generate a random password for the login user
        if [ -z "$LOGIN_PASSWORD" ]; then
           LOGIN_PASSWORD=$(generate_password)
        fi

        # Create the subscription & set php_handler
        echo "Creating subscription $DOMAIN"
        plesk bin subscription --create "$DOMAIN" -owner admin -login "$DOMAIN" -passwd "$LOGIN_PASSWORD" -service-plan "Unlimited" -ip "$SHARED_IPV4, $SHARED_IPV6" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME" && \
        plesk bin domain -u "$DOMAIN" -php_handler_id plesk-php"$PHP_HANDLER"-fpm >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
        if [[ $? -eq 0 ]]; then
            echo "  - Changed PHP_HANDLER for $DOMAIN to plesk-php"$PHP_HANDLER"-fpm."
        else
            echo "  - Failed to change PHP_HANDLER for $DOMAIN to plesk-php"$PHP_HANDLER"-fpm"
        fi

        if [[ $? -eq 0 ]]; then
            echo "Successfully created subscription for $DOMAIN."

            # Disable email service if EMAIL_SERVICE is no, No, or NO
            if [[ "$EMAIL_SERVICE" =~ ^[nN][oO]$ ]]; then
                plesk bin mail --off "$DOMAIN" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
                if [[ $? -eq 0 ]]; then
                    echo "  - Disabled email service for $DOMAIN."
                else
                    echo "  - Failed to disable email service for $DOMAIN."
                fi
            fi

            # Disable DNS management if DNS_MANAGEMENT is no, No, or NO
            if [[ "$DNS_MANAGEMENT" =~ ^[nN][oO]$ ]]; then
                plesk bin dns --off "$DOMAIN" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
                if [[ $? -eq 0 ]]; then
                    echo "  - Disabled DNS management for $DOMAIN."
                else
                    echo "  - Failed to disable DNS management for $DOMAIN."
                fi
            fi

            SUCCESSFUL+=("$DOMAIN: Domain/Subscription created successfully")
        else
        echo "Failed to create subscription for $DOMAIN."
        FAILED+=("$DOMAIN: Creation of domain/subscription failed")
    fi
    ;;
    
      subdomain)
        FULL_SUBDOMAIN="$DOMAIN.$SUBSCRIPTION"
        echo "Creating subdomain $FULL_SUBDOMAIN in subscription $SUBSCRIPTION"
        if plesk bin subdomain --create "$DOMAIN" -domain "$SUBSCRIPTION" -www-root "$FULL_SUBDOMAIN" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"; then
            SUCCESSFUL+=("$FULL_SUBDOMAIN: Subdomain created successfully")
        else
            echo "Failed to create subdomain $FULL_SUBDOMAIN." && \
            FAILED+=("$FULL_SUBDOMAIN: Creation of subdomain failed")
        fi
        plesk bin domain -u "$FULL_SUBDOMAIN" -php_handler_id plesk-php"$PHP_HANDLER"-fpm >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
        if [[ $? -eq 0 ]]; then
            echo "  - Changed PHP_HANDLER for $FULL_SUBDOMAIN to plesk-php"$PHP_HANDLER"-fpm."
        else
            echo "  - Failed to change PHP_HANDLER for $FULL_SUBDOMAIN to plesk-php"$PHP_HANDLER"-fpm"
        fi
        ;;

    alias)
        echo "Creating alias $DOMAIN for $SUBSCRIPTION"
        if plesk bin domalias --create "$DOMAIN" -domain "$SUBSCRIPTION" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"; then
        SUCCESSFUL+=("$DOMAIN: Alias created successfully for $SUBSCRIPTION.")
      else
        echo "Failed to create alias $DOMAIN_NAME for $SUBSCRIPTION" && \
        FAILED+=("$DOMAIN: Alias creation failed for $SUBSCRIPTION")
      fi
      ;;

    *)
      echo "Unknown or unsupported domain type $TYPE for $DOMAIN" && \
      FAILED+=("Unknown domain type $TYPE for $DOMAIN.")
      ;;
  esac

done < "$CSV_FILE"

# Print summary
echo "Summary:"
echo "---------"
echo "Successfully created entries:"
for ITEM in "${SUCCESSFUL[@]}"; do
  echo "$ITEM"
done
echo "---------"
echo "Failed to create entries:"
for ITEM in "${FAILED[@]}"; do
  echo "$ITEM"
done
echo "---------"