
# Parameter Setup
DAEMON_DESTINATION="/Library/LaunchDaemons/{{serviceName}}.plist"
PREFPANE_DESTINATION="/Library/PreferencePanes/{{displayName}}.prefPane"
SERVICE_APP_LOCATION="$TARGET_LOCATION/{{installationSubdirectory}}{{displayName}}.app"
RESOURCE_LOCATION="$SERVICE_APP_LOCATION/Contents/Resources"
SERVICE_PLIST="$RESOURCE_LOCATION/{{displayName}}.prefPane/Contents/Resources/service.plist"
COMMAND="$TARGET_LOCATION/{{installationSubdirectory}}{{displayName}}.app/Contents/MacOS/{{executable}}"

# change owner of the whole application.
if [ ! -z "$DAEMON_USER" ]; then
    echo "Changing user of '$SERVICE_APP_LOCATION' to $DAEMON_USER"
    chown -R "$DAEMON_USER:$DAEMON_USER" "$SERVICE_APP_LOCATION/Contents/Java" || echo "Could not change user"
else
    echo "Will not change the user of '$SERVICE_APP_LOCATION' because it is not set ('$DAEMON_USER')."
fi

# Link prefpane
if [ -L "$PREFPANE_DESTINATION" ]; then
    rm "$PREFPANE_DESTINATION"
fi

ln -s "$RESOURCE_LOCATION/{{displayName}}.prefPane" "$PREFPANE_DESTINATION"

# modify SERVICE_PLIST to reflect current installation
if [ -f "/usr/libexec/PlistBuddy" ]; then
    # Set executable
    /usr/libexec/PlistBuddy -c "Set :Program $COMMAND" "$SERVICE_PLIST"

    # Watch for modification to trigger uninstall
    /usr/libexec/PlistBuddy -c "Add :WatchPaths: String $PREFPANE_DESTINATION" "$UNINSTALL_WATCH"
    /usr/libexec/PlistBuddy -c "Add :WatchPaths: String $SERVICE_APP_LOCATION" "$UNINSTALL_WATCH"
else
    echo "Cannot properly set up the service without the PlistBuddy tool"
    exit 1
fi

# copy default launchd file and start daemon
/usr/bin/ditto "$SERVICE_PLIST" "$DAEMON_DESTINATION"
chown "$(whoami)":wheel "$DAEMON_DESTINATION"
chmod 644 "$DAEMON_DESTINATION"
/bin/launchctl load "$DAEMON_DESTINATION"
