#!/bin/bash
# ========================================================
#  syut.in — macOS Automatic Startup Setup
#  Runs syut.in silently in background when you log into Mac
# ========================================================

cd "$(dirname "$0")"
DIR="$(pwd)"
PLIST="$HOME/Library/LaunchAgents/in.syut.receiver.plist"

mkdir -p "$HOME/Library/LaunchAgents"

NODE_PATH="$(which node 2>/dev/null || echo "/usr/local/bin/node")"

cat <<EOF > "$PLIST"
<?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>in.syut.receiver</string>
    <key>ProgramArguments</key>
    <array>
        <string>$NODE_PATH</string>
        <string>$DIR/server/index.js</string>
    </array>
    <key>WorkingDirectory</key>
    <string>$DIR</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/syut-in.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/syut-in.err</string>
</dict>
</plist>
EOF

launchctl unload "$PLIST" 2>/dev/null
launchctl load "$PLIST" 2>/dev/null

echo "========================================================"
echo "  syut.in is now configured to start automatically"
echo "  in the background whenever you log into your Mac!"
echo "========================================================"
echo "  LaunchAgent created at:"
echo "  $PLIST"
echo "========================================================"
echo "  Admin Console: http://localhost:8083/admin"
echo "========================================================"
read -p "Press Enter to exit..."
