#!/bin/bash

# CSV file structure:
# DOMAIN SSL_CERT_FILENAME PASSWORD

# General notes on CSV
# DOMAIN: Domain for which the cert should be imported and enabled.
# SSL_CERT_FILENAME: Filename of the PKCS12 file containing the full cert and privatkey.
# PASSWORD: Password for PKCS12 file. Usually matches the HE-CUST-ID.

# General notes on CSV
# All fields in a row must be filled
# Delimiter is '€', since all other characters might be used in the 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
# Download pkcs12 certs from the customers SKD to /tmp/migration_ssl
# run /tmp/he_migration_cwh_fms_plesk/import_ssl_plesk_certificates.sh -f /tmp/migration_csv/MY_SSL_IMPORT.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

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

# Read the CSV file line by line
HEADER_PROCESSED=false
while IFS="€" read -r DOMAIN SSL_CERT_FILENAME PASSWORD; do
    # Skip empty lines
    if [[ -z "$DOMAIN" || -z "$SSL_CERT_FILENAME" || -z "$PASSWORD" ]]; then
        FAILED+=("Skipping incomplete line in CSV file - $DOMAIN")
        continue
    fi

    # Skip the header line if it exists
    if [[ "$HEADER_PROCESSED" == false ]]; then
        if [[ "$DOMAIN" == "Domain" && "$SSL_CERT_FILENAME" == "SSL_CERT_FILENAME" && "$PASSWORD" == "PASSWORD" ]]; then
            HEADER_PROCESSED=true
            continue
        fi
        HEADER_PROCESSED=true
    fi

    CERT_FILE="/tmp/migration_ssl/${SSL_CERT_FILENAME}.crt.pem"
    KEY_FILE="/tmp/migration_ssl/${SSL_CERT_FILENAME}.key.pem"
    CERT_NAME="Starfield SSL $SSL_CERT_FILENAME"

    # Extract CERT and KEY from PKCS12 file
    openssl pkcs12 -in "/tmp/migration_ssl/$SSL_CERT_FILENAME" -passin "pass:$PASSWORD" -out "$CERT_FILE" -nokeys && \
    openssl pkcs12 -in "/tmp/migration_ssl/$SSL_CERT_FILENAME" -passin "pass:$PASSWORD" -out "$KEY_FILE" -nocerts -nodes

    if [[ $? -ne 0 ]]; then
        FAILED+=("Failed to extract cert and key for $DOMAIN")
        continue
    fi

    # Add the cert to Plesk
    echo "Adding SSL certificate for $DOMAIN"
    plesk bin certificate -c "$CERT_NAME" -domain "$DOMAIN" -cert-file "$CERT_FILE" -cacert-file "$CERT_FILE" -key-file "$KEY_FILE" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
    if [[ $? -ne 0 ]]; then
        FAILED+=("Failed to add certificate to Plesk for $DOMAIN")
        continue
    fi

    # Activate the SSL certificate
    echo "Enabling SSL certificate for $DOMAIN"
    plesk bin site -u "$DOMAIN" -certificate-name "$CERT_NAME" >> "$LOG_FILE_NAME" 2>> "$ERR_FILE_NAME"
    if [[ $? -ne 0 ]]; then
        FAILED+=("Failed to activate certificate for $DOMAIN")
        continue
    fi
    SUCCESSFUL+=("Successfully imported and activated SSL for $DOMAIN")
done < "$CSV_FILE"

# Print summary
echo "Summary:"
echo "---------"
echo "Successful Subscriptions:"
for ITEM in "${SUCCESSFUL[@]}"; do
    echo "- $ITEM"
done

echo "Failed Subscriptions:"
for ITEM in "${FAILED[@]}"; do
    echo "- $ITEM"
done
