#!/usr/bin/env bash
###################################################################
#
#	File    : RunForever
#	Author  : adb <alex@alexdball.dev>
#	Created : 23-01-02
#
###################################################################
#
# Runs the given application/script
# at the given interval
#
# Clear the screen
clear
#
# Set the colors for the prompt
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Set the usage message
USAGE="\n${RED}[x]${NC} Usage : RunForever INTERVAL SCRIPT_TO_RUN 'PARAMETERS' \n\nSuuports scripts that are executable (Bash / Python)\n"

# Set the no script/application found message
NO_SCRIPT="\n${RED}[x]${NC} Script/Applicaiton ${GREEN}$2${NC} does not exist! Aborting...\n\n"

# Set the info header text
INFO_HEADER="${BLUE}[*]${NC} Running : $2 every $1 seconds..\n\n"

# Set the termination message text
TERMINATION_MESSAGE="${YELLOW}[i]${NC} Press CTRL+C at any time to terminate...\n\n"

# Check if parameters where given.
if [ -z "$1" ] || [ -z "$2" ]
then
	printf "$USAGE\n"
	exit 0
fi

# Set the variable for the application (binary/in path) to be run.
APP=$(whereis $2 | awk '{print $2}')

# Check if the executable parameter exists as an app in path
if [ ! -z "$APP" ]
then
    # Set the executable to the application
    EXEC=$APP
else
    
    # If parameter does not exist in path, check if is a file and it exists.
    if [ -f "$2" ]
    then
        # Set the execytable to the full filename
        EXEC="$2"
    else
        # Warn the user that the application/script does not exist and abort.
		printf "$NO_SCRIPT"
		exit 0
    fi

fi

# Show the info header
printf "$INFO_HEADER"

# Show the termination message
printf "$TERMINATION_MESSAGE"

# Wait 3 seconds before beginning execution
sleep 3

# Set the counter to 0 when the script starts
COUNT=0

    # Begin the loop of execution    
    while :; do

        # Execute the application with its parameters
        $EXEC $3

        # Increment the counter by on.
        COUNT=$(($COUNT + 1))

        # Set Process complete message
        PROCESS_COMPLETE="\n${GREEN}[*]${NC} Process complete..\n\n${YELLOW}[i] ${NC}Ran ${BLUE}$COUNT${NC} times total..\n\n"

        # Display the process complete and run count message
        printf "$PROCESS_COMPLETE"

        # Wait for the given interval until running again
        sleep $1

    done 
