#!/bin/sh
set -e

# Read environment variables set by launchd plist
# This is read first, and is less error prone, so simple, critical configuration makes sense here
verbose="${EXAMPLE_SIMPLE_VERBOSE:-}"
logpath="${EXAMPLE_SIMPLE_LOG_PATH:-}"

set -u

if test "$logpath"; then
    # Ensure the log directory exists
    mkdir -p "$(dirname "$logpath")"
    # Redirect stdout and stderr to the log file
    exec > "$logpath" 2>&1
fi

if test "$verbose"; then
    set -x
fi

# Assume this script is in $appbundle/Contents/Resources/run.sh
appbundle="$(dirname "$(readlink -f "$0" 2>/dev/null || printf '%s' "$0")")/../.."
echo "Using app bundle path: $appbundle"
infoplist="$appbundle/Contents/Info.plist"

# Read configuration variables from the app's Info.plist
# Items here are available even when launched outside of launchd e.g. from the Finder.
httproot="$(/usr/libexec/PlistBuddy -c "Print :ExampleApplicationHttpRoot" $infoplist)"
httpport="$(/usr/libexec/PlistBuddy -c "Print :ExampleApplicationHttpPort" $infoplist)"

# List the directory once, which ensures the app has access to it
ls -alF "$httproot"

# Run the service
python3 -m http.server --directory "$httproot" "$httpport"
