#!/bin/sh
set -eu

usage() {
    cat <<EOF
$0: Generate a macOS .app bundle
Usage: $0 [OPTIONS] APPBUNDLE httproot
EOF
}

SCRIPT_DIR=$(dirname "$(readlink -f "$0" 2>/dev/null || printf '%s' "$0")")
run_sh_src="$SCRIPT_DIR/run.sh"
main_scpt_src="$SCRIPT_DIR/main.applescript"
launchd_plist_src="$SCRIPT_DIR/com.example.Simple.plist"

# Parse arguments
appbundle=
httproot=
httpport=8000
while test $# -gt 0; do
    case "$1" in
        -h|--help) usage; exit 0;;
        --port) httpport="$2"; shift 2;;
        -*) printf 'Error: Unknown option: %s\n' "$1" >&2; usage >&2; exit 1;;
        *)
            if test -z "$appbundle"; then
                appbundle="$1"
            elif test -z "$httproot"; then
                httproot="$1"
            else
                printf 'Error: Too many arguments\n' >&2
                usage >&2
                exit 1
            fi
            shift;;
    esac
done

if test -z "$httproot" || test -z "$appbundle"; then
    printf 'Error: Missing required argument\n' >&2
    usage >&2
    exit 1
fi

# Create the app bundle
osacompile -o "$appbundle" "$main_scpt_src"

appinfo_plist_gen="$appbundle/Contents/Info.plist"
launchd_plist_gen="$appbundle/Contents/Resources/com.example.Simple.plist"
launchd_log_path="$HOME/Library/Logs/com.example.Simple.log"

# Set the app bundle Info.plist configuration settings
# Set the app to an "agent" which does not show in the dock or menu bar
/usr/libexec/PlistBuddy -c "Add :LSUIElement bool true" "$appinfo_plist_gen"
# Set bundle identifiers and names
/usr/libexec/PlistBuddy -c "Set :CFBundleName string ExampleBundleSimple" "$appinfo_plist_gen"
# This shows in System Settings > Security & Privacy > Privacy > Full Disk Access, IF the bundle ID is set below
# Otherwise the app will just be shown as `applet`
/usr/libexec/PlistBuddy -c "Add :CFBundleDisplayName string ExampleBundleSimple" "$appinfo_plist_gen"
# Set bundle ID
/usr/libexec/PlistBuddy -c "Add :CFBundleIdentifier string com.example.ExampleBundleSimple" "$appinfo_plist_gen"
# Add app-specific configuration
/usr/libexec/PlistBuddy -c "Add :ExampleApplicationHttpPort integer $httpport" "$appinfo_plist_gen"
/usr/libexec/PlistBuddy -c "Add :ExampleApplicationHttpRoot string $httproot" "$appinfo_plist_gen"

# Install the resources
cp "$run_sh_src" "$appbundle/Contents/Resources/"
cp "$launchd_plist_src" "$appbundle/Contents/Resources/"

# Modify the launchd plist to set the correct path to the app bundle
/usr/libexec/PlistBuddy -c "Set :Program $appbundle/Contents/MacOS/applet" "$launchd_plist_gen"
# Set environment variables for launchd
/usr/libexec/PlistBuddy -c "Set :EnvironmentVariables:EXAMPLE_SIMPLE_VERBOSE true" "$launchd_plist_gen"
/usr/libexec/PlistBuddy -c "Set :EnvironmentVariables:EXAMPLE_SIMPLE_LOG_PATH $launchd_log_path" "$launchd_plist_gen"

# Codesign the app bundle with an ad-hoc signature
codesign --deep --force --sign - "$appbundle"
