#!/usr/bin/env bash
# ZPLServer — macOS install script
# Must be run as root or with sudo.
set -euo pipefail

INSTALL_DIR="/usr/local/zplserver"
BINARY_NAME="ZPLServer"
DYLIB_NAME="libSkiaSharp.dylib"
PLIST_PATH="/Library/LaunchDaemons/com.neodynamic.zplserver.plist"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [[ $EUID -ne 0 ]]; then
    echo "Error: this script must be run as root (use sudo)." >&2
    exit 1
fi

for f in "$BINARY_NAME" "$DYLIB_NAME"; do
    if [[ ! -f "$SCRIPT_DIR/$f" ]]; then
        echo "Error: $f not found in the same folder as this script." >&2
        exit 1
    fi
done

# --- Copy files ---
echo "Installing to $INSTALL_DIR ..."
mkdir -p "$INSTALL_DIR"
cp "$SCRIPT_DIR/$BINARY_NAME" "$INSTALL_DIR/$BINARY_NAME"
cp "$SCRIPT_DIR/$DYLIB_NAME"  "$INSTALL_DIR/$DYLIB_NAME"
chmod +x "$INSTALL_DIR/$BINARY_NAME"

# --- Write launchd plist ---
echo "Writing launchd plist..."
cat > "$PLIST_PATH" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.neodynamic.zplserver</string>

    <key>ProgramArguments</key>
    <array>
        <string>$INSTALL_DIR/$BINARY_NAME</string>
    </array>

    <key>WorkingDirectory</key>
    <string>$INSTALL_DIR</string>

    <key>RunAtLoad</key>
    <true/>

    <key>KeepAlive</key>
    <true/>

    <key>StandardOutPath</key>
    <string>$INSTALL_DIR/stdout.log</string>

    <key>StandardErrorPath</key>
    <string>$INSTALL_DIR/stderr.log</string>
</dict>
</plist>
EOF

chown root:wheel "$PLIST_PATH"
chmod 644 "$PLIST_PATH"

# --- Load and start ---
echo "Loading and starting service..."
launchctl load "$PLIST_PATH"
launchctl start com.neodynamic.zplserver

echo ""
echo "ZPLServer installed and started successfully."
echo "Run the following to open the Settings page:"
echo "  $INSTALL_DIR/$BINARY_NAME --settings"
