#!/bin/bash

# Get list of open programs and their PIDs
programs=$(sudo lsof -t | xargs ps -p)

# Display list of open programs and their PIDs
echo "Open programs:"
echo "$programs"

# Ask user which program to modify
read -p "Enter the PID of the program you would like to adjust (0 to exit): " pid

# If user enters 0, exit the script
if [[ $pid -eq 0 ]]; then
  exit 0
fi

# Ask user for new value of p variable
read -p "Enter the new value of p variable: " p

# Update the p variable in the script
sudo sed -i "s/^p=.*$/p=$p/" "$0"

# Ask user for process priority level
read -p "Enter process priority level (high/idle): " priority

# Set process priority level using 'nice' command with sudo
if [[ "$priority" == "high" ]]; then
  sudo renice -n -20 -p "$pid"  # set high priority
elif [[ "$priority" == "idle" ]]; then
  sudo renice -n 20 -p "$pid"  # set idle priority
fi

while true; do
  # Get CPU usage of specified program
 cpu=$(top -b -n 1 -p "$pid" | awk 'NR>7 { sum += $9; } END { print sum; }')


  # Get path to executable file associated with specified PID
  exe=$(readlink "/proc/$pid/exe")

  # Get directory containing executable file
  directory=$(dirname "$exe")

  # Get disk usage of directory containing executable file
  disk=$(df -k "$directory" | awk '/\// { print $3 }')

  # Adjust I/O priority based on CPU and disk usage
  if (( $(echo "$cpu >= 5" | bc -l) )); then
    sudo ionice -c 3 -p "$pid"  # set I/O priority to low
  elif (( $(echo "$cpu <= 5" | bc -l) )); then
    sudo ionice -c 1 -n 0 -p "$pid"  # set I/O priority to high
  fi

  # Wait for 1 second before checking again
  sleep 1
done


