#!/bin/bash

SERVICE_NAME="${2:-ghost-node.service}"

if [[ "$SERVICE_NAME" != *.service ]]; then
    SERVICE_NAME="${SERVICE_NAME}.service"
fi

SERVICE_FULL_PATH="/etc/systemd/system/$SERVICE_NAME"
SKIPPED_NO_SERVICE="[-] patch-1 skipped: no serivce found at $SERVICE_FULL_PATH"
[[ ! -e "$SERVICE_FULL_PATH" ]] && { echo $SKIPPED_NO_SERVICE; exit 1; }

NETWORK_ONLINE_EXISTS=$(grep -Fx "After=network-online.target" "$SERVICE_FULL_PATH")
NETWORK_EXISTS=$(grep -Fx "After=network.target" "$SERVICE_FULL_PATH")

SKIPPED_SERVICE_OK="[+] patch-1 already applied: network-online.target is set correctly for $SERVICE_FULL_PATH"
[[ ! (-z "$NETWORK_ONLINE_EXISTS" && -n "$NETWORK_EXISTS") ]] && { echo $SKIPPED_SERVICE_OK; exit 0; }

PATCH_MESSAGE="missing network-online.target dependency in $SERVICE_FULL_PATH"
[[ -z "$1" ]] && { echo "[!] patch-1 could be applied: $PATCH_MESSAGE"; exit 2; }

echo "[+] patch-1 will be applied: $PATCH_MESSAGE"
sudo sed -i "s/After=network.target/After=network-online.target\nRequires=network-online.target/g" "$SERVICE_FULL_PATH"
echo "sudo systemctl daemon-reload"
echo "sudo systemctl restart $SERVICE_NAME"
exit 0
