#!/bin/bash

SCRIPT_DIR=$(dirname "$(readlink -f "$0")")

install_jq() {
    if ! command -v jq &>/dev/null; then
        echo "jq is not installed. Attempting to install..."
        sudo apt-get update
        sudo apt-get install -y jq
    fi
}

install_sendmail() {
    if ! command -v sendmail &>/dev/null; then
        echo "sendmail is not installed. Attempting to install..."
        sudo apt-get update
        sudo apt-get install -y postfix
    fi
}

send_email() {
    subject=$1
    body=$2
    attachment=$3
    logo=$4
    footer_link=$5

    cat <<EOF | sendmail -t
From: $from_email
To: $to_email
Subject: $subject
MIME-Version: 1.0
Content-Type: multipart/related; boundary="BOUNDARY"

--BOUNDARY
Content-Type: text/html; charset="UTF-8"
Content-Disposition: inline

<html>
<body>
<img src="cid:logo.png" alt="Logo" style="width: 200px; height: auto; display: block; margin: 0 auto;"/>
<hr/> <!-- New line below the logo -->
$body
<hr/> <!-- New line above the footer link -->
<p>Visit Our Website: <a href="$footer_link">$footer_link</a></p>
</body>
</html>

--BOUNDARY
Content-Type: image/png
Content-ID: <logo.png>
Content-Disposition: inline
Content-Transfer-Encoding: base64

$(base64 -w 0 "$logo")

--BOUNDARY
Content-Type: text/plain; charset="UTF-8"
Content-Disposition: attachment; filename="service_logs.txt"

$(cat "$attachment")

--BOUNDARY--
EOF
}

retry_download() {
    local url="$1"
    local output_file="$2"
    local retries=3
    local delay=5

    for ((i=1; i<=retries; i++)); do
        echo "Attempt $i: Downloading logo from URL: $url"
        wget -O "$output_file" "$url" --timeout=10
        if [ $? -eq 0 ]; then
            echo "Download completed"
            return 0
        else
            echo "Failed to download logo from URL: $url (Attempt $i)"
            sleep $delay
            delay=$((delay * 2))
        fi
    done
    echo "Failed to download logo after $retries attempts"
    return 1
}

install_jq
install_sendmail

config_file="$SCRIPT_DIR/configuration.json"

if [ ! -f "$config_file" ]; then
    echo "Error: Configuration file '$config_file' not found." >&2
    exit 1
fi

echo "Do you want to start the services? (Y/N)"
read answer

case $answer in
    [Yy]* )
        ;;
    [Nn]* )
        echo "Service start aborted."
        exit;;
    * )
        echo "Invalid input. Service start aborted."
        exit;;
esac

log_file="$SCRIPT_DIR/service_logs.txt"
services=($(jq -r '.services[]' "$config_file"))
from_email=$(jq -r '.email.from' "$config_file")
to_email=$(jq -r '.email.to' "$config_file")
logo=$(jq -r '.email.logo' "$config_file")
footer_link=$(jq -r '.email.link // empty' "$config_file")

if [ -z "$logo" ]; then
    echo "No logo provided in the configuration file."
    echo "Do you want to proceed without the logo? (Y/N)"
    read proceed_without_logo
    case $proceed_without_logo in
        [Yy]* )
            ;;
        [Nn]* )
            echo "Service start aborted."
            exit;;
        * )
            echo "Invalid input. Service start aborted."
            exit;;
    esac
else
    if [[ $logo == http* ]]; then
        echo "Downloading logo from URL: $logo"
        tmp_logo="$SCRIPT_DIR/logo.png"
        wget_output=$(wget -O "$tmp_logo" "$logo" --timeout=10 2>&1)
        wget_exit_status=$?
        if [ $wget_exit_status -ne 0 ]; then
            echo "Failed to download logo from URL: $logo (Exit status: $wget_exit_status)" >&2
            echo "wget output: $wget_output" >&2
            exit 1
        fi
        echo "Download completed"
        logo="$tmp_logo"
    else
        if [ ! -f "$logo" ]; then
            echo "Logo file '$logo' not found."
            echo "Do you wish to proceed without the logo? (Y/N)"
            read proceed_without_logo
            case $proceed_without_logo in
                [Yy]* )
                    ;;
                [Nn]* )
                    echo "Service start aborted."
                    exit;;
                * )
                    echo "Invalid input. Service start aborted."
                    exit;;
            esac
        fi
    fi
fi

echo "Service Start Log:" > "$log_file"
error_occurred=false
success_services=()
failed_services=()

for service in "${services[@]}"; do
    echo "Starting $service..."
    sudo service "$service" start >> "$log_file" 2>&1
    if [ $? -eq 0 ]; then
        success_services+=("$service")
        echo "$service started successfully."
    else
        failed_services+=("$service")
        error_occurred=true
        echo "Failed to start $service." >&2
    fi
done

services_list="<ul>"
for s in "${services[@]}"; do
    services_list+="<li>$s</li>"
done
services_list+="</ul>"

success_list="<ul>"
for s in "${success_services[@]}"; do
    success_list+="<li>$s</li>"
done
success_list+="</ul>"

failed_list="<ul>"
for s in "${failed_services[@]}"; do
    failed_list+="<li>$s</li>"
done
failed_list+="</ul>"

email_body="Service Starting Status:
<hr/>
Services Listed (configuration.json):
$services_list

Success Run:
$success_list

Failed Run:
$failed_list
"

send_email "Service Starting Status" "$email_body" "$log_file" "$logo" "$footer_link"
