#!/bin/zsh
# shellcheck shell=bash

if [ $UID -ne 0 ]; then
    echo "Please run this script as root (with sudo)"
    exit 1
fi


while [[ "$#" -gt 0 ]]; do
    case $1 in
        -s|--system) system=1 ;;
        *) echo "Unknown parameter passed: $1"; echo "Usage: $0 [-s; --system]" ;  exit 1 ;;
    esac
    shift
done


mytmpdir=$(mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir')

if [ -z "$system" ]
then
    echo "Skipping sysdiagnose"
else
    echo "Running sysdiagnose"
    sysdiagnose -v -b -u -n -f "$mytmpdir"
fi


echo "Getting tccd logs"
/usr/bin/log show --debug --predicate 'eventMessage contains[c] "tcc"' &> "$mytmpdir/tccd.log"

echo "Getting Cyberhaven logs in /var/log/io.cyberhaven.lightbeam"
cp -r /var/log/io.cyberhaven.lightbeam "$mytmpdir"

echo "Getting Cyberhaven logs in /Users/Shared/io.cyberhaven.lightbeam"
cp -r /Users/Shared/io.cyberhaven.lightbeam "$mytmpdir"

echo "Getting Cyberhaven data in /Library/Application\ Support/io.cyberhaven.lightbeam"
cp -r /Library/Application\ Support/io.cyberhaven.lightbeam "$mytmpdir"

echo "Getting applications list"
while IFS= read -r app_file_name
do
    echo "App: $app_file_name - Bundle ID: $(mdls -name kMDItemCFBundleIdentifier -r "$app_file_name")" >> "$mytmpdir/apps.log" 2>&1
done < <(system_profiler -detailLevel full SPApplicationsDataType | grep Location | awk -F  ":" '{print $2""}' | awk '{$1=$1};1')

echo "Getting MDM profiles and settings"
/usr/bin/profiles list -o stdout-xml  > "$mytmpdir/mdm-profiles.xml"
cp -r "/Library/Managed Preferences/" "$mytmpdir/managed-preferences"

unique_file_name="$(date +"%FT%H%M")-$(uuidgen)"

out_tmp_dir="/tmp"
out_file_name="$out_tmp_dir/cyberhaven-diagnosis-$unique_file_name.tgz"

echo "Creating archive $out_file_name"
tar -cjf "$out_file_name" -C "$mytmpdir" .
chmod a+r "$out_file_name"
echo "Wrote $out_file_name, please send it to the Cyberhaven team"
echo "Opening Finder at the archive location: $out_tmp_dir"
open "$out_tmp_dir"

