#!/bin/sh
set -ex

# Read environment variables set by launchd plist
reporoot="${MICAHRL_REPOROOT}"
logpath="${MICAHRL_LOG_PATH:-}"

set -u

# If log path is set, redirect output to it
if test -n "$logpath"; then
    # Truncate the log file and redirect stdout and stderr to it
    exec > "$logpath" 2>&1
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 environment variables from the app's Info.plist
hugo="$(/usr/libexec/PlistBuddy -c "Print :MicahrlHugo" "$infoplist")"
svchost="$(/usr/libexec/PlistBuddy -c "Print :MicahrlServiceHost" "$infoplist")"
svcport="$(/usr/libexec/PlistBuddy -c "Print :MicahrlServicePort" "$infoplist")"
devport="$(/usr/libexec/PlistBuddy -c "Print :MicahrlDevPort" "$infoplist")"
vedport="$(/usr/libexec/PlistBuddy -c "Print :MicahrlVedPort" "$infoplist")"
environment="$(/usr/libexec/PlistBuddy -c "Print :MicahrlEnvironment" "$infoplist")"
destination="$(/usr/libexec/PlistBuddy -c "Print :MicahrlDestination" "$infoplist")"
# Test for required environment variables
if test -z "$reporoot"; then
    echo "Error: Required environment variable(s) not set."
    echo "Please ensure that all required environment variables are set in the Launch Agent plist."
    exit 1
fi
if test -z "$hugo" \
    || test -z "$svchost" \
    || test -z "$svcport" \
    || test -z "$environment" \
    || test -z "$destination"
then
    echo "Error: Required plist variable(s) not set."
    echo "Please ensure that all required variables are set in the application's Info.plist."
    exit 1
fi

# Check TCC permissions early by attempting to access both paths
# This will trigger the permission dialog if needed
echo "Reading required paths..."
echo "Hugo path: $hugo"
$hugo version
echo "Repository root: $reporoot"
ls -alF "$reporoot"
cd "$reporoot"

# Required to make the mirroring work
export HUGO_DEV_HOST="$svchost"
export HUGO_DEV_PORT="$devport"
export HUGO_VED_PORT="$vedport"

$hugo server \
    --buildDrafts \
    --buildFuture \
    --bind 0.0.0.0 \
    --printPathWarnings \
    --templateMetrics \
    --templateMetricsHints \
    --logLevel debug \
    --environment "$environment" \
    --destination "$destination" \
    --baseURL "$svchost" \
    --port "$svcport"
