#!/bin/bash

# Configuration
SERVICE="apache2"
SLACK_WEBHOOK="https://slack.com/api/chat.postMessage"
SLACK_AUTH="xoxb-5949199497329-7014750916150-kE39CrmxYaSAKarkbITBRbnV"
SLACK_CHANNEL="C0896RFDC3G"

# Get server details
PUBLIC_IP=$(curl -s http://checkip.amazonaws.com)
HOSTNAME=$(hostname)

# Check the status of apache2
STATUS=$(systemctl is-active $SERVICE)

if [ "$STATUS" != "active" ]; then
    echo "Service $SERVICE is $STATUS. Attempting to restart." > /tmp/apache2_status.log

    # Restart apache2
    systemctl restart $SERVICE

    # Check if the restart was successful
    NEW_STATUS=$(systemctl is-active $SERVICE)

    if [ "$NEW_STATUS" = "active" ]; then
        echo "Service $SERVICE restarted successfully." >> /tmp/apache2_status.log

        # Send Slack notification
        curl -H "Content-type: application/json" \
             --data '{"channel":"'$SLACK_CHANNEL'","blocks":[{"type":"section","text":{"type":"mrkdwn","text":"@channel The *'$SERVICE'* service was '$STATUS' and has been successfully restarted on server *'$HOSTNAME'* with IP *'$PUBLIC_IP'*."}}]}' \
             -H "Authorization: Bearer $SLACK_AUTH" \
             -X POST $SLACK_WEBHOOK
    else
        echo "Failed to restart $SERVICE. Please check the service manually." >> /tmp/apache2_status.log

        # Optional: Send a different Slack notification
        curl -H "Content-type: application/json" \
             --data '{"channel":"'$SLACK_CHANNEL'","blocks":[{"type":"section","text":{"type":"mrkdwn","text":"@channel The *'$SERVICE'* service was '$STATUS' and the restart attempt failed on server *'$HOSTNAME'* with IP *'$PUBLIC_IP'*. Manual intervention required."}}]}' \
             -H "Authorization: Bearer $SLACK_AUTH" \
             -X POST $SLACK_WEBHOOK
    fi
else
    echo "Service $SERVICE is running normally. No action required." > /tmp/apache2_status.log
fi
