#!/bin/sh
set -eu
REVPN_UID=$(/usr/bin/stat -f %u /dev/console)
if [ "$REVPN_UID" -lt 501 ]; then
    echo 'Install reVPN while a desktop user is logged in.' >&2
    exit 1
fi
/bin/mkdir -p /Library/PrivilegedHelperTools/app.revpn.helper
/usr/sbin/chown -R root:wheel /Library/PrivilegedHelperTools/app.revpn.helper
/bin/chmod 700 /Library/PrivilegedHelperTools/app.revpn.helper
/bin/chmod 755 /Library/PrivilegedHelperTools/app.revpn.helper/revpn-helper /Library/PrivilegedHelperTools/app.revpn.helper/sing-box
/bin/cat > /Library/LaunchDaemons/app.revpn.helper.plist <<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>app.revpn.helper</string>
<key>ProgramArguments</key><array>
<string>/Library/PrivilegedHelperTools/app.revpn.helper/revpn-helper</string>
<string>--uid</string><string>$REVPN_UID</string>
</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>ProcessType</key><string>Interactive</string>
<key>ExitTimeOut</key><integer>20</integer>
<key>ThrottleInterval</key><integer>5</integer>
<key>AssociatedBundleIdentifiers</key><array><string>app.revpn.desktop</string></array>
</dict></plist>
PLIST
/usr/sbin/chown root:wheel /Library/LaunchDaemons/app.revpn.helper.plist
/bin/chmod 644 /Library/LaunchDaemons/app.revpn.helper.plist
/bin/launchctl enable system/app.revpn.helper
/bin/launchctl bootstrap system /Library/LaunchDaemons/app.revpn.helper.plist
exit 0
