#!/bin/zsh --no-rcs

################################################################################################################################
################################################################################################################################
#
# Script provided by DARE Technology Ltd to be used "as is".
# Copyright (c) 2026
# Support - www.zappl.co
#
################################################################################################################################
################################################################################################################################
#
# Parameter labels:
#
# Parameter 4 - Jamf Pro URL
# Parameter 5 - API Client ID
# Parameter 6 - API Client Secret
#
################################################################################################################################
################################################################################################################################
#
# ABOUT THIS SCRIPT:
# This script collects the main Zappl log located at /var/log/Zappl, as well as the last hour and last day of Zappl logs only filtered from the unified log, plus the last report JSON submitted.
# The resulting .zip file is uploaded to the attachment payload within the computer inventory record.
#
# REQUIREMENTS:
# 1. Zappl must be installed on the client
# 2. The Jamf Pro server must be defined in parameter 4
# 3. The API Client ID must be defined in parameter 5
# 4. The API Client Secret must be defined in parameter 6
#
################################################################################################################################
################################################################################################################################


###########################################################################################
################################## V A R I A B L E S ######################################
###########################################################################################

# Jamf Pro API credentials
jamfURL="${4%/}"    # strip any trailing slash
clientId="$5"
clientSecret="$6"

serialNumber=$(/usr/sbin/system_profiler SPHardwareDataType | /usr/bin/grep Serial | /usr/bin/awk '{print $NF}' )
timeStamp=$(/bin/date '+%Y-%m-%d-%H-%M-%S' )
logDir="/private/tmp/ZapplLogs-$timeStamp"

###########################################################################################
############################# A U T H E N T I C A T I O N #################################
###########################################################################################

# Generate an auth token
accessToken=$( /usr/bin/curl --silent --location --request POST "${jamfURL}/api/oauth/token" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "client_id=${clientId}" \
--data-urlencode "grant_type=client_credentials" \
--data-urlencode "client_secret=${clientSecret}" )

# Remove additional data from the initial response.
bearerToken=$(/usr/bin/plutil -extract access_token raw -o - - <<< "$accessToken")

if [[ -z "$bearerToken" ]]; then
	/bin/echo "Error: Could not obtain an API token from ${jamfURL}. Check the Jamf Pro URL, API Client ID and Secret."
	exit 1
fi

###########################################################################################
##################################### L O G I C ###########################################
###########################################################################################

## Copy the full Zappl log
/bin/mkdir "$logDir"
if [[ -e /var/log/Zappl.log ]];then
	/bin/cp /var/log/Zappl.log "$logDir"
else
	/bin/echo "Error: Zappl log not found"
	exit 1
fi

## Grab the last report JSON
/bin/mkdir "$logDir/Reports"
if [[ -e /Library/Application\ Support/DARE/Zappl/Run/lastReport.json ]];then
	/bin/cp /Library/Application\ Support/DARE/Zappl/Run/lastReport.json "$logDir/Reports"
else
	/bin/echo "Warning: Last report JSON not found"
fi

## Grab logs from the last 24 hours and the last hour
/usr/bin/log show --predicate 'subsystem BEGINSWITH "com.dare.zappl"' --info --debug --last 1h > /private/tmp/ZapplLastHour.log
/usr/bin/log show --predicate 'subsystem BEGINSWITH "com.dare.zappl"' --info --debug --last 1d > /private/tmp/ZapplLastDay.log
/bin/cp /private/tmp/ZapplLastHour.log "$logDir"
/bin/cp /private/tmp/ZapplLastDay.log "$logDir"

## Add log files to an archive
fileName="Zappl-Logs-$timeStamp.zip"
/usr/bin/zip -r "/private/tmp/$fileName" "$logDir"

## Using the Serial Number, pull the Computer ID by accessing the Inventory of General
## The general subset contains more than one <id> element (e.g. the site ID inside <site>),
## so stop at the first match, which is the computer's own ID.
computerID=$( /usr/bin/curl "${jamfURL}/JSSResource/computers/serialnumber/${serialNumber}/subset/general" \
--silent \
--request GET \
--header "Accept: text/xml" \
--header "Authorization: Bearer ${bearerToken}" | /usr/bin/xmllint --format - 2>/dev/null | /usr/bin/awk -F'>|<' '/<id>/{print $3; exit}' )

if [[ ! "$computerID" =~ ^[0-9]+$ ]]; then
	/bin/echo "Error: Could not determine the Jamf Pro computer ID for serial ${serialNumber} (got: '${computerID}'). Check the API Client has 'Read Computers' permission."
	/bin/rm -f "/private/tmp/$fileName" /private/tmp/ZapplLastHour.log /private/tmp/ZapplLastDay.log
	/bin/rm -rf "$logDir"
	exit 1
fi

## Upload Zappl logs
/usr/bin/curl --silent --show-error --fail -X POST -H "Authorization: Bearer ${bearerToken}" \
"${jamfURL}/JSSResource/fileuploads/computers/id/${computerID}" -F "name=@/private/tmp/${fileName}"
uploadResult=$?

## Cleanup
/bin/rm -f "/private/tmp/$fileName"
/bin/rm -f /private/tmp/ZapplLastHour.log
/bin/rm -f /private/tmp/ZapplLastDay.log
/bin/rm -rf "$logDir"

if [[ $uploadResult -ne 0 ]]; then
	/bin/echo "Error: Log upload to Jamf Pro failed (curl exit ${uploadResult})."
	exit 1
fi

/bin/echo "Zappl logs uploaded to computer ID ${computerID} as ${fileName}"
exit 0