#!/usr/bin/env bash
# https://forums.macrumors.com/threads/ard-agent-leaks-memory.2223720/
prefix='/Users/macuser/logs/'
logfile="${prefix}ARDreload.log"
# keeps the last 40 entries in the log file
tail -40 "${logfile}" > "${logfile}.new"
mv -f "${logfile}.new" "${logfile}"
echo -n "$( date ) : " >> "${logfile}"
# https://keithmfoster.com/restarting-the-apple-remote-desktop-ard-via-ssh/
# https://ss64.com/mac/kickstart.html
# if 'Remote Desktop' is running and you restart ARDAgent, 'Remote Desktop' will crash
# thus, this test
# additionally, don't have 'Remote Desktop' running when not actively using it
if [[ $( ps aux | grep 'Remote Desktop.app' | grep -v grep | wc -l ) -gt 0 ]]
then
    echo 'Remote Desktop.app active' >> "${logfile}"
else
    ARDAgent='/System/Library/CoreServices/RemoteManagement/ARDAgent.app'
    ${ARDAgent}/Contents/Resources/kickstart \
        -stop -agent
    sleep 5
    # '-users' & '-allowAccessFor' needs to be modified according to your setup
    ${ARDAgent}/Contents/Resources/kickstart \
        -activate \
        -restart -agent \
        -configure \
            -users macuser \
            -access -on \
            -privs -all \
            -allowAccessFor -specifiedUsers
    echo $( ps aux | grep ARDA | grep -v grep | awk '{print $2,$9}' ) >> "${logfile}"
fi