#!/bin/bash
set -e
DIR="$(cd "$(dirname "$0")" && pwd)"
PLIST="$HOME/Library/LaunchAgents/com.lottery.printagent.plist"
mkdir -p "$HOME/Library/LaunchAgents"
cat > "$PLIST" <<PLISTEOF
<?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.lottery.printagent</string>
  <key>ProgramArguments</key><array>
    <string>DIR_PLACEHOLDER/lottery-print-agent.command</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
</dict></plist>
PLISTEOF
sed -i "" "s#DIR_PLACEHOLDER#$DIR#g" "$PLIST"
# Clear the download quarantine on the whole folder so Gatekeeper
# does not block the agent/updates (user right-click-opens THIS once).
xattr -dr com.apple.quarantine "$DIR" 2>/dev/null || true
launchctl unload "$PLIST" 2>/dev/null || true
launchctl load "$PLIST"
echo "Agente configurado para iniciar con la sesión."
