#!/bin/sh

# This spell allows you to add or remove directories from your PATH environment variable permanently.
# It uses the 'grep' and 'sed' commands to search and edit the '.bashrc' file in your home directory.

# Check if the correct number of arguments was provided
if [ "$#" -ne 1 ] && [ "$#" -ne 2 ]; then
  echo "Error: This spell requires one or two arguments: 'add' or 'remove' and an optional directory path."
  exit 1
fi

# Set the action and directory variables
action=$1
directory=$2

# Check if the action is 'add' or 'remove'
if [ "$action" != "add" ] && [ "$action" != "remove" ]; then
  echo "Error: The first argument must be 'add' or 'remove'."
  exit 1
fi

# Check if the directory path was provided
if [ -z "$directory" ]; then
  # If no directory path was provided, use the current directory
  directory=$(pwd)
else
  # If a directory path was provided, expand the '~' character if necessary
  directory="${directory/#\~/$HOME}"
fi

# Check if the directory exists
if [ ! -d "$directory" ]; then
  echo "Error: The directory does not exist."
  exit 1
fi

# Check if the '.bashrc' file exists in the home directory
if [ ! -f "$HOME/.bashrc" ]; then
  echo "Error: The '.bashrc' file does not exist in your home directory."
  exit 1
fi

# Check if the directory is already in the PATH variable
if grep -q "$directory" "$HOME/.bashrc"; then
  # If the directory is already in the PATH variable, check if the action is 'add'
  if [ "$action" = "add" ]; then
    echo "The directory is already in your PATH."
    exit 0
  fi

  # If the action is 'remove' and the directory is already in the PATH variable, remove the directory from the PATH variable using the 'sed' command
  sed -i "\|$directory|d" "$HOME/.bashrc"
  echo "The directory has been removed from your PATH."
else
  # If the directory is not in the PATH variable, check if the action is 'add'
  if [ "$action" = "add" ]; then
    # If the action is 'add', append the directory to the PATH variable in the '.bashrc' file
    echo "export PATH=$PATH:$directory" >> "$HOME/.bashrc"
    echo "The directory has been added to your PATH."
  else
    # If the action is 'remove' and the directory is not in the PATH variable, display an error message
    echo "Error: The directory is not in your PATH."
    exit 1
  fi
fi

if [ "$action" = "add" ]; then
	echo "The changes to your PATH will not take effect until you open a new terminal or run the 'source ~/.bashrc' command in your current terminal."
else
	echo "The changes to your PATH will not take effect until you open a new terminal."
fi