-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathpatchomator.sh
executable file
·1298 lines (966 loc) · 35.7 KB
/
patchomator.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
# Version: 2024.02.29 - 1.1.1
# "Leap Day"
# Gigantic Thanks to:
# rondelltron
# Big Thanks to:
# Adam Codega
# @tlark
# @mickl089
# Shad Hass
# Derek McKenzie
# Armin Briegel
# Jordy Thery
# Trevor Sysock
# Michael Zukrow
# Sjur Lohne
# Max Roy
# To Fix:
# Only search for apps in /Applications by default, optionally --everywhere
# Passing installomator options with spaces in.
# To Do:
# Add MDM optimized Non-interactive Mode --mdm "MDMName"
# apps installed in other weird locations should be identifiable by their pkg receipt.
# Recent Changes/Fixes:
# Automatically ignore labels that conflict with required ones
# Swift Dialog support
# labels with dashes. Seriously.
# Added logging to /var/log/Patchomator.log
# Interactive mode overhaul, automatically adding skipped labels as ignored
# 1.1 Ignored labels from CLI added into preferences on --write
# [speed] --skip-verify to skip the step of verifying discovered apps. Does *not* skip the verification on install.
# [speed] Defer verification step until discovery is complete. Parallelize as much as possible.
# Offers to install Installomator update, but requires user intervention.
# On --write, add any found label to the config, even if the latest version is installed
# Messaging for missing config file on --write
# Respects --installomatoroptions setting for ignoring App Store apps (or not)
# Older:
# Add --ignored "all" option to skip discovery all together
# Add --installomatoroptions to pass options to installomator
# Turn off pretty printed formatting for --quiet
# Monterey fix for working path
# Major overhaul based on MacAdmins #patchomator feedback
# 7 days -> 30 days
# Added required/excluded keys in preference file
# system-level config file for running via sudo, or deploying via MDM
# git and Xcode tools are optional now. Did you know GitHub has a pretty decent API?
# No longer requires root for normal operation. (thanks, @tlark)
# Downloads XCode Command Line Tools to provide git (Thanks Adam Codega)
# Install package/github release
# add back installomator install steps
# use release version of installomator, not dev. (Thanks Adam Codega)
# selfupdate when labels are older than 7 days
# parse label name, expectedTeamID, packageID
# match to codesign -dvvv of *.app
# packageID to Identifier
# expectedTeamID to TeamIdentifier
# added quiet mode, noninteractive mode
# choose between labels that install the same app (firefox, etc)
# - offer user selection
# - pick the first match (noninteractive mode)
# on duplicate labels, skip subsequent verification
# on -I, parse generated config, pipe to Installomator to install updates
# Installomator requires root
# NGD:
# self-update switch branches from release to latest source
if [ -z "${ZSH_VERSION}" ]; then
>&2 echo "[ERROR] This script is only compatible with Z shell (/bin/zsh). Re-run with"
echo "\t zsh patchomator.sh"
exit 1
fi
# Environment checks
OSVERSION=$(defaults read /System/Library/CoreServices/SystemVersion ProductVersion | awk '{print $1}')
OSMAJOR=$(echo "${OSVERSION}" | cut -d . -f1)
OSMINOR=$(echo "${OSVERSION}" | cut -d . -f2)
if [[ $OSMAJOR -lt 11 ]] && [[ $OSMINOR -lt 13 ]]
then
echo "[ERROR] Patchomator requires MacOS 10.13 or higher."
exit 1
fi
# Check your privilege
if [ $(whoami) = "root" ]
then
IAMROOT=true
else
IAMROOT=false
fi
# log levels from Installomator/fragments/arguments.sh
if [[ $DEBUG -ne 0 ]]; then
LOGGING=DEBUG
elif [[ -z $LOGGING ]]; then
LOGGING=INFO
datadogLoggingLevel=INFO
fi
logPATH="/private/var/log/Patchomator.log"
declare -A levels=(DEBUG 0 INFO 1 WARN 2 ERROR 3 REQ 4)
declare -A configArray=()
declare -A InstallomatorOptions=()
declare -A foundLabelsArray=()
declare -A ignoredLabelsArray=()
declare -A requiredLabelsArray=()
# default paths
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
InstallomatorPATH=("/usr/local/Installomator/Installomator.sh")
configfile=("/Library/Application Support/Patchomator/patchomator.plist")
managedConfigfile=("/Library/Managed Preferences/com.mac-nerd.patchomator.plist")
#patchomatorPath=$(dirname $(realpath $0)) # default install at /usr/local/Installomator/
# "realpath" doesn't exist on Monterey.
patchomatorPath="/usr/local/Installomator/"
fragmentsPATH=("$patchomatorPath/fragments")
# Pretty print, ignored if no terminal (eg, running via MDM)
BOLD=$(tput bold 2>/dev/null)
RESET=$(tput sgr0 2>/dev/null)
RED=$(tput setaf 1 2>/dev/null)
YELLOW=$(tput setaf 3 2>/dev/null)
skipDiscovery=false
#######################################
# Functions
usage() {
echo "\n${BOLD}Usage:${RESET}"
echo "\tpatchomator.sh [ -ryqvIh -c configfile -p InstallomatorPATH ]\n"
echo "${BOLD}Default:${RESET}"
echo "\tScans the system for installed apps and matches them to Installomator labels."
echo "\t${BOLD}--ignored \"space-separated list of labels to ignore\""
echo "\t${BOLD}--required \"space-separated list of labels to require\""
echo "\t${BOLD}-w | --write \t${RESET} Write Config. Creates a new config file or refreshes an existing one."
echo "\t${BOLD}-r | --read \t${RESET} Read Config. Parses and displays an existing config file. \n\tDefault path ${YELLOW}/Library/Application Support/Patchomator/patchomator.plist${RESET}"
echo "\t${BOLD}-c | --config \"path to config file\" \t${RESET} Overrides default configuration file location."
echo "\t${BOLD}--everywhere\t${RESET} Search the entire filesystem for matching apps."
echo "\t${BOLD}-y | --yes \t${RESET} Non-interactive mode. Accepts the default (usually nondestructive) choice at each prompt. Use with caution."
echo "\t${BOLD}-q | --quiet \t${RESET} Quiet mode. Minimal output."
echo "\t${BOLD}-v | --verbose \t${RESET} Verbose mode. Logs more information to stdout. Overrides ${BOLD}--quiet${RESET}"
echo "\t${BOLD}-s | --skipverify \t${RESET} Skips the signature verification step for discovered apps. ${BOLD}Does not skip verifying on installation.${RESET}"
echo "\t${BOLD}-I | --install \t${RESET} Install mode. This parses an existing configuration and sends the commands to Installomator to update. ${BOLD}Requires sudo${RESET}"
echo "\t${BOLD}-p | --pathtoinstallomator \"path to Installomator.sh\"${RESET}\n\tDefault Installomator Path ${YELLOW}/usr/local/Installomator/Installomator.sh${RESET}"
echo "\t${BOLD}--options \"option1=value option2=value ...\"${RESET}\n\tCommand line options passed through to Installomator.${RESET}"
echo "\t${BOLD}-h | --help \t${RESET} Show this text and exit.\n"
echo "${YELLOW}See readme for more options and examples: ${BOLD}https://github.com/mac-nerd/Patchomator${RESET}"
exit 0
}
caffexit () {
kill "$caffeinatepid"
echo "quit:" >> /var/tmp/dialog.log
exit $1
}
makepath() { # creates the full path to a file, but not the file itself
mkdir -p "$(sed 's/\(.*\)\/.*/\1/' <<< $1)" # && touch $1
}
notice() { # verbose mode
if [[ ${#verbose} -eq 1 ]]; then
echo "${YELLOW}[NOTICE]${RESET} $1" | tee -a "$logPATH"
fi
}
infoOut() { # normal messages
if ! [[ ${#quietmode} -eq 1 ]]; then
echo "$1" | tee -a "$logPATH"
echo "progresstext: $1" >> /var/tmp/dialog.log
fi
}
error() { # bad, but recoverable
echo "${BOLD}[ERROR]${RESET} $1" | tee -a "$logPATH"
let errorCount++
}
fatal() { # something bad happened.
echo "\n${BOLD}${RED}[FATAL ERROR]${RESET} $1\n\n" | tee -a "$logPATH"
echo "quit:" >> /var/tmp/dialog.log
echo "Patchomator finished: $(date '+%F %H:%M:%S')" | tee -a "$logPATH"
exit 1
}
# --read
# --write
displayConfig() {
echo "\n${BOLD}Currently configured labels:${RESET}"
# if a config file was created, show it at the end.
if [[ -f $configfile ]]
then
column -t -s "=;\"\"" <<< $(defaults read "$configfile" | tr -d "{}()\"")
else
# if no config was saved, show the results of the discovery process
for discoveredItem in $configArray
do
echo $discoveredItem
done
echo "\n${BOLD}Ignored Labels:${RESET}"
for ignoredItem in $ignoredLabelsList
do
echo $ignoredItem
done
echo "\n${BOLD}Required Labels:${RESET}"
for requiredItem in $requiredLabelsList
do
echo $requiredItem
done
fi
echo "quit:" >> /var/tmp/dialog.log
echo "Patchomator finished: $(date '+%F %H:%M:%S')" >> "$logPATH"
exit 0
}
checkInstallomator() {
infoOut "Checking Installomator version."
# check for existence of Installomator to enable installation of updates
notice "Looking for Installomator.sh at ${YELLOW}$InstallomatorPATH ${RESET}"
InstalledVersion="$($InstallomatorPATH version)"
LatestVersion="$(versionFromGit Installomator Installomator)"
notice "Latest Version: $LatestVersion - Installed Version: $InstalledVersion"
if [[ "$InstalledVersion" -ne "$LatestVersion" ]]
then
error "Installomator was found, but is out of date. You can update it by running \n\t${YELLOW}sudo $InstallomatorPATH installomator ${RESET}"
if [[ ${#noninteractive} -eq 1 ]]
then
notice "Running in non-interactive mode. Skipping Installomator update."
else
OfferToInstall
fi
fi
if ! [[ -f $InstallomatorPATH ]]
then
error "Installomator was not found at ${YELLOW}$InstallomatorPATH ${RESET}"
LatestInstallomator=$(curl --silent --fail "https://api.github.com/repos/Installomator/Installomator/releases/latest" | awk -F '"' "/browser_download_url/ && /pkg\"/ { print \$4; exit }")
if [[ ${#noninteractive} -eq 1 ]]
then
notice "Running in non-interactive mode. Skipping Installomator install."
else
OfferToInstall
fi
else
if [ $($InstallomatorPATH version | cut -d . -f 1) -lt 10 ]
then
fatal "Installomator is installed, but is out of date. Versions prior to 10.0 function unpredictably with Patchomator.\nYou can probably update it by running \n\t${YELLOW}sudo $InstallomatorPATH installomator ${RESET}"
fi
fi
}
# --install
OfferToInstall() {
#Check your privilege
if $IAMROOT
then
echo -n "Patchomator can still discover apps on the system and create a configuration for later use, but will not be able to install or update anything without Installomator. \
\n${BOLD}Download and install Installomator now? ${YELLOW}[y/N]${RESET} "
read DownloadFromGithub
if [[ $DownloadFromGithub =~ '[Yy]' ]]
then
installInstallomator
else
echo "${BOLD}Continuing without Installomator.${RESET}"
# disable installs
if [[ $installmode ]]
then
fatal "Patchomator cannot install or update apps without the latest Installomator. If you would like to continue, either re-run Patchomator without ${YELLOW}--install${RESET}, or install Installomator from this URL:\
\n\t ${YELLOW}https://github.com/Installomator/Installomator${RESET}"
fi
fi
else
fatal "Specify a different path with \"${YELLOW}-p [path to Installomator]${RESET}\" or download and install it from here:\
\n\t ${YELLOW}https://github.com/Installomator/Installomator${RESET}\
\n\nThis script can also attempt to install Installomator for you. Re-run patchomator with ${YELLOW}sudo${RESET} or without ${YELLOW}--install${RESET}"
fi
}
installInstallomator() {
# Get the URL of the latest PKG From the Installomator GitHub repo
# no need for git, if there's an API
PKGurl=$(curl --silent --fail "https://api.github.com/repos/Installomator/Installomator/releases/latest" | awk -F '"' "/browser_download_url/ && /pkg\"/ { print \$4; exit }")
# Expected Team ID of the downloaded PKG
expectedTeamID="JME5BW3F3R"
tempDirectory=$( mktemp -d )
notice "Created working directory '$tempDirectory'"
# Download the installer package
notice "Downloading Installomator package"
curl --location --silent "$PKGurl" -o "$tempDirectory/Installomator.pkg" || fatal "Download failed."
# Verify the download
teamID=$(spctl -a -vv -t install "$tempDirectory/Installomator.pkg" 2>&1 | awk '/origin=/ {print $NF }' | tr -d '()')
notice "Team ID of downloaded package: $teamID"
# Install the package, only if Team ID validates
if [ "$expectedTeamID" = "$teamID" ]
then
notice "Package verified. Installing package Installomator.pkg"
installer -pkg "$tempDirectory/Installomator.pkg" -target / -verbose || fatal "Installation failed. See /var/log/installer.log for details."
else
fatal "Package verification failed. TeamID does not match."
fi
# Remove the temporary working directory when done
notice "Deleting working directory '$tempDirectory' and its contents"
rm -Rf "$tempDirectory"
}
checkLabels() {
infoOut "Checking for latest labels."
notice "Looking for labels in ${fragmentsPATH}/labels/"
# use curl to get the labels - who needs git?
if [[ ! -d "$fragmentsPATH" ]]
then
if [[ -w "$patchomatorPath" ]]
then
infoOut "Package labels not present at $fragmentsPATH. Attempting to download from https://github.com/installomator/"
downloadLatestLabels
else
fatal "Package labels not present and $patchomatorPath is not writable. Re-run patchomator with sudo to download and install them."
fi
else
labelsAge=$((($(date +%s) - $(stat -t %s -f %m -- "$fragmentsPATH/labels")) / 86400))
if [[ $labelsAge -gt 30 ]]
then
if [[ -w "$patchomatorPath" ]]
then
error "Package labels are out of date. Last updated ${labelsAge} days ago. Attempting to download from https://github.com/installomator/"
downloadLatestLabels
else
fatal "Package labels are out of date. Last updated ${labelsAge} days ago. Re-run patchomator with sudo to update them."
fi
else
infoOut "Package labels installed. Last updated ${labelsAge} days ago."
fi
fi
}
dialogProgress() {
echo "message: $1" >> /var/tmp/dialog.log
echo "progress: reset" >> /var/tmp/dialog.log
}
dialogPercent() { # steps / max
echo "progress: $((100*$1/$2))" >> /var/tmp/dialog.log
}
dialogReset() {
echo "progress: reset" >> /var/tmp/dialog.log
}
downloadLatestLabels() {
dialogProgress "Downloading latest labels."
dialogPercent 1 5
# gets the latest release version tarball.
latestURL=$(curl -sSL -o - "https://api.github.com/repos/Installomator/Installomator/releases/latest" | grep tarball_url | awk '{gsub(/[",]/,"")}{print $2}') # remove quotes and comma from the returned string
#eg "https://api.github.com/repos/Installomator/Installomator/tarball/v10.3"
tarPath="$patchomatorPath/installomator.latest.tar.gz"
notice "Downloading ${latestURL} to ${tarPath}"
dialogPercent 2 5
curl -sSL -o "$tarPath" "$latestURL" || fatal "Unable to download. Check ${patchomatorPath} is writable or re-run as root."
dialogPercent 3 5
notice "Extracting ${tarPath} into ${patchomatorPath}"
tar -xz --include='*/fragments/*' -f "$tarPath" --strip-components 1 -C "$patchomatorPath" || fatal "Unable to extract ${tarPath}. Corrupt or incomplete download?"
touch "${fragmentsPATH}/labels/"
dialogPercent 5 5
}
# --install
doInstallations() {
infoOut "Performing installations."
# No sleeping
/usr/bin/caffeinate -d -i -m -u &
caffeinatepid=$!
# Count errors
errorCount=0
InstallomatorOptionsString=""
if [[ -n "$OptionsString" ]]; then
InstallomatorOptionsString+="$OptionsString"
else
# convert InstallomatorOptions array to string
for key value in ${(kv)InstallomatorOptions}; do
InstallomatorOptionsString+=" $key=\"$value\""
done
fi
installedLabels=0
dialogProgress "Installing $numLabels items."
for label in $queuedLabelsArray
do
let installedLabels++
dialogPercent $installedLabels $numLabels
infoOut "Installing ${label}..."
${InstallomatorPATH} ${label} ${InstallomatorOptionsString}
if [ $? != 0 ]; then
error "Error installing ${label}. Exit code $?"
let errorCount++
fi
done
echo "Errors: $errorCount"
echo "Patchomator finished: $(date '+%F %H:%M:%S')" | tee -a "$logPATH"
caffexit $errorCount
}
FindAppFromLabel() {
# appname label_name packageID
label_name=$1
appversion=""
if [ -z "$appName" ]; then
# when not given derive from name
appName="$name.app"
fi
# shortcut: pkgs contains a version number, if it's installed then we don't have to parse the plist.
# still need to confirm it's installed, tho. Receipts can be unreliable.
if [[ "$packageID" != "" ]]
then
notice "Searching system for $packageID"
appversion="$(pkgutil --pkg-info-plist ${packageID} 2>/dev/null | grep -A 1 pkg-version | tail -1 | sed -E 's/.*>([0-9.]*)<.*/\1/g')"
if [[ -n $appversion ]]; then
notice "Label: $label_name"
notice "--- found packageID $packageID version $appversion installed"
InstalledLabelsArray+=( "$label_name" )
fi
else
notice "Searching system for $appName"
fi
# get app in /Applications, or /Applications/Utilities, or find using Spotlight
if [[ -d "/Applications/$appName" ]]; then
applist="/Applications/$appName"
elif [[ -d "/Applications/Utilities/$appName" ]]; then
applist="/Applications/Utilities/$appName"
else
if [[ ${#everywhere} -eq 1 ]]; then
applist=$(mdfind "kMDItemFSName == '$appName' && kMDItemContentType == 'com.apple.application-bundle'" -0 )
else
applist=$(mdfind -onlyin "/Applications/" -onlyin "/usr/local/" -onlyin "/Library/" "kMDItemFSName == '$appName' && kMDItemContentType == 'com.apple.application-bundle'" -0 )
fi
# can't install things in /System/Applications, and probably shouldn't look in /Users
# apps installed in other weird locations should be identifiable by their pkg receipt.
# random files named *.app were potentially coming up in the list. Now it has to be an actual app bundle
fi
appPathArray=( ${(0)applist} )
if [[ ${#appPathArray} -gt 0 ]]
then
filteredAppPaths=( ${(M)appPathArray:#${targetDir}*} )
if [[ ${#filteredAppPaths} -eq 1 ]]
then
installedAppPath=$filteredAppPaths[1]
[[ -n "$appversion" ]] || appversion=$(defaults read "$installedAppPath/Contents/Info.plist" "$versionKey" 2> /dev/null)
infoOut "Found $appName version $appversion"
notice "Label: $label_name"
notice "--- found app at $installedAppPath"
# Is current app from App Store
# AND is IGNORE_APP_STORE_APPS=yes?
if [[ -d "$installedAppPath"/Contents/_MASReceipt ]] && [[ $InstallomatorOptions[IGNORE_APP_STORE_APPS] =~ [YyEeSs1] ]]
then
notice "$appName is from App Store. Ignoring."
notice "Use the Installomator option \"IGNORE_APP_STORE_APPS=no\" to replace."
else
foundLabelsArray[$label_name]="$installedAppPath"
fi
fi
fi
}
verifyApp() {
foundLabel="$1"
appPath="$2"
if [[ -n "$configArray[$appPath]" ]]
then
infoOut "$appPath already verified."
else
if [[ $skipVerify == false ]]
then
infoOut "Verifying: $appPath"
# verify with spctl
appVerify=$(spctl -a -vv "$appPath" 2>&1 )
appVerifyStatus=$(echo $?)
teamID=$(echo $appVerify | awk '/origin=/ {print $NF }' | tr -d '()' )
if [[ $appVerifyStatus -ne 0 ]]
then
error "Error verifying $appPath: Returned $appVerifyStatus"
return
fi
if [ "$expectedTeamID" != "$teamID" ]
then
error "Error verifying $appPath"
notice "Team IDs do not match: expected: $expectedTeamID, found $teamID"
return
fi
fi
infoOut "Checking version: $appPath"
# run the commands in current_label to check for the new version string
newversion=$(zsh << SCRIPT_EOF
declare -A levels=(DEBUG 0 INFO 1 WARN 2 ERROR 3 REQ 4)
currentUser=$currentUser
source "$fragmentsPATH/functions.sh"
${current_label}
echo "\$appNewVersion"
SCRIPT_EOF
)
fi
# build array of labels for the config and/or installation
# push label to array
# if in write config mode, writes to plist. Otherwise to an array.
if [[ -n "$configArray[$appPath]" ]]
then
exists="$configArray[$appPath]"
infoOut "${appPath} already linked to label ${exists}."
if [[ ${#noninteractive} -eq 1 ]]
then
echo "\t${BOLD}Skipping.${RESET}"
return
else
echo -n "${BOLD}Replace label ${exists} with $foundLabel? ${YELLOW}[y/N]${RESET} "
read replaceLabel
if [[ $replaceLabel =~ '[Yy]' ]]
then
echo "\t${BOLD}Replacing.${RESET}"
configArray[$appPath]=$label_name
# Remove duplicate label already in queue:
labelsList=$(echo "$labelsList" | sed s/"$exists "//)
# add replaced label to Ignored list
ignoredLabelsArray["$exists"]=1
if [[ ${#writeconfig} -eq 1 ]]
then
/usr/libexec/PlistBuddy -c "set \":${appPath}\" ${foundLabel}" "$configfile"
/usr/libexec/PlistBuddy -c "add \":IgnoredLabels:\" string \"${exists}\"" $configfile
fi
else
echo "\t${BOLD}Skipping.${RESET}"
# add skipped label to Ignored list
/usr/libexec/PlistBuddy -c "add \":IgnoredLabels:\" string \"${foundLabel}\"" $configfile
return
fi
fi
else
configArray[$appPath]=$foundLabel
if [[ ${#writeconfig} -eq 1 ]]
then
/usr/libexec/PlistBuddy -c "add \":${appPath}\" string ${foundLabel}" "$configfile"
fi
fi
appversion="$(pkgutil --pkg-info-plist ${packageID} 2>/dev/null | grep -A 1 pkg-version | tail -1 | sed -E 's/.*>([0-9.]*)<.*/\1/g')"
[[ -n "$appversion" ]] || appversion=$(defaults read "$appPath/Contents/Info.plist" "$versionKey" 2>/dev/null)
notice "--- Installed version: ${appversion}"
[[ -n "$newversion" ]] && notice "--- Newest version: ${newversion}"
if [[ "$appversion" == "$newversion" ]]
then
notice "--- Latest version installed."
else
queueLabel
fi
}
# --install
queueLabel() {
notice "Queueing $label_name"
# add to queue if in install mode
if [[ $installmode ]]
then
labelsList+="$label_name "
# echo "$labelsList"
fi
}
#######################################
# You're probably wondering why I've called you all here...
# Command line options
#zparseopts -D -E -F -K -- \
zparseopts -D -E -F -K -- \
-help+=showhelp h+=showhelp \
-install=installmode I=installmode \
-quiet=quietmode q=quietmode \
-yes=noninteractive y=noninteractive \
-verbose=verbose v=verbose \
-read=readconfig r=readconfig \
-write=writeconfig w=writeconfig \
-config:=configfile c:=configfile \
-skipverify=skipVerify s=skipVerify \
-pathtoinstallomator:=InstallomatorPATH p:=InstallomatorPATH \
-ignored:=ignoredLabels \
-required:=requiredLabels \
-mdm:=MDMName \
-everywhere=everywhere \
-options:=CLIOptions \
|| fatal "Bad command line option. See patchomator.sh --help"
# -h --help
# -I --install
# -q --quiet
# -y --yes
# -v --verbose
# -r --read
# -w --write
# -s --skip-verify
# -c / --config <config file path>
# -p / --pathtoinstallomator <installomator path>
# New in 1.1
# --mdm [one of jamf, mosyleb, mosylem, addigy, microsoft, ws1, other ] Any other Mac MDM solutions worth mentioning?
# --options "list of installomator options to pass through"
# Show usage
# --help
if [[ ${#showhelp} -gt 0 ]]
then
usage
fi
notice "Verbose Mode enabled." # and if it's not? This won't echo.
if ! [[ -f $configfile[-1] ]] && [[ -f $managedConfigfile ]]
then
configfile=$managedConfigfile
else
configfile=$configfile[-1] # either provided on the command line, or default path
fi
# prevent patchomator modify the content of the managed config
if [[ $configfile == $managedConfigfile ]] && [[ ${#writeconfig} -eq 1 ]]
then
fatal "You should not manualy overwrite ${YELLOW}$managedConfigfile${RESET}"
fi
InstallomatorPATH=$InstallomatorPATH[-1] # either provided on the command line, or default /usr/local/Installomator
MDMName=$MDMName[-1] #[one of jamf, mosyleb, mosylem, addigy, microsoft, ws1, other ]
# --mdm
# Assumes certain settings when an MDM is declared:
# - Installomator options:
# - logo
# - ?
# --install
# --quiet
# --yes
### Default Installomator Options:
InstallomatorOptions=(\
[NOTIFY]=success \
[PROMPT_TIMEOUT]=86400 \
[BLOCKING_PROCESS_ACTION]=tell_user \
[LOGO]=appstore \
[IGNORE_APP_STORE_APPS]="no" \
[SYSTEMOWNER]=0 \
[REOPEN]="yes" \
[INTERRUPT_DND]="yes" \
[NOTIFY_DIALOG]=1 \
[LOGGING]="INFO" \
)
# Parse command line --options
OptionsString=$CLIOptions[-1]
# split on spaces, then on =
# AddOptions=$(echo "$OptionsString" | awk -v OFS="\n" '{$1=$1}1' | awk -v FS="=" '{print "InstallomatorOptions+=\(["$1"]="$2"\)"}')
# Add them to the InstallomatorOptions array
# eval "$AddOptions"
# Additional optional settings by MDM
# if [ "$MDMName" ]
# then
# quietmode[1]=true
# # installmode=true
# noninteractive[1]=true
# fi
#
# if [ "$MDMName" ]
# then
# # set logos for known MDM vendors
# if [ "$MDMName" != "other" ]
# then
# InstallomatorOptions[LOGO]="$MDMName"
# fi
# fi
## Starting up. Need to log options, etc
## check for log location, writable, roll if over $size?
if [[ -w "$logPATH" ]] then
# exists and writable
echo "Patchomator starting $(date)" >> "$logPATH"
elif [[ ! -f "$logPATH" ]] then
# doesn't exist
touch "$logPATH" 2> /dev/null && chmod a+rw "$logPATH" || error "$logPATH not writable."
fi
notice "Option Count ${#InstallomatorOptions[@]}"
notice "Installomator Options:"
for key value in ${(kv)InstallomatorOptions}; do
notice " - $key=\"$value\""
done
# ReadConfig mode - read existing plist and display in pretty columns
# skips discovery and all the rest
# --read
if [[ ${#readconfig} -eq 1 ]]
then
notice "Reading Config"
if ! [[ -f $configfile ]]
then
fatal "No config file at $configfile. Run patchomator again with ${YELLOW}--write${RESET} to create one now.\n"
else
displayConfig
fi
fi
## initiate swiftdialog if we're doing more than just reading config.
if ! [[ ${#quietmode} -eq 1 ]]; then
[[ -f /usr/local/bin/dialog ]] && /usr/local/bin/dialog -t "Patchomator Progress" -m "Starting Patchomator." --style mini --icon "/usr/local/Installomator/patch-o-mater-icon.png" -o --progress 100 --button1text "..." & sleep .1
fi
if [[ -f $configfile ]] && [[ ${#writeconfig} -ne 1 ]]
then
infoOut "Reading existing configuration for ignored/required labels"
# parse the config for existing ignored/required labels
ignoredLabelsFromConfig=($(defaults read "$configfile" IgnoredLabels | awk '{printf "%s ",$NF}' | tr -c -d "[:alnum:][:space:][\-_]" | tr -s "[:space:]"))
requiredLabelsFromConfig=($(defaults read "$configfile" RequiredLabels | awk '{printf "%s ",$NF}' | tr -c -d "[:alnum:][:space:][\-_]" | tr -s "[:space:]"))
for ignoredLabel in $ignoredLabelsFromConfig
do
if [[ -f "${fragmentsPATH}/labels/${ignoredLabel}.sh" ]]
then
ignoredLabelsArray["$ignoredLabel"]=1
# echo $ignoredLabelsArray["$ignoredLabel"]
notice "Ignoring $ignoredLabel"
fi
done
for requiredLabel in $requiredLabelsFromConfig
do
if [[ -f "${fragmentsPATH}/labels/${requiredLabel}.sh" ]]
then
requiredLabelsArray["$requiredLabel"]=1
notice "Requiring $requiredLabel"
fi
done
fi
# Create Config file on --write, or if none already exists
# --write
if [[ ${#writeconfig} -eq 1 ]] || ! [[ -f $configfile ]]
then
notice "Writing Config"
if [[ -d $configfile ]] # common mistake, select a directory, not a filename
then
fatal "Please specify a file name for the configuration, not a directory.\n\tExample: ${YELLOW}patchomator --write --config \"/etc/patchomator.plist\""
fi
if ! [[ -f $configfile ]] # no existing config
then
if [[ -d "$(dirname $configfile)" ]]
# directory exists
then
if [[ -w "$(dirname $configfile)" ]]
#directory is writable
then
infoOut "No existing config file at $configfile. Creating one now."
else
# exists, but not writable
fatal "$(dirname $configfile) exists, but is not writable. Re-run patchomator with sudo to create the config file there, or use a writable path with\n\t ${YELLOW}--config \"path to config file\"${RESET}"
fi
else
# directory doesn't exist
infoOut "No existing config file at $configfile. Creating one now."
makepath "$configfile"
fi
# creates a blank plist
plutil -create xml1 "$configfile" || fatal "Unable to create $configfile. Re-run patchomator with sudo to create the config file there, or use a writable path with\n\t ${YELLOW}--config \"path to config file\"${RESET}"
else # file exists
if [[ -w $configfile ]]
then
infoOut "Refreshing $configfile"
# create blank plist or empty an existing one
/usr/libexec/PlistBuddy -c "clear dict" "${configfile}"
else
fatal "$configfile is not writable. Re-run patchomator with sudo, or use a writable path with\n\t ${YELLOW}--config \"path to config file\"${RESET}"
fi
fi
# add sections for label arrays
/usr/libexec/PlistBuddy -c 'add ":IgnoredLabels" array' "${configfile}"
/usr/libexec/PlistBuddy -c 'add ":RequiredLabels" array' "${configfile}"
fi
# END --write
# can't do discovery without the labels files.
checkLabels
# MOAR Functions! miscellaneous pieces referenced in the occasional label
# Needs to confirm that labels exist first.
source "$fragmentsPATH/functions.sh"
# can't install without the 'mator
# can't check version without the functions.
checkInstallomator
# speed up the discovery phase.
if [[ ${#skipVerify} -eq 1 ]]
then
skipVerify=true
else
skipVerify=false
fi
# --install
# some functions act differently based on install vs discovery/read
if [[ ${#installmode} -eq 1 ]]
then
installmode=true
fi
if [[ $installmode ]]
then
# Check your privilege
if ! $IAMROOT
then
fatal "Install mode must be run with root/sudo privileges. Re-run Patchomator with\n\t ${YELLOW}sudo zsh patchomator.sh --install${RESET}"
fi
fi
# discovery mode
# the main attraction.
# --required
if [[ -n "$requiredLabels" ]]
then
requiredLabelsList=("${(@s/ /)requiredLabels[-1]}")
notice "Required labels: $requiredLabelsList"
for requiredLabel in $requiredLabelsList
do
if [[ -f "${fragmentsPATH}/labels/${requiredLabel}.sh" ]]
then
notice "[CLI] Requiring ${requiredLabel}."