#!/bin/bash
set -e
BLUE='\033[0;34m'
NC='\033[0m'
current_directory="$(pwd)"
HTML_PATH="${1:-"${current_directory}/cmake-build-debug/coverage/index.html"}"
process_info=$(pgrep -af "python3 -m http.server") || process_info=""
found_matching_process=false
if [[ -n "$process_info" ]]; then
while read -r line; do
pid=$(echo "$line" | awk '{print $1}')
working_directory=$(readlink -f /proc/"$pid"/cwd)
if [[ "$working_directory" == "$current_directory" ]]; then
PORT=$(echo "$line" | grep -oP '\d{4,5}(?= --bind)')
if [[ "$line" =~ --bind\ ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) ]]; then
IP="${BASH_REMATCH[1]}"
fi
echo "Server is already running on IP: $IP and Port: $PORT"
found_matching_process=true
break
fi
done <<< "$process_info"
if ! $found_matching_process; then
echo "No matching server processes found in the current working directory."
fi
else
echo "No python3 -m http.server processes are running."
fi
if ! $found_matching_process; then
IP=$(hostname -I | awk '{print $1}')
PORT=$(seq 8000 9000 | grep -v -x -f <(nc -z localhost -w 1 -v $(seq 8000 9000) 2>&1 | awk '{print $3}') | head -n 1)
if [ -n "$PORT" ]; then
echo "Starting HTTP server at $IP:$PORT"
python3 -m http.server "$PORT" --bind "$IP" >/dev/null 2>/dev/null &
echo "Server started successfully."
else
echo "No available port found."
fi
fi
echo -e "\nOpen the link below to view the coverage report:\n\n${BLUE}http://$IP:$PORT${HTML_PATH}${NC}\n\n"