-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathpatchomator.sh
More file actions
executable file
·1664 lines (1405 loc) · 55.8 KB
/
patchomator.sh
File metadata and controls
executable file
·1664 lines (1405 loc) · 55.8 KB
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="1.2"
VERSIONDATE="2025-10-27"
VERSIONNAME="One Point Spooky"
# Gigantic Thanks to:
# rondelltron
# Skinflint
# 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:
# To Do:
# Add MDM optimized Non-interactive Mode --mdm "MDMName"
# Recent Changes/Fixes:
# Recommended ignores
# Dialog Prompt for choices to replace labels with timeout of promptTimeoutMax variable.
# Speed increases
# Script Checks
# Version output from --version
# Consistent messages for exiting and logging
# Set maximum rolled logs to 5 by default. Configured via backupLogsMax
# Roll logs if greater than 1MB by default. Configured via logSizeMax in bytes
# Use appCustomVersion from label file for a check
# Detect Swift Dialog
# remove extra spaces, and use requiredLabelsList
# 1.1.2 Installomator 10.8 version check
# Only search for apps in /Applications by default, optionally --everywhere
# Passing installomator options with spaces in.
# 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
IAMROOT=$(( EUID == 0 ))
autoload -Uz is-at-least
# 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"
backupLogsMax=5
logSizeMax=$((1024 * 1024)) # 1 MB in bytes
defaultPromptTimeoutMax=120 #Time in seconds
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=()
declare -A foundLabelsTeamID=()
declare -A foundLabelsAppVersion=()
declare -A foundLabelsPackageID=()
declare -A foundLabelsVersionKey=()
declare -A requiredLabelsPath=()
# default paths
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
defaultInstallomatorPATH=("/usr/local/Installomator/Installomator.sh")
defaultConfigFile=("/Library/Application Support/Patchomator/patchomator.plist")
managedConfigFile=("/Library/Managed Preferences/com.mac-nerd.patchomator.plist")
patchomatorPath="${${0:A:h}:-/usr/local/Installomator}"
patchomatorIcon="${patchomatorPath}/patch-o-mater-icon.png"
fragmentsPATH=("${patchomatorPath}/fragments")
lockfile="/tmp/com.mac-nerd.patchomator.lock"
# 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)
if [ -e "$lockfile" ] && kill -0 "$(cat "$lockfile")" 2>/dev/null; then
echo "Script is already running with PID $(cat "$lockfile"). Exiting."
exit 1
fi
echo $$ > "$lockfile"
# create a temporary working directory, removed when script exits clean
tempPath=$(mktemp -d)
if [[ -f /usr/local/bin/dialog ]]; then
DialogPATH="/var/tmp/patch_dialog.log"
rm -f "$DialogPATH" 2>/dev/null
touch "$DialogPATH" 2>/dev/null && chmod a+rw "$DialogPATH" || error "$DialogPATH not writable."
fi
[[ -w "$DialogPATH" ]] || DialogPATH="/dev/null"
# These are labels that commonly need sorting out because they are DMG installers for which a PKG also exists, or alternate/localized versions.
# If you find this helpful, and want to add other labels to the distributed script, open a PR at https://github.com/Mac-Nerd/patchomator/
recommendedIgnores=("bbedit" "firefox" "firefox_da" "firefox_intl" "firefoxesr" "firefoxesr_intl" "firefoxpkg_intl" "googlechrome" "googlechromeenterprise" "microsoftofficebusinesspro" "microsoftonedrive-deferred" "microsoftonedrive-rollingout" "microsoftonedrive-rollingoutdeferred" "microsoftonedrivesuinsiders" "microsoftonedrivesuprod" "microsoftoutlook-monthly" "zoomgov" "zoomclient" "virtualboxbeta" "virtualboxlatest" "virtualboxstable")
### Default Installomator Options:
InstallomatorOptions=(\
[NOTIFY]=success \
[PROMPT_TIMEOUT]=3600 \
[BLOCKING_PROCESS_ACTION]=tell_user \
[IGNORE_APP_STORE_APPS]="no" \
[SYSTEMOWNER]=0 \
[REOPEN]="yes" \
[INTERRUPT_DND]="yes" \
[NOTIFY_DIALOG]=1 \
[LOGGING]="INFO" \
[DEBUG]=-1
)
trap cleanup INT TERM
#######################################
# 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.\n"
echo "\t${BOLD}-h | --help \t${RESET} Show this text and exit."
echo "\t${BOLD}--version \t${RESET} Show version and exit."
echo "\t${BOLD}--fullversion \t${RESET} Show full version and exit."
echo "\t${BOLD}--icon \"path to icon.file\" \t${RESET} Set the icon file for Swift Dialog."
echo "\t${BOLD}--proxy \"proxyIP:Port\" \t${RESET} Attempts to access the specified proxy and sets the ALL_PROXY environment variable upon success."
echo "\t${BOLD}--required \"space-separated list of labels to require\""
echo "\t${BOLD}--ignored \"space-separated list of labels to ignore\"${RESET}\n\t\t If list contains ${YELLOW}'ALL'${RESET} then discovery will be skipped\n\t\t If list contains ${YELLOW}'RECOMMENDED'${RESET} then the recommended list of ignores will be appended.\n"
echo "\t${BOLD}-h | --help \t${RESET} Show this text and exit."
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."
echo "\t${BOLD}-c | --config \"path to config file\" \t${RESET} Overrides default configuration file location. \n\t\tDefault path ${YELLOW}$defaultConfigFile${RESET}"
echo "\t${BOLD}-e | --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}-g | --gatekeeper \t${RESET} Use spctl to check app against gatekeeper instead of using codesign."
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}-u | --updatescripts \t${RESET} Update scripts mode. This can be used with install mode to update the installomator and patchomator scripts.\n\t\tThis mode only updates scripts if they have been discovered or added to required list. ${BOLD}Requires sudo${RESET}\n"
echo "\t${BOLD}-p | --pathtoinstallomator \"path to Installomator.sh\"${RESET}\n\t\tDefault Installomator Path ${YELLOW}/usr/local/Installomator/Installomator.sh${RESET}"
echo "\t${BOLD}-o | --options \"option1=value option2=value ...\"${RESET}\tCommand line options passed through to Installomator.${RESET}"
echo "\t${BOLD}-m | --mdm \"name\"${RESET}\tOne of jamf, mosyleb, mosylem, addigy, microsoft, ws1, kandji, filewave. Changes the Swift Dialog icon to the respective MDM icon.${RESET}"
echo "\t${BOLD}-t | --timeout integer${RESET}\tSets the replace label timeout to specified integer. Cannot be less than 10 or over 9000 or it will default to $defaultPromptTimeoutMax seconds.${RESET}"
echo "${YELLOW}See readme for more options and examples: ${BOLD}https://github.com/mac-nerd/Patchomator${RESET}"
exit 0
}
finishAndExit () {
echo "Patchomator finished: $(date '+%F %H:%M:%S')" | tee -a "$logPATH"
(( ${#quietmode} )) || (( ${#readconfig} )) || echo "quit:" >> $DialogPATH
# Remove the temporary working directory when done
notice "Deleting working directory '$tempPath' and its contents"
rm -Rf "$tempPath"
rm -f "$lockfile" 2>/dev/null
exit $1
}
cleanup() {
[[ -e "$tmpTimeoutPromptfile" ]] && rm -f "$tmpTimeoutPromptfile" 2>/dev/null
if [[ -e "$tmpTimeoutDialogCommandFile" ]]; then
echo "quit:" >> "$tmpTimeoutDialogCommandFile"
sleep 0.1
rm -f "$tmpTimeoutDialogCommandFile" 2>/dev/null
fi
kill -0 "$caffeinatepid" 2>/dev/null && kill "$caffeinatepid" 2>/dev/null
kill -0 "$dialogPID" 2>/dev/null && kill "$dialogPID" 2>/dev/null
kill -0 "$dialogTimeoutPID" 2>/dev/null && kill "$dialogTimeoutPID" 2>/dev/null
echo
finishAndExit 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} )); then
echo "${YELLOW}[NOTICE]${RESET} $1" | tee -a "$logPATH"
fi
}
infoOut() { # normal messages
if (( ! ${#quietmode} )); then
echo "$1" | tee -a "$logPATH"
echo "progresstext: $1" >> $DialogPATH
fi
}
warning() { # warning messges
echo "${YELLOW}[WARN]${RESET} $1" | tee -a "$logPATH"
}
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"
cleanup
}
# --read
# --write
displayConfig() {
# if a config file exists and write or read config mode then read from file
if [[ -f "$configFile" ]] && ( (( ${#writeconfig} )) || (( ${#readconfig} )) )
then
echo "\n${BOLD}Currently configured labels:${RESET}"
column -t -s "=;\"\"" <<< $(defaults read "$configFile" | tr -d "{}()\"")
else
# if no config was saved, show the results of the discovery process
echo "\n${BOLD}Found labels:${RESET}"
printf "%s\n" ${(o)configArray}
echo "\n${BOLD}Ignored Labels:${RESET}"
printf "%s\n" ${(o)${(k)ignoredLabelsArray//\"/}}
echo "\n${BOLD}Required Labels:${RESET}"
printf "%s\n" ${(o)${(k)requiredLabelsArray//\"/}}
echo ""
if (( appNeedsUpdates > 0 )); then
echo "${BOLD}$appNeedsUpdates of $uniqueAppTotal found labels need updates.${RESET}"
elif (( processedLabels > 0 )); then
echo "${BOLD}None of the found apps need updates.${RESET}"
fi
fi
}
checkInstallomator() {
infoOut "Checking Installomator version."
# check for existence of Installomator to enable installation of updates
notice "Looking for Installomator.sh at ${YELLOW}$InstallomatorPATH ${RESET}"
if [[ ! -f "$InstallomatorPATH" ]]; then
error "Installomator was not found at ${YELLOW}$InstallomatorPATH ${RESET}"
OfferToInstall
fi
InstalledVersion="$($InstallomatorPATH version | tail -1)"
if [ $(echo $InstalledVersion | 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
LatestVersion="$(versionFromGit Installomator Installomator)"
[[ "$LatestVersion" == *"could not retrieve version"* ]] && LatestVersion=""
if [[ -z "$LatestVersion" ]] && [[ -n "$InstalledVersion" ]]; then
notice "Installomator is installed, but cannot check for latest version."
fi
if [[ -n "$LatestVersion" ]] && [[ -n "$InstalledVersion" ]]; then
notice "Latest Version: $LatestVersion - Installed Version: $InstalledVersion"
if ! is-at-least "$LatestVersion" "$InstalledVersion"; then
error "Installomator was found, but is out of date. You can update it by running \n\t${YELLOW}sudo $InstallomatorPATH installomator ${RESET}"
OfferToInstall
fi
fi
if (( ${#installmode} )) && [[ ! -f "$InstallomatorPATH" ]]; then
fatal "Cannot run patchomator in install mode without installomator."
fi
}
# --install
OfferToInstall() {
#Check your privilege
if (( ${#noninteractive} )); then
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} and without ${YELLOW}--yes${RESET}"
else
echo "Patchomator can still discover apps and create a configuration for later use, but will not be able to install or update anything without Installomator."
if [[ -n "$dialogPID" ]]; then
tmpTimeoutPromptFile=$(mktemp)
tmpTimeoutDialogCommandFile=$(mktemp /tmp/tmpTimeoutDialog.XXXXXX)
chmod a+rw "$tmpTimeoutDialogCommandFile"
dialogTimeoutPrompt "Download and install Installomator?\nPatchomator can still discover apps and create a configuration for later use, but will not be able to install or update anything without Installomator."\
"$tmpTimeoutPromptFile" "$tmpTimeoutDialogCommandFile" "Install Installomator?" "Yes" "No ($promptTimeoutMax)" &
sleep 0.2
dialogTimeoutPID=$(pgrep -f "$tmpTimeoutDialogCommandFile" | tail -n 1)
echo "hide:" >> "$DialogPATH"
fi
DownloadFromGithub="n"
for ((i=promptTimeoutMax; i>0; i--)); do
echo -ne "\r" && tput el
echo -ne "\r${BOLD}Download and install Installomator now? ${YELLOW}[y/N($i)]${RESET} "
[[ -n "$dialogPID" ]] && echo "button2text: No ($i)" >> "$tmpTimeoutDialogCommandFile"
if read -t 1 -k 1 char; then
if [[ "$char" =~ [Yy] ]]; then
DownloadFromGithub="$char"
break
elif [[ "$char" =~ [Nn] ]]; then
break
fi
fi
if [[ -n "$dialogPID" ]] && [[ -s "$tmpTimeoutPromptFile" ]]; then
DownloadFromGithub="$(< "$tmpTimeoutPromptFile")"
break
fi
done
echo -ne "\r" && tput el
echo -ne "\r${BOLD}Download and install Installomator now? ${YELLOW}[y/N]${RESET} "
echo "$DownloadFromGithub"
if [[ -n "$dialogPID" ]]; then
kill $dialogTimeoutPID 2>/dev/null
rm -f "$tmpTimeoutPromptFile" "$tmpTimeoutDialogCommandFile" 2>/dev/null
echo "position: center" >> "$DialogPATH"
echo "show:" >> "$DialogPATH"
fi
if [[ $DownloadFromGithub =~ '[Yy]' ]]; then
installInstallomator
else
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
}
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
dialogProgress "Installing Installomator"
infoOut "Downloading Installomator package"
curl --location --silent "$PKGurl" -o "$tempDirectory/Installomator.pkg" || fatal "Download failed."
# Verify the download
teamID=$(spctl -a -vv -t install "$tempPath/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
infoOut "Package verified. Installing package Installomator.pkg"
installer -pkg "$tempDirectory/Installomator.pkg" -target / -verbose
installStatus=$(echo $?)
if [ $installStatus != 0 ]; then
rm -Rf "$tempDirectory" 2>/dev/null
fatal "Installation failed. See /var/log/installer.log for details."
fi
else
rm -Rf "$tempDirectory" 2>/dev/null
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" 2>/dev/null
}
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
infoOut "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
elif [[ ! -f "$fragmentsPATH/functions.sh" ]]; then
if [[ -w "$patchomatorPath" ]]; then
infoOut "Installomator functions file is missing. Attempting to download from https://github.com/installomator/"
downloadLatestLabels
else
fatal "Installomator functions file is missing. Re-run patchomator with sudo to reinstall fragments folder."
fi
else
infoOut "Package labels installed. Last updated ${labelsAge} days ago."
fi
fi
}
dialogProgress() {
if (( ! ${#quietmode} )); then
echo "message: $1" >> $DialogPATH
echo "progress: reset" >> $DialogPATH
fi
}
dialogPercent() { # steps / max
if (( ! ${#quietmode} )); then
echo "progress: $((100*$1/$2))" >> $DialogPATH
fi
}
dialogReset() {
if (( ! ${#quietmode} )); then
echo "progress: reset" >> $DialogPATH
fi
}
rollLogs() {
notice "Rolling over logs. Max logs is $backupLogsMax."
for (( i=backupLogsMax; i>=1; i-- )); do
prevLog=$((i-1))
if [[ $prevLog -eq 0 ]]; then
srcLog="$logPATH"
else
srcLog="$logPATH.$prev"
fi
destLog="$logPATH.$i"
if [[ -f "$srcLog" ]]; then
mv -f "$srcLog" "$destLog"
fi
done
touch "$logPATH" 2>/dev/null && chmod a+rw "$logPATH" || error "$logPATH not writable."
}
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"
# temptarDirectory=$( mktemp -d )
tarPath="$tempPath/installomator.latest.tar.gz"
notice "Downloading ${latestURL} to ${tarPath}"
dialogPercent 2 5
curl -sSL -o "$tarPath" "$latestURL" || fatal "Unable to download. Check ${tempPath} 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
# Remove the temporary working directory when done
notice "Deleting working directory '$temptarDirectory' and its contents"
rm -Rf "$temptarDirectory" 2>/dev/null
}
# --install
doInstallations() {
infoOut "Performing installations."
# No sleeping
/usr/bin/caffeinate -d -i -m -u -w $$ -t 1800 &
caffeinatepid=$!
# Count errors
errorCount=0
# convert InstallomatorOptions array to string
InstallomatorOptionsString=""
for key value in ${(kv)InstallomatorOptions}; do
InstallomatorOptionsString+=" $key=\"$value\""
done
installedLabels=0
dialogProgress "Installing $numLabels items."
for label in $queuedLabelsArray
do
let installedLabels++
dialogPercent $installedLabels $numLabels
infoOut "Installing ${label}..."
if [[ "$label" == "installomator" ]] || [[ "$label" == "patchomator" ]]; then
if (( ! ${#updatescripts} )); then
infoOut "${BOLD}Skipping $label.${RESET}\n"
continue
fi
fi
${InstallomatorPATH} ${label} ${InstallomatorOptionsString}
installomatorStatus=$(echo $?)
if [ $installomatorStatus != 0 ]; then
error "Error installing ${label}. Exit code $installomatorStatus\n"
fi
done
kill "$caffeinatepid" 2>/dev/null
}
FindAppFromLabel() {
# appname label_name packageID
label_name=$1
installLocation=""
applist=""
notice "Label: $label_name"
if [ -z "$appName" ]; then
# when not given derive from name
appName="$name.app"
fi
# if the appversion is already set, there is an appCustomVersion function defined
# check the funtion to see if it uses defaults read for an Info.plist for the app
# if that exists, we can parse the file path from the function
if [[ -n "$appversion" ]]; then
if echo "$appCustomVersion" | grep -q 'Contents/Info\.plist'; then
installLocation=$(echo "$appCustomVersion" | tr -d '\n' | sed -n 's|.*defaults read *"\{0,1\}\([^"]\{1,\}\)/Contents/Info.plist.*|\1|p')
if [[ -d "$installLocation" ]]; then
notice "Found: ${installLocation}"
applist="$installLocation"
fi
fi
fi
# shortcut: pkgs contains a version number, if it's installed then we don't have to search the HD for the file
# still need to confirm it's installed, tho. Receipts can be unreliable.
if [[ -n "$packageID" ]] && [[ -z "$applist" ]]; 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 "--- found packageID $packageID version $appversion installed"
installLocation="$(pkgutil --pkg-info-plist ${packageID} 2>/dev/null | grep -A 1 install-location | tail -1 | sed -E 's/.*>(.*)<.*/\1/g')"
installLocation=${installLocation%/}
if [ -f "/${installLocation}/$name.sh" ]; then
notice "Found: /${installLocation}/$name.sh"
applist="/${installLocation}/$name.sh"
else
for ext in .app .plugin .prefPane .framework .kext; do
if [ -d "/${installLocation}${ext}" ]; then
notice "Found: /${installLocation}${ext}"
applist="/${installLocation}${ext}"
break
fi
done
fi
fi
fi
# get app in /Applications, or /Applications/Utilities, or find using Spotlight if not already found
if [[ -z "$applist" ]]; then
notice "Searching system for $appName"
if [[ -z "$mdfindAppList" ]]; then
if (( ${#everywhere} )); then
mdfindAppList=$(mdfind "kMDItemContentType == 'com.apple.application-bundle'")
else
mdfindAppList=$(mdfind -onlyin "/Applications/" -onlyin "/usr/local/" -onlyin "/Library/" "kMDItemContentType == 'com.apple.application-bundle'")
fi
fi
applist=$(grep "/$appName" <<< "$mdfindAppList")
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 $name 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"
foundLabelsTeamID[$label_name]="$expectedTeamID"
foundLabelsAppVersion[$label_name]="$appversion"
foundLabelsPackageID[$label_name]="$packageID"
foundLabelsVersionKey[$label_name]="$versionKey"
if [[ ${requiredLabelsArray["$label_name"]} == 1 ]]; then
requiredLabelsPath["$installedAppPath"]="$label_name"
fi
fi
fi
fi
}
dialogTimeoutPrompt() {
local message="$1"
local promptFile="$2"
local commandFile="$3"
local title="$4"
local button1="$5"
local button2="$6"
/usr/local/bin/dialog --title "$title" \
--message "$message" \
--icon "$swiftDialogIcon" \
--mini \
--button1text "$button1" \
--button2text "$button2" \
--ontop \
--moveable \
--position "center" \
--commandfile "$commandFile" > /dev/null 2>&1
dialogTimeoutRet=$(echo $?)
if [[ "$dialogTimeoutRet" -eq 0 ]]; then
echo "y" > "$promptFile"
elif [[ "$dialogTimeoutRet" -eq 2 ]]; then
echo "n" > "$promptFile"
fi
}
verifyApp() {
foundLabel="$1"
appPath="$2"
appNewVersion=""
infoOut "Checking: $appPath"
notice "--- Processing Label $foundLabel at $appPath"
if [[ -n "$configArray[$appPath]" ]]
then
infoOut "$appPath already verified."
else
if (( ! ${#skipVerify} ))
then
infoOut "Verifying: $appPath"
# verify with spctl or codesign
if (( ${#useSpctl} )); then
appVerify=$(spctl -a -vv "$appPath" 2>&1 )
else
appVerify=$(codesign -dv "$appPath" 2>&1 )
fi
appVerifyStatus=$(echo $?)
# If there is no usable signature and the app type is .plugin, then try another method
# Found useful for JRE since Oracle does not sign JRE Plugin, but does sign in bin
if [[ "$appVerify" == *"not signed at all" ]] || [[ "$appVerify" == *"no usable signature" ]]; then
if [[ "$appPath" == *".plugin" ]]; then
teamIdentifiers="$(find "$appPath/Contents/Home/Bin" -type f -exec codesign -dv {} 2>&1 \; | grep TeamIdentifier | sort -u)"
if [[ -n "$teamIdentifiers" ]]; then
idCount=$(printf "%s\n" "$teamIdentifiers" | wc -l | tr -d ' ')
if ((idCount > 1)); then
error "Error verifying $appPath"
notice "Team IDs do not match: expected: $expectedTeamID, found multiple IDs in plugin Home/Bin directory"
return
fi
teamID="${teamIdentifiers#*=}"
else
error "Error verifying $appPath"
notice "Team IDs do not match: expected: $expectedTeamID, found no IDs in plugin Home/Bin directory"
return
fi
elif [[ "$appPath" == *".sh" ]]; then
verifyScript
verifyScriptStatus=$(echo $?)
if [[ $verifyScriptStatus -gt 1 ]]; then
error "Error verifying the script."
return
elif [[ $verifyScriptStatus -eq 1 ]]; then
infoOut "The script has been modified from it's original version."
infoOut "\t${BOLD}Skipping.${RESET}"
return
fi
fi
else
if [[ $appVerifyStatus -ne 0 ]]; then
error "Error verifying $appPath: Returned $appVerifyStatus"
return
fi
if (( ${#useSpctl} )); then
teamID=$(echo $appVerify | awk '/origin=/ {print $NF }' | tr -d '()' )
else
teamID=${$(grep 'TeamIdentifier' <<< "$appVerify")#*=}
fi
fi
if [ "$expectedTeamID" != "$teamID" ]; then
error "Error verifying $appPath"
notice "Team IDs do not match: expected: $expectedTeamID, found $teamID"
return
fi
fi
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} )); then
infoOut "\t${BOLD}Skipping.${RESET}"
return
else
if [[ -n "$dialogPID" ]]; then
tmpTimeoutPromptFile=$(mktemp)
tmpTimeoutDialogCommandFile=$(mktemp /tmp/tmpTimeoutDialog.XXXXXX)
chmod a+rw "$tmpTimeoutDialogCommandFile"
dialogTimeoutPrompt "Replace label '${exists}' with '$foundLabel'?" "$tmpTimeoutPromptFile" "$tmpTimeoutDialogCommandFile" "Replace Label?" "Replace" "Skip ($promptTimeoutMax)" &
sleep 0.2
dialogTimeoutPID=$(pgrep -f "$tmpTimeoutDialogCommandFile" | tail -n 1)
echo "hide:" >> "$DialogPATH"
fi
replaceLabel="n"
for ((i=promptTimeoutMax; i>0; i--)); do
echo -ne "\r" && tput el
echo -ne "\r${BOLD}Replace label ${exists} with $foundLabel? ${YELLOW}[y/N($i)]${RESET} "
[[ -n "$dialogPID" ]] && echo "button2text: Skip ($i)" >> "$tmpTimeoutDialogCommandFile"
if read -t 1 -k 1 char; then
if [[ "$char" =~ [Yy] ]]; then
replaceLabel="$char"
break
elif [[ "$char" =~ [Nn] ]]; then
break
fi
fi
if [[ -n "$dialogPID" ]] && [[ -s "$tmpTimeoutPromptFile" ]]; then
replaceLabel="$(< "$tmpTimeoutPromptFile")"
break
fi
done
echo -ne "\r" && tput el
echo -ne "\r${BOLD}Replace label ${exists} with $foundLabel? ${YELLOW}[y/N]${RESET} "
echo "$replaceLabel"
if [[ -n "$dialogPID" ]]; then
kill $dialogTimeoutPID 2>/dev/null
rm -f "$tmpTimeoutPromptFile" "$tmpTimeoutDialogCommandFile" 2>/dev/null
echo "position: center" >> "$DialogPATH"
echo "show:" >> "$DialogPATH"
fi
if [[ "$replaceLabel" =~ [Yy] ]]
then
infoOut "\t${BOLD}Replacing.${RESET}"
configArray[$appPath]=$foundLabel
# add replaced label to Ignored list
ignoredLabelsArray["$exists"]=1
ignoredLabelsList+=("$exists")
# remove item from unique tally
let uniqueAppTotal--
# remove item from update tally
CURRENTIFS="$IFS"
IFS=' '
if [[ ! " ${appUpToDateList[@]} " =~ " ${exists} " ]]; then
let appNeedsUpdates--
fi
IFS="$CURRENTIFS"
if (( ${#writeconfig} )); then
/usr/libexec/PlistBuddy -c "set \":${appPath}\" ${foundLabel}" "$configFile"
/usr/libexec/PlistBuddy -c "add \":IgnoredLabels:\" string \"${exists}\"" $configFile
fi
else
infoOut "\t${BOLD}Skipping.${RESET}"
# add skipped label to Ignored list
ignoredLabelsArray["$foundLabel"]=1
(( ${#writeconfig} )) && /usr/libexec/PlistBuddy -c "add \":IgnoredLabels:\" string \"${foundLabel}\"" $configFile
return
fi
fi
else
configArray[$appPath]=$foundLabel
(( ${#writeconfig} )) && /usr/libexec/PlistBuddy -c "add \":${appPath}\" string ${foundLabel}" "$configFile"
fi
# If appversion was not found from eval then try a couple other methods
[[ -n "$appversion" ]] || 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)
[[ -n "$appversion" ]] && notice "--- Installed version: ${appversion}"
if [[ -z "$appNewVersion" ]] && grep -q '^\s*appNewVersion' "$labelFragment"; then
linesToEval="case $foundLabel in
$foundLabel|\
$(cat $labelFragment)
esac"
appNewVersion=$(zsh <<-EOF
DEBUG=1 && INSTALL="force"
declare -A levels=(DEBUG 0 INFO 1 WARN 2 ERROR 3 REQ 4)
currentUser=$currentUser
source "$fragmentsPATH/functions.sh"
printlog() { }
cleanupAndExit() { }
$(printf '%s\n' "${linesToEval}") 2>/dev/null
echo "\$appNewVersion"
EOF
)
fi
if [[ -n "$appNewVersion" ]]; then
notice "--- Newest version: ${appNewVersion}"
if is-at-least "$appNewVersion" "$appversion"; then
infoOut "--- Latest version installed."
appUpToDateList+=($foundLabel)
else
infoOut "--- Newer version available."
let appNeedsUpdates++
fi
else
infoOut "--- Unable to find newest version."
let appNeedsUpdates++
fi
if (( ${#installmode} )); then
labelsList+="$foundLabel "
fi
let uniqueAppTotal++
}
verifyScript() {
downloadURL=""
type=""
local retval=0
eval $(grep -E -m1 '^\s*type' "$labelFragment") 2>/dev/null
labelDownloadUrl=$(grep -E -m1 '^\s*downloadURL' "$labelFragment")
if grep -q '^\s*appNewVersion' "$labelFragment"; then
linesToEval="case $foundLabel in
$foundLabel|\
$(cat $labelFragment)
esac"
appNewVersion=$(zsh <<-EOF
DEBUG=1 && INSTALL="force"
declare -A levels=(DEBUG 0 INFO 1 WARN 2 ERROR 3 REQ 4)
currentUser=$currentUser
source "$fragmentsPATH/functions.sh"
printlog() { }
cleanupAndExit() { }
$(printf '%s\n' "${linesToEval}") 2>/dev/null
echo "\$appNewVersion"
EOF
)
fi
if [[ "$appNewVersion" == "$appversion" ]]; then
eval "$labelDownloadUrl" 2>/dev/null
elif [[ "$labelDownloadUrl" == *"downloadURLFromGit"* ]]; then
labelDownloadUrl=(${(s: :)labelDownloadUrl})
local gitusername=$(echo "$labelDownloadUrl" | awk '{print $2}')
local gitreponame=$(echo "$labelDownloadUrl" | awk '{print $3}')
downloadURL=$(curl -sfL "https://api.github.com/repos/$gitusername/$gitreponame/releases/tags/$appversion" | awk -F '"' "/browser_download_url/ && /$filetype\"/ { print \$4; exit }")
[[ -z "$downloadURL" ]] && downloadURL=$(curl -sfL "https://api.github.com/repos/$gitusername/$gitreponame/releases/tags/v$appversion" | awk -F '"' "/browser_download_url/ && /$filetype\"/ { print \$4; exit }")
else
notice "Unsure how to handle a download URL that is not the latest release from anywhere but github."
return 2
fi
if [[ -n "$downloadURL" ]] && [[ "$type" == "pkg" ]]; then
tmpPkgFile="$tempPath/$foundLabel.pkg"
notice "Downloading $downloadURL"
curl -sfL "$downloadURL" > "$tmpPkgFile" 2>/dev/null
if (( ${#useSpctl} )); then
scriptVerify=$(spctl -a -vv -t install "$tmpPkgFile" 2>&1 )
else
scriptVerify=$(pkgutil --check-signature "$tmpPkgFile" 2>&1 )
fi
scriptVerifyStatus=$(echo $?)
if [[ $scriptVerifyStatus -eq 0 ]]; then