-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathBaseline.sh
executable file
·1907 lines (1660 loc) · 77 KB
/
Baseline.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/zsh --no-rcs
set -x
#dryRun=true
# Written by Trevor Sysock of Second Son Consulting
# @BigMacAdmin on the MacAdmins Slack
scriptVersion="2.2.1"
# MIT License
#
# Copyright (c) 2024 Second Son Consulting
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
########################################################################################################
########################################################################################################
##
## DEFINE INITIAL VARIABLES
##
########################################################################################################
########################################################################################################
if [ "${1}" = '--version' ]; then
echo "$(basename $0) by Second Son Consulting - v. $scriptVersion"
exit 0
fi
#################################
# Declare file/folder paths #
#################################
#Baseline files/folders
BaselineConfig="/Library/Managed Preferences/com.secondsonconsulting.baseline.plist"
BaselineDir="/usr/local/Baseline"
BaselineTempDir="$(mktemp -d /var/tmp/baselineTempDir.XXXXXXX)"
customConfigPlist="$BaselineDir/BaselineConfig.plist"
logFile="/var/log/Baseline.log"
reportFile="/var/log/Baseline-Report.txt"
BaselinePath="$BaselineDir/Baseline.sh"
BaselineScripts="$BaselineDir/Scripts"
BaselinePackages="$BaselineDir/Packages"
BaselineIcons="$BaselineDir/Icons"
BaselineLaunchDaemon="/Library/LaunchDaemons/com.secondsonconsulting.baseline.plist"
BaselineTempIconsDir=$(mktemp -d "${BaselineTempDir}/baselineTmpIcons.XXXX")
ScriptOutputLog="/var/log/Baseline-ScriptsOutput.log"
#Binaries
pBuddy="/usr/libexec/PlistBuddy"
dialogPath="/usr/local/bin/dialog"
dialogAppPath="/Library/Application Support/Dialog/Dialog.app"
installomatorPath="/usr/local/Installomator/Installomator.sh"
#Other stuff
dialogCommandFile=$(mktemp "${BaselineTempDir}/baselineDialog.XXXXXX")
dialogJsonFile=$(mktemp "${BaselineTempDir}/baselineJson.XXXX")
expectedDialogTeamID="PWA5E9TQ59"
defaultWaitForTimeout=300
# Path to the Jamf log file
jamfLogFile="/private/var/log/jamf.log"
chmod -R 655 "${BaselineTempDir}"
########################################################################################################
########################################################################################################
##
## DEFINE FUNCTIONS
##
########################################################################################################
########################################################################################################
#################################
# Logging and Housekeeping #
#################################
function check_root(){
# check we are running as root
if [[ $(id -u) -ne 0 ]]; then
echo "ERROR: This script must be run as root **EXITING**"
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
exit 1
fi
}
function make_directory(){
if [ ! -d "${1}" ]; then
debug_message "Folder does not exist. Making it: ${1}"
mkdir -p "${1}"
fi
}
#Used only for debugging. Gives feedback into standard out if verboseMode=1, also to $logFile if you set it
function debug_message(){
if [ "$verboseMode" = 1 ]; then
/bin/echo "DEBUG: $*"
fi
}
#Publish a message to the log (and also to the debug channel)
function log_message(){
echo "$(date): $*" | tee >( cat >> "$logFile" )
debug_message "$*"
}
function rotate_logs(){
touch "$logFile"
chmod 655 "$logFile"
if [ "$(wc -l < "$logFile" | xargs)" -ge 30000 ]; then
log_message "Rotating Logs"
mv "$logFile" "$logFile".old
touch "$logFile"
log_message "Logfile Rotated"
fi
}
#Report messages go to our report, but also pass through log_message (and thus, also to debug_message)
function report_message(){
/bin/echo "$@" >> "$reportFile"
log_message "$@"
}
# Initiate logging
function initiate_logging(){
if ! touch "$logFile" ; then
debug_message "ERROR: Logging fail. Cannot create log file"
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
exit 1
else
log_message "Baseline.sh initiated"
fi
}
#Only delete something if the variable has a value!
function rm_if_exists(){
if [ -n "${1}" ] && [ -e "${1}" ];then
/bin/rm -rf "${1}"
fi
}
function initiate_report(){
if ! touch "$reportFile" ; then
debug_message "ERROR: Reporting fail. Cannot create report file"
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
exit 1
else
rm_if_exists "$reportFile"
report_message "Report created: $(date)"
fi
}
#Define our script exit process. Usage: cleanup_and_exit 'exitcode' 'exit message'
function cleanup_and_exit(){
# Check if we are going to restart
check_restart_option
# Check if we are leaving the Baseline working directory or deleting
cleanupAfterUse=$($pBuddy -c "Print :CleanupAfterUse" "$BaselineConfig" 2> /dev/null)
if [[ $cleanupAfterUse == "false" ]]; then
cleanupBaselineDirectory="false"
else
cleanupBaselineDirectory="true"
fi
# Log message
report_message "$2"
report_message "Baseline exited with error code: $1"
# Delete the Baseline LaunchDaemon
# Doing this in a loop because I've seen edge cases where it failed unexpectedly and it is high impact.
while [ -e "$BaselineLaunchDaemon" ]; do
rm_if_exists "$BaselineLaunchDaemon"
sleep 1
done
kill "$caffeinatepid"
dialog_command "quit:"
rm_if_exists "${BaselineTempDir}"
if [ "$dryRun" != true ] && [ "$cleanupBaselineDirectory" = "true" ] ; then
rm_if_exists "$BaselineDir"
fi
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
exit "$1"
}
# This function doesn't always shut down, but I'm leaving the name in place for now at least.
# Usage: cleanup_and_exit 'exitcode' 'exit message'
function cleanup_and_restart(){
# Check if we are going to restart
check_restart_option
# Check if we are leaving the Baseline working directory or deleting
cleanupAfterUse=$($pBuddy -c "Print :CleanupAfterUse" "$BaselineConfig" 2> /dev/null )
if [ "$cleanupAfterUse" = "false" ]; then
cleanupBaselineDirectory="false"
else
cleanupBaselineDirectory="true"
fi
# Log message
report_message "$2"
# Delete the LaunchDaemon. Saw an edge case where it didn't delete once, so I made it a while loop.
while [ -e "$BaselineLaunchDaemon" ]; do
rm_if_exists "$BaselineLaunchDaemon"
sleep 1
done
# Kill our caffeinate command
kill "$caffeinatepid"
# Close dialog window
dialog_command "quit:"
# Check if we are deleting the Baseline working directory and do it
if [ $cleanupBaselineDirectory = "true" ]; then
rm_if_exists "$BaselineDir"
fi
# Determine exit configuration
# If ForceRestart is set to false, and dry run is off
if $forceRestart && ! $dryRun ; then
report_message "Force Restart is configured. Restarting"
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
log_message "Forcing restart"
shutdown -r now
# If Force Log Out is set to true, and dry run is off
elif $forceLogOut && ! $dryRun; then
report_message "Force Log Out is set to true."
osascript -e "tell application \"/System/Library/CoreServices/loginwindow.app\" to «event aevtrlgo»"
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
exit "$1"
elif ! $forceLogOut && ! $forceRestart && ! $dryRun; then
report_message "Force Log Out and Force Restart are false. Exiting with no action."
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
exit "$1"
# If the script is in DryRun mode
elif $dryRun; then
report_message "Dry Run Enabled, no exit action taken."
report_message "ForceRestart is set to: $forceRestart"
report_message "ForceLogOut is set to: $forceLogOut"
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
exit "$1"
fi
# Shutting down
log_message "Unknown ExitAction determined. Falling back on default to ForceRestart"
# Delete Baseline Temp Dir
rm_if_exists "${BaselineTempDir}"
shutdown -r now
}
function no_sleeping(){
/usr/bin/caffeinate -d -i -m -u &
caffeinatepid=$!
}
# execute a dialog command
function dialog_command(){
/bin/echo "$@" >> $dialogCommandFile
sleep .1
}
#This function is modified from the awesome one given to us via Adam Codega. Thanks Adam!
#https://github.com/acodega/dialog-scripts/blob/main/dialogCheckFunction.sh
function install_dialog(){
# Check for Dialog and install if not found. We'll try 10 times before exiting the script with a fail.
dialogInstallAttempts=0
while [ ! -e "$dialogAppPath" ] && [ "$dialogInstallAttempts" -lt 10 ]; do
# If SwiftDialog.pkg exists in the Packages folder check the TeamID is valid, and install it
localDialogTeamID=$(/usr/sbin/spctl -a -vv -t install "$BaselinePackages/SwiftDialog.pkg" 2>&1 | awk '/origin=/ {print $NF }' | tr -d '()')
if [ "$expectedDialogTeamID" = "$localDialogTeamID" ]; then
/usr/sbin/installer -pkg "$BaselinePackages/SwiftDialog.pkg" -target / > /dev/null 2>&1
# If Installomator is already here use that
elif [ -e "$installomatorPath" ]; then
"$installomatorPath" swiftdialog INSTALL=force NOTIFY=silent BLOCKING_PROCESS_ACTION=ignore > /dev/null 2>&1
dialogInstallAttempts=$((dialogInstallAttempts+1))
else
# Get the URL of the latest PKG From the Dialog GitHub repo
# Expected Team ID of the downloaded PKG
dialogURL=$(curl -L --silent --fail "https://api.github.com/repos/swiftDialog/swiftDialog/releases/latest" | awk -F '"' "/browser_download_url/ && /pkg\"/ { print \$4; exit }")
log_message "Dialog not found. Installing."
# Create temporary working directory
workDirectory=$( /usr/bin/basename "$0" )
tempDirectory=$( /usr/bin/mktemp -d "/private/tmp/$workDirectory.XXXXXX" )
# Download the installer package
/usr/bin/curl --location --silent "$dialogURL" -o "$tempDirectory/SwiftDialog.pkg"
# Verify the download
teamID=$(/usr/sbin/spctl -a -vv -t install "$tempDirectory/SwiftDialog.pkg" 2>&1 | awk '/origin=/ {print $NF }' | tr -d '()')
# Install the package if Team ID validates
if [ "$expectedDialogTeamID" = "$teamID" ]; then
/usr/sbin/installer -pkg "$tempDirectory/SwiftDialog.pkg" -target / > /dev/null 2>&1
fi
#If Dialog wasn't installed, wait 5 seconds and increase the attempt count
if [ ! -e "$dialogAppPath" ]; then
log_message "Dialog installation failed."
sleep 5
dialogInstallAttempts=$((dialogInstallAttempts+1))
fi
# Remove the temporary working directory when done
rm_if_exists "$tempDirectory"
fi
done
}
function install_installomator(){
# Check for Installomator and install if not found. We'll try 10 times before exiting the script with a fail.
installomatorInstallAttempts=0
while [ ! -e "$installomatorPath" ] && [ "$installomatorInstallAttempts" -lt 10 ]; do
# Check if there is a local Installomator.pkg, and if so run it.
if [ -e "${BaselinePackages}/Installomator.pkg" ]; then
/usr/sbin/installer -pkg "${BaselinePackages}/Installomator.pkg" -target / > /dev/null 2>&1
else
# Get the URL of the latest PKG From the Installomator GitHub repo
# Expected Team ID of the downloaded PKG
installomatorURL=$(curl --silent -L --fail "https://api.github.com/repos/Installomator/Installomator/releases/latest" | awk -F '"' "/browser_download_url/ && /pkg\"/ { print \$4; exit }")
expectedTeamID="JME5BW3F3R"
log_message "Installomator not found. Installing."
# Create temporary working directory
workDirectory=$( /usr/bin/basename "$0" )
tempDirectory=$( /usr/bin/mktemp -d "/private/tmp/$workDirectory.XXXXXX" )
# Download the installer package
/usr/bin/curl --location --silent "$installomatorURL" -o "$tempDirectory/Installomator.pkg"
# Verify the download
teamID=$(/usr/sbin/spctl -a -vv -t install "$tempDirectory/Installomator.pkg" 2>&1 | awk '/origin=/ {print $NF }' | tr -d '()')
# Install the package if Team ID validates
if [ "$expectedTeamID" = "$teamID" ]; then
/usr/sbin/installer -pkg "$tempDirectory/Installomator.pkg" -target / > /dev/null 2>&1
installomatorInstallExitCode=$?
fi
if [ ! -e "$installomatorPath" ]; then
log_message "Installomator installation failed."
sleep 5
installomatorInstallAttempts=$((installomatorInstallAttempts+1))
fi
# Remove the temporary working directory when done
rm_if_exists "$tempDirectory"
fi
done
}
#Checks if a user is logged in yet, and if not it waits and loops until we can confirm there is a real user
function wait_for_user(){
#Set our test to false
verifiedUser="false"
#Loop until user is found
while [ "$verifiedUser" = "false" ]; do
#Get currently logged in user
currentUser=$( echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }' )
#Verify the current user is not root, loginwindow, or _mbsetupuser
if [ "$currentUser" = "root" ] \
|| [ "$currentUser" = "loginwindow" ] \
|| [ "$currentUser" = "_mbsetupuser" ] \
|| [ -z "$currentUser" ]
then
#If we aren't verified yet, wait 1 second and try again
sleep 1
else
#Logged in user found, but continue the loop until Dock and Finder processes are running
if pgrep -q "dock" && pgrep -q "Finder"; then
uid=$(id -u "$currentUser")
log_message "Verified User is logged in: $currentUser UID: $uid"
verifiedUser="true"
fi
fi
debug_message "Disabling verbose output to prevent logspam while waiting for user at timestamp: $(date +%s)"
set +x
done
debug_message "Re-enabling verbose output after finding user at timestamp: $(date +%s)"
}
#Check for custom config. We prioritize this even over a mobileconfig file.
function check_for_custom_plist(){
if [ -e $customConfigPlist ] && ! $configFromArgument; then
BaselineConfig="$customConfigPlist"
fi
}
#Verify configuration file
function verify_configuration_file(){
#We need to make sure our configuration file is in place. By the time the user logs in, this should have happened.
debug_message "Verifying configuration file. Failure here probably means an MDM profile hasn't been properly scoped, or there's a problem with the MDM delivering the profile."
#Set timeout variables
configFileTimeout=600
configFileWaiting=0
# Look for a custom plist
check_for_custom_plist
# While the plist or configuration file doesn't exist, wait and timeout at 10 minutes if never found.
while [ ! -e $BaselineConfig ]; do
check_for_custom_plist
#wait 2 seconds
sleep 2
debug_message "Configuration file not found"
configFileWaiting=$((configFileWaiting+2))
if [ $configFileWaiting -gt $configFileTimeout ]; then
cleanup_and_exit 1 "ERROR: Configuration file not found within $configFileTimeout seconds. Exiting."
fi
done
debug_message "Configuration file found successfully: $BaselineConfig "
# If we're working off an MDM configuration profile, copy it to our temp location and go off the copy.
# Have seen edge cases where an MDM removes or re-applies profiles, this will prevent that from causing issues.
if [[ "$BaselineConfig" == "/Library/Managed Preferences/com.secondsonconsulting.baseline.plist" ]]; then
cp "$BaselineConfig" "$BaselineTempDir/BaselineConfig.plist"
BaselineConfig="$BaselineTempDir/BaselineConfig.plist"
fi
}
function build_installomator_array(){
#Set an index internal to this function
index=0
#Loop through and test if there is a value in the slot of this index for the given array
#If this command fails it means we've reached the end of the array in the config file and we exit our loop
while $pBuddy -c "Print :Installomator:${index}" "$BaselineConfig" > /dev/null 2>&1; do
#Get the Display Name of the current item
currentDisplayName=$($pBuddy -c "Print :Installomator:${index}:DisplayName" "$BaselineConfig")
dialogList+="$currentDisplayName"
#Done looping. Increase our array value and loop again.
index=$((index+1))
done
}
function process_installomator_labels(){
#Set an index internal to this function
currentIndex=0
#Loop through and test if there is a value in the slot of this index for the given array
#If this command fails it means we've reached the end of the array in the config file (or there are none) and we exit our loop
while $pBuddy -c "Print :Installomator:${currentIndex}" "$BaselineConfig" > /dev/null 2>&1; do
check_for_bail_out
if [ ! -e "$installomatorPath" ]; then
cleanup_and_exit 1 "ERROR: Installomator failed to install after numerous attempts. Exiting."
fi
#Set the current label name
currentLabel=$($pBuddy -c "Print :Installomator:${currentIndex}:Label" "$BaselineConfig")
#Check if there are Options defined, and set the variable accordingly
if $pBuddy -c "Print :Installomator:${currentIndex}:Arguments" "$BaselineConfig" > /dev/null 2>&1; then
#This label has options defined
currentArguments=$($pBuddy -c "Print :Installomator:${currentIndex}:Arguments" "$BaselineConfig")
else
#This label does not have options defined
currentArguments=""
fi
#Now we have to do a trick in case there are multiple arguments, some of which are quoted together
#Consider: /path/to/script.sh --font "Times New Roman"
#Used the eval trick outlined here: https://superuser.com/questions/1066455/how-to-split-a-string-with-quotes-like-command-arguments-in-bash
currentArgumentArray=()
if [ -n "$currentArguments" ]; then
eval 'for argument in '$currentArguments'; do currentArgumentArray+=$argument; done'
fi
#Get the display name of the label we're installing. We need this to update the dialog list
currentDisplayName=$($pBuddy -c "Print :Installomator:${currentIndex}:DisplayName" "$BaselineConfig")
# Configure Installomator SwiftDialog Integration
useInstallomatorSwiftDialogIntegration=$($pBuddy -c "Print :InstallomatorSwiftDialogIntegration" "$BaselineConfig" 2> /dev/null)
# If we're using the integrated SwiftDialog, then
if [[ $useInstallomatorSwiftDialogIntegration == "true" ]]; then
currentArgumentArray+="DIALOG_CMD_FILE=\"$dialogCommandFile\""
currentArgumentArray+=DIALOG_LIST_ITEM_NAME=\"$currentDisplayName\"
else
#Update the dialog window so that this item shows as "pending"
dialog_command "listitem: title: $currentDisplayName, status: wait"
fi
set_progressbar_text "$currentDisplayName"
#Call installomator with our desired options. Default options first, so that they can be overriden by "currentArguments"
$installomatorPath $currentLabel ${defaultInstallomatorOptions[@]} ${currentArgumentArray[@]} > /dev/null 2>&1
installomatorExitCode=$?
if [ $installomatorExitCode != 0 ]; then
report_message "Failed Item - Installomator: $currentLabel - Exit Code: $installomatorExitCode"
failList+=("$currentDisplayName")
# If we're NOT using the integrated SwiftDialog, then
if [[ $useInstallomatorSwiftDialogIntegration != "true" ]]; then
dialog_command "listitem: title: $currentDisplayName, status: fail"
fi
else
report_message "Successful Item - Installomator: $currentLabel"
successList+=("$currentDisplayName")
if [[ $useInstallomatorSwiftDialogIntegration != "true" ]]; then
dialog_command "listitem: title: $currentDisplayName, status: success"
fi
fi
update_tracker "$currentDisplayName" $installomatorExitCode
currentIndex=$((currentIndex+1))
# This gets set for use with the BailOut feature
previousDisplayName="$currentDisplayName"
check_for_bail_out
increment_progress_bar
done
}
# Our main list builder for the Dialog window
function build_dialog_array(){
## Usage: Build the dialog array for the given profile configuration key. $1 is the name of the key
## Example: build_dialog_array Scripts | InitialScripts | Packages | Installomator
# Set the MDM key to the given argument
configKey="${1}"
#Set an index internal to this function
index=0
#Loop through and test if there is a value in the slot of this index for the given array
#If this command fails it means we've reached the end of the array in the config file and we exit our loop
while $pBuddy -c "Print :$configKey:${index}" "$BaselineConfig" > /dev/null 2>&1; do
#Get the Display Name of the current item
currentDisplayName=$($pBuddy -c "Print :$configKey:${index}:DisplayName" "$BaselineConfig")
dialogList+="$currentDisplayName"
#Get the icon path if populated in the configuration profile
if $pBuddy -c "Print :$configKey:${index}:Icon" "$BaselineConfig" > /dev/null 2>&1; then
currentIconPath=$($pBuddy -c "Print :$configKey:${index}:Icon" "$BaselineConfig")
# Check if Icon is remotely hosted URL
if [[ ${currentIconPath:0:4} == "http" ]]; then
log_message "Icon set to URL: $currentIconPath"
# Check if Icon is an SF Symbol
elif [[ ${currentIconPath:0:3} == 'SF=' ]]; then
log_message "Icon set to SF Symbol: $currentIconPath"
#Check of the given icon path exists on disk
elif [ -e "$currentIconPath" ]; then
log_message "Icon found: $currentIconPath"
elif [ -e "$BaselineTempIconsDir/$currentIconPath" ]; then
log_message "Icon found: $currentIconPath"
currentIconPath="$BaselineTempIconsDir/$currentIconPath"
chmod 655 "${currentIconPath}"
else
#If we can't find the local file, report and leave blank
log_message "ERROR: Icon key cannot be located: $currentIconPath"
currentIconPath=""
fi
else
#If no icon key is set, ensure it's blank
currentIconPath=""
fi
#Get the desired subtitle if populated in the configuration profile
if $pBuddy -c "Print :$configKey:${index}:Subtitle" "$BaselineConfig" > /dev/null 2>&1; then
currentSubtitle=$($pBuddy -c "Print :$configKey:${index}:Subtitle" "$BaselineConfig")
else
#If no icon key is set, ensure it's blank
currentSubtitle=""
fi
#Generate JSON entry for item
#NOTE: We will strip out the final comma later to ensure a valid JSON
dialogListJson+="{\"title\" : \"$currentDisplayName\",\"subtitle\" : \"$currentSubtitle\", \"icon\" : \"$currentIconPath\", \"status\" : \"\"},"
#Done looping. Increase our array value and loop again.
index=$((index+1))
progressBarTotal=$((progressBarTotal+1))
done
}
function process_scripts(){
# Usage: process_scripts ProfileKey
# Actual use: process_scripts [ InitialScripts | Scripts ]
#Set an index internal to this function
currentIndex=0
#Loop through and test if there is a value in the slot of this index for the given array
#If this command fails it means we've reached the end of the array in the config file (or there are none) and we exit our loop
while $pBuddy -c "Print :${1}:${currentIndex}" "$BaselineConfig" > /dev/null 2>&1; do
check_for_bail_out
#Unset variables for next loop
unset useVerboseJamf
unset jamfVerbosePID
unset expectedMD5
unset actualMD5
unset currentArguments
unset currentArgumentArray
unset currentScript
unset currentScriptPath
unset currentDisplayName
unset scriptDownloadExitCode
#Get the display name of the label we're installing. We need this to update the dialog list
currentDisplayName=$($pBuddy -c "Print :${1}:${currentIndex}:DisplayName" "$BaselineConfig")
#Set the current script name
currentScriptPath=$($pBuddy -c "Print :${1}:${currentIndex}:ScriptPath" "$BaselineConfig")
#Check if the defined script is a remote path
if [[ ${currentScriptPath:0:4} == "http" ]]; then
#Set variable to the base file name to be downloaded
currentScript="$BaselineScripts/"$(basename "$currentScriptPath")
#Download the remote script, and put it in the Baseline Scripts directory
curl -s --fail-with-body "${currentScriptPath}" -o "$currentScript"
#Capture the exit code of our curl command
scriptDownloadExitCode=$?
#Check if curl exited cleanly
if [ "$scriptDownloadExitCode" != 0 ];then
#Report a failed download
report_message "Failed Item - Script download error: $currentScriptPath"
#Rm the output of our curl command. This will result in it being processed as a failure
rm_if_exists "$currentScript"
else
log_message "Script downloaded successfully: $currentScriptPath"
#Make our downloaded script executable
chmod +x "$currentScript"
fi
#Check if the given script exists on disk
elif [ -e "$currentScriptPath" ]; then
# The path to the script is a local file path which exists
currentScript="$currentScriptPath"
elif [ -e "$BaselineScripts/$currentScriptPath" ]; then
currentScript="$BaselineScripts/$currentScriptPath"
fi
#If the currentScript variable still isn't set to an existing file we need to bail..
if [ ! -e "$currentScript" ]; then
report_message "Failed Item - Script does not exist: $currentScript"
# Iterate the index up one
currentIndex=$((currentIndex+1))
increment_progress_bar
# Report the fail
dialog_command "listitem: title: $currentDisplayName, status: fail"
failList+=("$currentDisplayName")
update_tracker $currentDisplayName 99
# Bail this pass through the while loop and continue processing next item
continue
fi
#Check if this is a Jamf binary call and if we're using verbose jamf output
if [[ ${currentScriptPath} == "/usr/local/bin/jamf" ]] && $showVerboseJamf ; then
jamf_verbose_dialog "$currentDisplayName" & jamfVerbosePID=$!
fi
#Check for MD5 validation
if $pBuddy -c "Print :${1}:${currentIndex}:MD5" "$BaselineConfig" > /dev/null 2>&1; then
#This script has MD5 validation provided
#Read the expected MD5 value from the profile
expectedMD5=$($pBuddy -c "Print :${1}:${currentIndex}:MD5" "$BaselineConfig")
#Calculate the actual MD5 of the script
actualMD5=$(md5 -q "$currentScript")
#Evaluate whether the expected and actual MD5 do not match
if [ "$actualMD5" != "$expectedMD5" ]; then
report_message "Failed Item - Script MD5 error: $currentScriptPath - Expected $expectedMD5 - Actual $actualMD5"
# Iterate the index up one
currentIndex=$((currentIndex+1))
# Only increment the progress bar if we're processing Scripts, not InitialScripts since users won't see those
if [ "$1" = "Scripts" ]; then
increment_progress_bar
fi
# Report the fail
dialog_command "listitem: title: $currentDisplayName, status: fail"
failList+=("$currentDisplayName")
# Bail this pass through the while loop and continue processing next item
continue
fi
fi
#Check if there are Arguments defined, and set the variable accordingly
if $pBuddy -c "Print :${1}:${currentIndex}:Arguments" "$BaselineConfig" > /dev/null 2>&1; then
#This script has arguments defined
currentArguments=$($pBuddy -c "Print :${1}:${currentIndex}:Arguments" "$BaselineConfig")
else
#This script does not have arguments defined
currentArguments=""
fi
#Now we have to do a trick in case there are multiple arguments, some of which are quoted together
#Consider: /path/to/script.sh --font "Times New Roman"
#Used the eval trick outlined here: https://superuser.com/questions/1066455/how-to-split-a-string-with-quotes-like-command-arguments-in-bash
currentArgumentArray=()
if [ -n "$currentArguments" ]; then
eval 'for argument in '$currentArguments'; do currentArgumentArray+=$argument; done'
fi
#Update the dialog window so that this item shows as "pending"
dialog_command "listitem: title: $currentDisplayName, status: wait"
#Only set the progress label if we're processing Scripts, not InitialScripts since users won't see those
if [ "$1" = "Scripts" ]; then
set_progressbar_text "$currentDisplayName"
fi
#Call our script with our desired options. Default options first, so that they can be overriden by "currentArguments"
"$currentScript" ${currentArgumentArray[@]} >> "$ScriptOutputLog" 2>&1
scriptExitCode=$?
if [ $scriptExitCode != 0 ]; then
report_message "Failed Item - Script runtime error: $currentScript - Exit Code: $scriptExitCode"
dialog_command "listitem: title: $currentDisplayName, status: fail"
failList+=("$currentDisplayName")
else
report_message "Successful Item - Script: $currentScript"
dialog_command "listitem: title: $currentDisplayName, status: success"
successList+=("$currentDisplayName")
fi
update_tracker $currentDisplayName $scriptExitCode
#Iterate index for next loop
currentIndex=$((currentIndex+1))
# This gets set for use with the BailOut feature
previousDisplayName="$currentDisplayName"
#Stuff in this section only happens if we're processing Scripts and not InitialScripts
if [ "$1" = "Scripts" ]; then
increment_progress_bar
#If we're using jamf, and jamf verbose is configured
if [[ ${currentScriptPath} == "/usr/local/bin/jamf" ]] && $showVerboseJamf; then
# If the PID is still running, kill it
if ps -x "$jamfVerbosePID" > /dev/null 2>&1; then
kill "$jamfVerbosePID"
fi
# Now clear the jamf verbose status text
dialog_command "listitem: title: ${currentDisplayName}, statustext: "
fi
fi
done
}
function process_pkgs(){
#Set an index internal to this function
currentIndex=0
#Loop through and test if there is a value in the slot of this index for the given array
#If this command fails it means we've reached the end of the array in the config file (or there are none) and we exit our loop
while $pBuddy -c "Print :Packages:${currentIndex}" "$BaselineConfig" > /dev/null 2>&1; do
check_for_bail_out
# Unset variables for next loop
unset currentPKG
unset currentPKGPath
unset expectedTeamID
unset expectedMD5
unset actualTeamID
unset actualMD5
unset currentArguments
unset currentArgumentArray
unset currentDisplayName
unset pkgBasename
unset downloadResult
#Get the display name of the label we're installing. We need this to update the dialog list
currentDisplayName=$($pBuddy -c "Print :Packages:${currentIndex}:DisplayName" "$BaselineConfig")
#Set the current package path
currentPKGPath=$($pBuddy -c "Print :Packages:${currentIndex}:PackagePath" "$BaselineConfig")
##Here is where we begin checking what kind of PKG was defined, and how to process it
##The end result of this chunk of code, is that we have a valid path to a PKG on the file system
##Else we bail and continue looping to install the next item
#Check if the package path is a web URL
if [[ ${currentPKGPath:0:4} == "http" ]]; then
# The path to the PKG appears to be a URL.
#Get the basename of the .pkg we're downloading
pkgBasename=$(basename "$currentPKGPath")
#Set the "currentPKG" variable, this gets used as the download path as well as processed later
currentPKG="$BaselinePackages"/"$pkgBasename"
#Check for conflict. If there's already a PKG in the directory we're downloading to, delete it
rm_if_exists "$currentPKG"
#Perform the download of the remote pkg
curl -LJs "$currentPKGPath" -o "$currentPKG"
#Capture the output of our curl command
downloadResult=$?
#Verify curl exited with 0
if [ "$downloadResult" != 0 ]; then
report_message "Failed Item - Package download error: $currentPKGPath"
# Iterate the index up one
currentIndex=$((currentIndex+1))
increment_progress_bar
# Report the fail
dialog_command "listitem: title: $currentDisplayName, status: fail"
# Bail this pass through the while loop and continue processing next item
continue
else
debug_message "PKG downloaded successfully: $currentPKGPath"
fi
fi
# Check if the pkg exists
if [ -e "$currentPKG" ]; then
debug_message "PKG found: $currentPKG"
elif [ -e "$currentPKGPath" ]; then
# The path to the PKG appears to exist on the local file system
currentPKG="$currentPKGPath"
elif [ -e "$BaselinePackages/$currentPKGPath" ]; then
# The path to the PKG appears to exist within Baseline directory
currentPKG="$BaselinePackages/$currentPKGPath"
else
report_message "Failed Item - Package does not exist: $currentPKGPath"
dialog_command "listitem: title: $currentDisplayName, status: fail"
failList+=("$currentDisplayName")
currentIndex=$((currentIndex+1))
increment_progress_bar
update_tracker $currentDisplayName 99
continue
fi
##At this point, the pkg exists on the file system, or we've bailed on this loop.
#Check if there are Arguments defined, and set the variable accordingly
if $pBuddy -c "Print :Packages:${currentIndex}:Arguments" "$BaselineConfig" > /dev/null 2>&1; then
#This pkg has arguments defined
currentArguments=$($pBuddy -c "Print :Packages:${currentIndex}:Arguments" "$BaselineConfig")
else
#This pkg does not have arguments defined
currentArguments=""
fi
#Now we have to do a trick in case there are multiple arguments, some of which are quoted together
#Consider: /path/to/script.sh --font "Times New Roman"
#Used the eval trick outlined here: https://superuser.com/questions/1066455/how-to-split-a-string-with-quotes-like-command-arguments-in-bash
currentArgumentArray=()
eval 'for argument in '$currentArguments'; do currentArgumentArray+=$argument; done'
if $pBuddy -c "Print :Packages:${currentIndex}:TeamID" "$BaselineConfig" > /dev/null 2>&1; then
#This pkg has TeamID defined
expectedTeamID=$($pBuddy -c "Print :Packages:${currentIndex}:TeamID" "$BaselineConfig")
else
#This pkg does not have TeamID Validation defined
expectedTeamID=""
fi
if $pBuddy -c "Print :Packages:${currentIndex}:MD5" "$BaselineConfig" > /dev/null 2>&1; then
#This script has MD5 defined
expectedMD5=$($pBuddy -c "Print :Packages:${currentIndex}:MD5" "$BaselineConfig")
else
#This script does not have MD5 defined
expectedMD5=""
fi
#Update the dialog window so that this item shows as "pending"
dialog_command "listitem: title: $currentDisplayName, status: wait"
set_progressbar_text "$currentDisplayName"
## Package validation happens here
# Check TeamID, if a value has been provided
if [ -n "$expectedTeamID" ]; then
#Get the TeamID for the current PKG
actualTeamID=$(spctl -a -vv -t install "$currentPKG" 2>&1 | awk -F '(' '/origin=/ {print $2 }' | tr -d ')' )
# Check if actual does not match expected
if [ "$expectedTeamID" != "$actualTeamID" ]; then
report_message "Failed Item - Package TeamID error: $currentPKG - Expected - $expectedTeamID Actual - $actualTeamID"
dialog_command "listitem: title: $currentDisplayName, status: fail"
failList+=("$currentDisplayName")
# Iterate the index up one
currentIndex=$((currentIndex+1))
increment_progress_bar
# Report the fail
dialog_command "listitem: title: $currentDisplayName, status: fail"
# Bail this pass through the while loop and continue processing next item
continue
else
log_message "TeamID of PKG validated: $currentPKG $expectedTeamID"
fi
fi
# Check MD5, if a value has been provided
if [ -n "$expectedMD5" ]; then
#Get MD5 for the current PKG
actualMD5=$(md5 -q "$currentPKG")
# Check if actual does not match expected
if [ "$expectedMD5" != "$actualMD5" ]; then
report_message "Failed Item - Package MD5 error: $currentPKG - Expected - $expectedMD5 Actual - $actualMD5"
dialog_command "listitem: title: $currentDisplayName, status: fail"
failList+=("$currentDisplayName")
# Iterate the index up one
currentIndex=$((currentIndex+1))
increment_progress_bar
# Report the fail
dialog_command "listitem: title: $currentDisplayName, status: fail"
update_tracker $currentDisplayName 99
# Bail this pass through the while loop and continue processing next item
continue
else
log_message "MD5 of PKG validated: $currentPKG $expectedMD5"
fi
fi
## The package installation happens here. We do this in a variable so we can capture the output and report it for debugging
pkgInstallerOutput=$(installer -allowUntrusted -pkg "$currentPKG" -target / ${currentArgumentArray[@]} )
# Capture the installer exit code
pkgExitCode=$?
# Verify the install completed successfully
if [ $pkgExitCode != 0 ]; then
report_message "Failed Item - Package installation error: $currentPKG - Exit Code: $pkgExitCode"
dialog_command "listitem: title: $currentDisplayName, status: fail"
failList+=("$currentDisplayName")
else
report_message "Successful Item - Package: $currentPKG"
dialog_command "listitem: title: $currentDisplayName, status: success"
successList+=("$currentDisplayName")
fi
update_tracker $currentDisplayName $pkgExitCode
debug_message "Output of the install package command: $pkgInstallerOutput"
# Iterate to the next index item, and continue our loop
currentIndex=$((currentIndex+1))
increment_progress_bar
# This gets set for use with the BailOut feature
previousDisplayName="$currentDisplayName"
check_for_bail_out
done
}
function copy_icons_dir(){
if [ -d "${BaselineIcons}" ]; then
cp -r "${BaselineIcons}/"* "${BaselineTempIconsDir}/"
chmod -R 655 "${BaselineTempIconsDir}"
fi
}
function build_dialog_json_file(){
# Initiate Json file
/bin/echo "{\"listitem\" : [" >> $dialogJsonFile
# For each item in our list, add the Json line
for jsonItem in $dialogListJson; do
/bin/echo "$jsonItem" >> $dialogJsonFile
done
# This trick removes the final character from the file, to ensure a valid Json
cat "$dialogJsonFile" | sed '$ s/.$//' > "${BaselineTempDir}/tempJson1"
mv "${BaselineTempDir}/tempJson1" "$dialogJsonFile"
# Finish Json file
/bin/echo "]}" >> "$dialogJsonFile"
# Set global read permissions for Json file
chmod 644 "$dialogJsonFile"
}
function build_dialog_list_options(){
# This function populates an array with all of the items Baseline iterates through
for i in $dialogList; do
dialogListItems+=(--listitem $i)
done
}
function check_exit_condition(){
exitConditionPath=""
# If `ExitCondition` key is passed in the configuration profile, then set a variable
if $pBuddy -c "Print :ExitCondition" "$BaselineConfig" > /dev/null 2>&1; then
exitConditionPath=$($pBuddy -c "Print :ExitCondition" "$BaselineConfig" | sed 's/"//g' )
fi
# If our variable is set, and if the file exists, cleanup and exit quietly
if [ -n "$exitConditionPath" ] && [ -e "$exitConditionPath" ]; then
cleanup_and_exit 0 "Exit Condition exists. Exiting: "$exitConditionPath""
fi
}
function check_bail_out_configuration(){
# If BailOutFile key has a value, set it for the filepath we'll check
if $pBuddy -c "Print :BailOutFile" "$BaselineConfig" > /dev/null 2>&1; then
bailOutFilePath=$($pBuddy -c "Print :BailOutFile" "$BaselineConfig")
else
bailOutFilePath=""
fi
}
function check_for_bail_out(){
# If our BailOutFilePath has a value
if [ ! -z $bailOutFilePath ]; then
# Check if the file exists
if [ -f "$bailOutFilePath" ]; then
# Add the previousDisplayName to our failure list
failList+=("$previousDisplayName")
# Delete the bail out file
rm_if_exists "$bailOutFilePath"
#Close our running dialog window
dialog_command "quit:"
# Do the Failure window
present_failure_window
# Exit with code 99
cleanup_and_restart 99 "Bail out file identified: $bailOutFilePath"
fi
fi
}
function check_restart_option(){
restartSetting=$($pBuddy -c "Print :Restart" "$BaselineConfig" 2> /dev/null )
logOutSetting=$($pBuddy -c "Print :LogOut" "$BaselineConfig" 2> /dev/null )
if [ -z $logOutSetting ]; then
log_message "No LogOut key in configuration file"