#!/bin/bash

# Set the paths and other configurations
monitoring_script_path="/usr/local/bin/application_monitor.sh"
service_file="/etc/systemd/system/application_monitor.service"
log_file="/var/log/application_monitor.log"

# Note Make sure to enter correct process name of Application

# Set the process names of the applications
process1_name="APPLICATION_ProcessNAME1"
process2_name="APPLICATION_ProcessNAME2"

# Fetch the paths to the executables
process1_path=$(which APPLICATION_Process_NAME1)
process2_path=$(which APPLICATION_Process_NAME2)

# Write the monitoring script content to the file
cat <<EOF > "$monitoring_script_path"
#!/bin/bash

# Set the process names of the applications
process1_name="$process1_name"
process2_name="$process2_name"

# Fetch the paths to the executables
process1_path="$process1_path"
process2_path="$process2_path"

# Delay before starting monitoring loop (in seconds)
initial_delay=10

# Initial delay
sleep \$initial_delay

# Start monitoring loop
while true; do
    # Check if process1 is running and terminate it if it is
    if pgrep "\$process1_name" > /dev/null; then
        echo "\$(date +"%Y-%m-%d %H:%M:%S") - \$process1_name is running. Terminating..." >> "$log_file"
        # Terminate process1
        pkill "\$process1_name"
    fi

    # Check if process2 is running and terminate it if it is
    if pgrep "\$process2_name" > /dev/null; then
        echo "\$(date +"%Y-%m-%d %H:%M:%S") - \$process2_name is running. Terminating..." >> "$log_file"
        # Terminate process2
        pkill "\$process2_name"
    fi

    # Block execution of process1 executable
    chmod -x "\$process1_path"

    # Block execution of process2 executable
    chmod -x "\$process2_path"

    # Sleep for 24 hours
    sleep \$((24 * 60 * 60))

    # Restore execution permission for process1 executable
    chmod +x "\$process1_path"

    # Restore execution permission for process2 executable
    chmod +x "\$process2_path"
done
EOF

# Set execute permissions for the monitoring script
chmod +x "$monitoring_script_path"

# Write the service unit file
cat <<EOF > "$service_file"
[Unit]
Description=Application Monitor Service
After=network.target

[Service]
Type=simple
ExecStart="$monitoring_script_path"
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd
systemctl daemon-reload

# Enable and start the service
systemctl enable application_monitor.service
systemctl start application_monitor.service

# Check the status of the service
systemctl status application_monitor.service
