#!/bin/bash

# Check if an executable is provided as an argument
if [ -z "$1" ]; then
  echo "Usage: $0 <executable>"
  exit 1
fi

# Find the executable path using 'which'
EXEC_PATH=$(which "$1")

# Check if the executable exists
if [ -z "$EXEC_PATH" ]; then
  echo "Error: Executable '$1' not found."
  exit 1
fi

# Get the executable name
EXEC_NAME=$(basename "$EXEC_PATH")

# Create the launchd plist file content
PLIST_FILE_CONTENT="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
  <key>Label</key>
  <string>$EXEC_NAME</string>
  <key>ProgramArguments</key>
  <array>
    <string>$EXEC_PATH</string>
  </array>
  <key>KeepAlive</key>
  <true/>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>"

# Create the launchd plist file
PLIST_FILE="$HOME/Library/LaunchAgents/$EXEC_NAME.plist"
echo "$PLIST_FILE_CONTENT" > "$PLIST_FILE"

# Load the launchd service
launchctl load "$PLIST_FILE"

echo "Service '$EXEC_NAME' has been created and loaded."