-
Notifications
You must be signed in to change notification settings - Fork 1
/
runme.ps1
1860 lines (1706 loc) · 101 KB
/
runme.ps1
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/pwsh
set-executionpolicy -scope CurrentUser -executionPolicy Bypass -Force
# Set culture to Invariant Culture to ensure consistent number formatting
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::InvariantCulture
### Variables and constants ###
## Env file related constants and variables ##
# env file name and template file name #
$script:ENV_TEMPLATE_FILENAME = '.env.template'
$script:ENV_FILENAME = '.env'
# Env file default #
$DEVICE_NAME_PLACEHOLDER = 'yourDeviceName'
$script:DEVICE_NAME = 'yourDeviceName'
# Proxy config #
$script:PROXY_CONF = $false
$script:CURRENT_PROXY = ''
$script:NEW_STACK_PROXY = ''
## Config file related constants and variables ##
$script:APP_CONFIG_JSON_FILE = "app_config.json"
$script:MAINMENU_JSON_FILE = "mainmenu.json"
## Docker compose related constants and variables ##
# docker compose yaml file name and template file name #
$DKCOM_TEMPLATE_FILENAME = "docker-compose.yaml.template"
$DKCOM_FILENAME = "docker-compose.yaml"
### Docker installer script for Windows source link ##
$DKINST_WIN_SRC = 'https://github.com/MRColorR/money4band/raw/main/.resources/.scripts/install-docker-win.ps1'
### Docker installer script for Mac source link ##
$DKINST_MAC_SRC = 'https://github.com/MRColorR/money4band/raw/main/.resources/.scripts/install-docker-mac.ps1'
## Script init and variables ##
# Script default sleep time #
$SLEEP_TIME = 1.5
### Resources, Scripts and Files folders ###
$script:RESOURCES_DIR = "$PWD\.resources"
$script:CONFIG_DIR = "$RESOURCES_DIR\.www\.configs"
$script:SCRIPTS_DIR = "$RESOURCES_DIR\.scripts"
$script:FILES_DIR = "$RESOURCES_DIR\.files"
## Architecture and OS related constants and variables ##
# Architecture default. Also define a map for the recognized architectures #
$script:ARCH = 'unknown'
$script:DKARCH = 'unknown'
$arch_map = @{
"x86_64" = "amd64";
"amd64" = "amd64";
"aarch64" = "arm64";
"arm64" = "arm64";
}
# OS default. Also define a map for the recognized OSs #
$script:OS_TYPE = 'unknown'
# Define the OS type map
$os_map = @{
"win32nt" = "Windows"
"windows_nt" = "Windows"
"windows" = "Windows"
"linux" = "Linux";
"darwin" = "MacOS";
"macos" = "MacOS";
"macosx" = "MacOS";
"mac" = "MacOS";
"osx" = "MacOS";
"cygwin" = "Cygwin";
"mingw" = "MinGw";
"msys" = "Msys";
"freebsd" = "FreeBSD";
}
## Colors ##
# Colors used inside the script #
$colors = @{
"default" = [System.ConsoleColor]::White
"green" = [System.ConsoleColor]::Green
"blue" = [System.ConsoleColor]::Blue
"red" = [System.ConsoleColor]::Red
"yellow" = [System.ConsoleColor]::Yellow
"magenta" = [System.ConsoleColor]::Magenta
"cyan" = [System.ConsoleColor]::Cyan
}
# Color functions #
function colorprint($color, $text) {
$color = $color.ToLower()
#$prevColor = [System.Console]::ForegroundColor
if ($colors.ContainsKey($color)) {
[System.Console]::ForegroundColor = $colors[$color]
Write-Output $text
#[System.Console]::ForegroundColor = $prevColor
[System.Console]::ForegroundColor = $colors["default"]
}
else {
Write-Output "Unknown color: $color. Available colors are: $($colors.Keys -join ', ')"
}
}
# initialize the env file with the default values if there is no env file already present
# Check if the ${ENV_FILENAME} file is already present in the current directory, if it is not present copy from the .env.template file renaming it to ${ENV_FILENAME}, if it is present ask the user if they want to reset it or keep it as it is
if (-not (Test-Path .\${ENV_FILENAME})) {
Write-Output "No ${ENV_FILENAME} file found, copying ${ENV_FILENAME} and ${DKCOM_FILENAME} from the template files"
Copy-Item .\${ENV_TEMPLATE_FILENAME} .\${ENV_FILENAME} -Force
Copy-Item .\${DKCOM_TEMPLATE_FILENAME} .\${DKCOM_FILENAME} -Force
Write-Output "Copied ${ENV_FILENAME} and ${DKCOM_FILENAME} from the template files"
}
else {
Write-Output "Already found ${ENV_FILENAME} file, proceeding with setup"
# check if the release version in the local env fileis the same of the local template file , if not align it
$LOCAL_SCRIPT_VERSION = (Get-Content .\${ENV_FILENAME} | Select-String -Pattern "PROJECT_VERSION=" -SimpleMatch).ToString().Split("=")[1]
$LOCAL_SCRIPT_TEMPLATE_VERSION = (Get-Content .\${ENV_TEMPLATE_FILENAME} | Select-String -Pattern "PROJECT_VERSION=" -SimpleMatch).ToString().Split("=")[1]
if ($LOCAL_SCRIPT_VERSION -ne $LOCAL_SCRIPT_TEMPLATE_VERSION) {
Write-Output "Local ${ENV_FILENAME} file version differs from local ${ENV_TEMPLATE_FILENAME} file version"
Write-Output "This could be the result of an updated project using an outdated ${ENV_FILENAME} file"
Start-Sleep -Seconds $SLEEP_TIME
Write-Output "Generating new ${ENV_FILENAME} and ${DKCOM_FILENAME} files from the local template files and backing up the old files as ${ENV_FILENAME}.bak and ${DKCOM_FILENAME}.bak"
Copy-Item "${ENV_FILENAME}" "${ENV_FILENAME}.bak" -Force
Copy-Item "${ENV_TEMPLATE_FILENAME}" "${ENV_FILENAME}" -Force
Copy-Item "${DKCOM_FILENAME}" "${DKCOM_FILENAME}.bak" -Force
Copy-Item "${DKCOM_TEMPLATE_FILENAME}" "${DKCOM_FILENAME}" -Force
Write-Output "New local ${ENV_FILENAME} and ${DKCOM_FILENAME} files generated from the local template files"
Write-Output "If you are unsure, download the latest version directly from GitHub."
Start-Sleep -Seconds $SLEEP_TIME
Read-Host -Prompt "Press Enter to continue"
}
}
# Script version getting it from ${ENV_FILENAME} file#
$SCRIPT_VERSION = (Get-Content .\${ENV_FILENAME} | Select-String -Pattern "PROJECT_VERSION=" -SimpleMatch).ToString().Split("=")[1]
# Script name #
$SCRIPT_NAME = $MyInvocation.MyCommand.Name # save the script name in a variable, not the full path
# Project Discord URL #
$DS_PROJECT_SERVER_URL = (Get-Content .\${ENV_FILENAME} | Select-String -Pattern "DS_PROJECT_SERVER_URL=" -SimpleMatch).ToString().Split("=")[1]
# Script URL for update #
$PROJECT_BRANCH = "main"
$PROJECT_URL = "https://raw.githubusercontent.com/MRColorR/money4band/${PROJECT_BRANCH}"
# Script debug log file #
$DEBUG_LOG = "debug_$SCRIPT_NAME.log"
# Function to manage unexpected choices of flags #
function fn_unknown($REPLY) {
colorprint "Red" "Unknown choice $REPLY, please choose a valid option"
}
# Function to exit the script gracefully #
function fn_bye {
colorprint "Green" "Share this app with your friends thank you!"
colorprint "Cyan" "Support the M4B development <3 check the donation options in the README, on GitHub or in our Discord. Every bit helps!"
print_and_log "Green" "Exiting the application...Bye!Bye!"
exit 0
}
### Log, Update and Utility functions ###
# Function to write info/debug/warn/error messages to the log file if debug flag is true #
function toLog_ifDebug {
param (
[Parameter(Mandatory = $false)]
[Alias('l')]
[string]$log_level = "[DEBUG]",
[Parameter(Mandatory = $true)]
[Alias('m')]
[string]$message
)
# Only log if DEBUG mode is enabled
if ($script:DEBUG) {
"$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) - $log_level - $message" | Out-File -Append -FilePath $script:DEBUG_LOG
}
}
## Enable or disable logging using debug mode ##
# Check if the first argument is -d or --debug if so, enable debug mode
if ($args[0] -eq '-d' -or $args[0] -eq '--debug') {
$script:DEBUG = $true
# shift the arguments array to remove the debug flag consumed
$args = $args[1..$args.Length]
toLog_ifDebug -l "[DEBUG]" -m "Debug mode enabled."
}
else {
$script:DEBUG = $false
}
# Function to print an info message that will be also logged to the debug log file #
function print_and_log($color, $message) {
colorprint $color $message
toLog_ifDebug -l "[INFO]" -m "$message"
}
# Function to print an error message and write it to the debug log file #
function errorprint_and_log($text) {
Write-Error $text
toLog_ifDebug -l "[ERROR]" -m "$text"
}
# Function to print criticals errors that will stop the script execution, write them to the debug log file and exit the script with code 1 #
function fn_fail($text) {
errorprint_and_log $text
Read-Host -Prompt "Press Enter to exit..."
exit 1
}
## Utility functions ##
# Function to check if the env file is already configured #
function Check-ConfigurationStatus {
param (
[string]$envFileArg
)
# Check if ${envFileArg} file is already configured
$script:ENV_CONFIGURATION_STATUS = (Get-Content $envFileArg | Select-String -Pattern "ENV_CONFIGURATION_STATUS=" -SimpleMatch).ToString().Split("=")[1]
toLog_ifDebug -l "[DEBUG]" -m "Current ENV_CONFIGURATION_STATUS: $ENV_CONFIGURATION_STATUS"
$script:PROXY_CONFIGURATION_STATUS = (Get-Content $envFileArg | Select-String -Pattern "PROXY_CONFIGURATION_STATUS=" -SimpleMatch).ToString().Split("=")[1]
toLog_ifDebug -l "[DEBUG]" -m "Current PROXY_CONFIGURATION_STATUS: $PROXY_CONFIGURATION_STATUS"
$script:NOTIFICATIONS_CONFIGURATION_STATUS = (Get-Content $envFileArg | Select-String -Pattern "NOTIFICATIONS_CONFIGURATION_STATUS=" -SimpleMatch).ToString().Split("=")[1]
toLog_ifDebug -l "[DEBUG]" -m "Current NOTIFICATIONS_CONFIGURATION_STATUS: $NOTIFICATIONS_CONFIGURATION_STATUS"
}
# Function to round up to the nearest power of 2
function RoundUpPowerOf2 {
param([float]$value)
$value = ($value) # Convert to an integer by rounding
$i = 1
while ($i -lt $value) {
$i = $i * 2
}
return $i
}
function adaptLimits {
# Define minimum values for CPU and RAM limits
$MIN_CPU_LIMIT = 0.2 # Minimum CPU limit (reasonable value)
$MIN_MEM_LIMIT = 6 # Minimum RAM limit is 6 MB (enforced by Docker)
$COMPUTER_INFO = Get-CimInstance -ClassName Win32_ComputerSystem
# Get the number of CPU cores the machine has and others CPU related info
# $CPU_INFO = Get-CimInstance -ClassName Win32_Processor
# $CPU_SOCKETS = $COMPUTER_INFO.NumberOfProcessors
# #$CPU_SOCKETS = '-' # Uncomment to simulate incorrect socket number reporting
# if (-not [int]::TryParse($CPU_SOCKETS, [ref]$null)) {
# $CPU_SOCKETS = 1 # Default to 1 if CPU_SOCKETS is not a number
# }
# $CPU_CORES = $CPU_INFO.NumberOfCores
# $TOTAL_CPUS_OLD = $CPU_CORES * $CPU_SOCKETS # commented ot as the absh equivalent calculations were not working on some systems as sockets or cpus per socket are not reported correctly
$TOTAL_CPUS = (Get-WmiObject -Class Win32_Processor | Measure-Object -Property NumberOfCores -Sum).Sum
# Adapt the limits in .env file for CPU and RAM taking into account the number of CPU cores the machine has and the amount of RAM the machine has
# CPU limits: little should use max 25% of the CPU power , medium should use max 50% of the CPU power , big should use max 75% of the CPU power , huge should use max 100% of the CPU power
$appCpuLimitLittle = ($TOTAL_CPUS * 25 / 100)
$appCpuLimitMedium = ($TOTAL_CPUS * 50 / 100)
$appCpuLimitBig = ($TOTAL_CPUS * 75 / 100)
$appCpuLimitHuge = ($TOTAL_CPUS * 100 / 100)
# Ensure CPU limits are not below minimum
$appCpuLimitLittle = [math]::Max($appCpuLimitLittle, $MIN_CPU_LIMIT)
$appCpuLimitMedium = [math]::Max($appCpuLimitMedium, $MIN_CPU_LIMIT)
$appCpuLimitBig = [math]::Max($appCpuLimitBig, $MIN_CPU_LIMIT)
$appCpuLimitHuge = [math]::Max($appCpuLimitHuge, $MIN_CPU_LIMIT)
# Get the total RAM of the machine in MB
$totalRamBytes = $COMPUTER_INFO | Select-Object -ExpandProperty TotalPhysicalMemory
$totalRamMb = ($totalRamBytes / 1024)
# Load current limits from .env file
$envContent = Get-Content -Path $ENV_FILENAME
$currentAppCpuLimitLittle = ($envContent | Where-Object { $_ -match 'APP_CPU_LIMIT_LITTLE=(.*)' }) -replace 'APP_CPU_LIMIT_LITTLE=', ''
$currentAppCpuLimitMedium = ($envContent | Where-Object { $_ -match 'APP_CPU_LIMIT_MEDIUM=(.*)' }) -replace 'APP_CPU_LIMIT_MEDIUM=', ''
$currentAppCpuLmitBig = ($envContent | Where-Object { $_ -match 'APP_CPU_LIMIT_BIG=(.*)' }) -replace 'APP_CPU_LIMIT_BIG=', ''
$currentAppCpuLimitHuge = ($envContent | Where-Object { $_ -match 'APP_CPU_LIMIT_HUGE=(.*)' }) -replace 'APP_CPU_LIMIT_HUGE=', ''
$currentAppMemReservLittle = ($envContent | Where-Object { $_ -match 'APP_MEM_RESERV_LITTLE=(.*)' }) -replace 'APP_MEM_RESERV_LITTLE=', ''
$currentAppMemLimitLittle = ($envContent | Where-Object { $_ -match 'APP_MEM_LIMIT_LITTLE=(.*)' }) -replace 'APP_MEM_LIMIT_LITTLE=', ''
$currentAppMemReservMedium = ($envContent | Where-Object { $_ -match 'APP_MEM_RESERV_MEDIUM=(.*)' }) -replace 'APP_MEM_RESERV_MEDIUM=', ''
$currentAppMemLimitMedium = ($envContent | Where-Object { $_ -match 'APP_MEM_LIMIT_MEDIUM=(.*)' }) -replace 'APP_MEM_LIMIT_MEDIUM=', ''
$currentAppMemReservBig = ($envContent | Where-Object { $_ -match 'APP_MEM_RESERV_BIG=(.*)' }) -replace 'APP_MEM_RESERV_BIG=', ''
$currentAppMemLimitBig = ($envContent | Where-Object { $_ -match 'APP_MEM_LIMIT_BIG=(.*)' }) -replace 'APP_MEM_LIMIT_BIG=', ''
$currentAppMemReservHuge = ($envContent | Where-Object { $_ -match 'APP_MEM_RESERV_HUGE=(.*)' }) -replace 'APP_MEM_RESERV_HUGE=', ''
$currentAppMemLimitHuge = ($envContent | Where-Object { $_ -match 'APP_MEM_LIMIT_HUGE=(.*)' }) -replace 'APP_MEM_LIMIT_HUGE=', ''
# RAM limits: little should reserve at least MIN_RAM_LIMIT MB or the next near power of 2 in MB of 5% of RAM as upperbound and use as max limit the 250% of this value, medium should reserve double of the little value or the next near power of 2 in MB of 10% of RAM as upperbound and use as max limit the 250% of this value, big should reserve double of the medium value or the next near power of 2 in MB of 20% of RAM as upperbound and use as max limit the 250% of this value, huge should reserve double of the big value or the next near power of 2 in MB of 40% of RAM as upperbound and use as max limit the 400% of this value
# Implementing a cap for high RAM devices reading value from .env.template file it will be like RAM_CAP_MB_DEFAULT=6144m we need the value 6144
$ramCapMbDefault = (Get-Content $ENV_TEMPLATE_FILENAME | Where-Object { $_ -match 'RAM_CAP_MB_DEFAULT=(.*)' }) -replace 'RAM_CAP_MB_DEFAULT=', '' -replace 'm', ''
# Uncomment the following to simulate a specific amount of RAM for the device
# $totalRamMb = 1024
$ramCapMb = If ($totalRamMb -gt $ramCapMbDefault) { $ramCapMbDefault } else { $totalRamMb }
$maxUseRamMb = [math]::Min($totalRamMb, $ramCapMb)
# Calculate new RAM limits
$appMemReservLittle = RoundUpPowerOf2 (($maxUseRamMb * 5 / 100))
$appMemLimitLittle = RoundUpPowerOf2 (($appMemReservLittle * 200 / 100))
$appMemReservMedium = RoundUpPowerOf2 (($maxUseRamMb * 10 / 100))
$appMemLimitMedium = RoundUpPowerOf2 (($appMemReservMedium * 200 / 100))
$appMemReservBig = RoundUpPowerOf2 (($maxUseRamMb * 20 / 100))
$appMemLimitBig = RoundUpPowerOf2 (($appMemReservBig * 200 / 100))
$appMemReservHuge = RoundUpPowerOf2 (($maxUseRamMb * 40 / 100))
$appMemLimitHuge = RoundUpPowerOf2 (($appMemReservHuge * 200 / 100))
# Ensure the calculated values do not exceed RAM_CAP_MB_DEFAULT
$appMemReservLittle = [math]::Min($appMemReservLittle, $ramCapMbDefault)
$appMemLimitLittle = [math]::Min($appMemLimitLittle, $ramCapMbDefault)
$appMemReservMedium = [math]::Min($appMemReservMedium, $ramCapMbDefault)
$appMemLimitMedium = [math]::Min($appMemLimitMedium, $ramCapMbDefault)
$appMemReservBig = [math]::Min($appMemReservBig, $ramCapMbDefault)
$appMemLimitBig = [math]::Min($appMemLimitBig, $ramCapMbDefault)
$appMemReservHuge = [math]::Min($appMemReservHuge, $ramCapMbDefault)
$appMemLimitHuge = [math]::Min($appMemLimitHuge, $ramCapMbDefault)
# Ensure RAM limits are not below minimum
$appMemReservLittle = [math]::Max($appMemReservLittle, $MIN_MEM_LIMIT)
$appMemLimitLittle = [math]::Max($appMemLimitLittle, $MIN_MEM_LIMIT)
$appMemReservMedium = [math]::Max($appMemReservMedium, $MIN_MEM_LIMIT)
$appMemLimitMedium = [math]::Max($appMemLimitMedium, $MIN_MEM_LIMIT)
$appMemReservBig = [math]::Max($appMemReservBig, $MIN_MEM_LIMIT)
$appMemLimitBig = [math]::Max($appMemLimitBig, $MIN_MEM_LIMIT)
$appMemReservHuge = [math]::Max($appMemReservHuge, $MIN_MEM_LIMIT)
$appMemLimitHuge = [math]::Max($appMemLimitHuge, $MIN_MEM_LIMIT)
# Update the CPU limits with the new values
(Get-Content $ENV_FILENAME).Replace("APP_CPU_LIMIT_LITTLE=$currentAppCpuLimitLittle", "APP_CPU_LIMIT_LITTLE=$appCpuLimitLittle") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_CPU_LIMIT_MEDIUM=$currentAppCpuLimitMedium", "APP_CPU_LIMIT_MEDIUM=$appCpuLimitMedium") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_CPU_LIMIT_BIG=$currentAppCpuLmitBig", "APP_CPU_LIMIT_BIG=$appCpuLimitBig") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_CPU_LIMIT_HUGE=$currentAppCpuLimitHuge", "APP_CPU_LIMIT_HUGE=$appCpuLimitHuge") | Set-Content $ENV_FILENAME
# Update RAM limits with the new values unsing as unit MB
(Get-Content $ENV_FILENAME).Replace("APP_MEM_RESERV_LITTLE=$currentAppMemReservLittle", "APP_MEM_RESERV_LITTLE=${appMemReservLittle}m") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_MEM_LIMIT_LITTLE=$currentAppMemLimitLittle", "APP_MEM_LIMIT_LITTLE=${appMemLimitLittle}m") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_MEM_RESERV_MEDIUM=$currentAppMemReservMedium", "APP_MEM_RESERV_MEDIUM=${appMemReservMedium}m") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_MEM_LIMIT_MEDIUM=$currentAppMemLimitMedium", "APP_MEM_LIMIT_MEDIUM=${appMemLimitMedium}m") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_MEM_RESERV_BIG=$currentAppMemReservBig", "APP_MEM_RESERV_BIG=${appMemReservBig}m") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_MEM_LIMIT_BIG=$currentAppMemLimitBig", "APP_MEM_LIMIT_BIG=${appMemLimitBig}m") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_MEM_RESERV_HUGE=$currentAppMemReservHuge", "APP_MEM_RESERV_HUGE=${appMemReservHuge}m") | Set-Content $ENV_FILENAME
(Get-Content $ENV_FILENAME).Replace("APP_MEM_LIMIT_HUGE=$currentAppMemLimitHuge", "APP_MEM_LIMIT_HUGE=${appMemLimitHuge}m") | Set-Content $ENV_FILENAME
# If debug mode is enabled print the calculated limits values
if ($Debug -eq $true) {
print_and_log "DEFAULT" "Total CPUs: $TOTAL_CPUS"
print_and_log "DEFAULT" "APP_CPU_LIMIT_LITTLE: $appCpuLimitLittle"
print_and_log "DEFAULT" "APP_CPU_LIMIT_MEDIUM: $appCpuLimitMedium"
print_and_log "DEFAULT" "APP_CPU_LIMIT_BIG: $appCpuLimitBig"
print_and_log "DEFAULT" "APP_CPU_LIMIT_HUGE: $appCpuLimitHuge"
print_and_log "DEFAULT" "APP_MEM_RESERV_LITTLE: $appMemReservLittle"
print_and_log "DEFAULT" "APP_MEM_LIMIT_LITTLE: $appMemLimitLittle"
print_and_log "DEFAULT" "APP_MEM_RESERV_MEDIUM: $appMemReservMedium"
print_and_log "DEFAULT" "APP_MEM_LIMIT_MEDIUM: $appMemLimitMedium"
print_and_log "DEFAULT" "APP_MEM_RESERV_BIG: $appMemReservBig"
print_and_log "DEFAULT" "APP_MEM_LIMIT_BIG: $appMemLimitBig"
print_and_log "DEFAULT" "APP_MEM_RESERV_HUGE: $appMemReservHuge"
print_and_log "DEFAULT" "APP_MEM_LIMIT_HUGE: $appMemLimitHuge"
#Read-Host -Prompt "Press Enter to continue"
}
}
# Function to check if there are any updates available #
function check_project_updates {
# Get the current script version from the local .env file
$SCRIPT_VERSION_MATCH = (Get-Content .\$ENV_FILENAME | Select-String -Pattern "PROJECT_VERSION=(\d+\.\d+\.\d+)").Matches
if ($SCRIPT_VERSION_MATCH.Count -eq 0) {
errorprint_and_log "Failed to get the script version from the local .env file."
return
}
$SCRIPT_VERSION = $SCRIPT_VERSION_MATCH[0].Groups[1].Value
# Get the latest script version from the .env.template file on GitHub
try {
$webClient = New-Object System.Net.WebClient
$templateContent = $webClient.DownloadString("$PROJECT_URL/$ENV_TEMPLATE_FILENAME")
$LATEST_SCRIPT_VERSION_MATCH = ($templateContent | Select-String -Pattern "PROJECT_VERSION=(\d+\.\d+\.\d+)").Matches
if ($LATEST_SCRIPT_VERSION_MATCH.Count -eq 0) {
errorprint_and_log "Failed to get the latest script version from GitHub."
return
}
$LATEST_SCRIPT_VERSION = $LATEST_SCRIPT_VERSION_MATCH[0].Groups[1].Value
} catch {
print_and_log "Blue" "Updates check failed. Will try again later. Reason: $_"
return
}
# Split the versions into major, minor, and patch numbers
$SCRIPT_VERSION_SPLIT = $SCRIPT_VERSION.Split(".")
$LATEST_SCRIPT_VERSION_SPLIT = $LATEST_SCRIPT_VERSION.Split(".")
# Compare the versions and print a message if a newer version is available
for ($i=0; $i -lt 3; $i++) {
if ([int]$SCRIPT_VERSION_SPLIT[$i] -lt [int]$LATEST_SCRIPT_VERSION_SPLIT[$i]) {
print_and_log "Yellow" "A newer version of the script is available. Please consider updating."
return
}
elseif ([int]$SCRIPT_VERSION_SPLIT[$i] -gt [int]$LATEST_SCRIPT_VERSION_SPLIT[$i]) {
return
}
}
# If the loop completes without finding a newer version, print a message indicating that the script is up to date
print_and_log "BLUE" "Script is up to date."
}
# Function to detect OS
function detect_os {
toLog_ifDebug -l "[DEBUG]" -m "Detecting OS..."
try {
if ($PSVersionTable.Platform) {
$OSStr = $PSVersionTable.Platform.ToString().ToLower()
}
elseif ($env:OS) {
$OSStr = $env:OS.ToString().ToLower()
}
else {
$OSStr = (uname -s).ToLower()
}
# check if OSStr contains any known OS substring
$script:OS_TYPE = $os_map.Keys | Where-Object { $OSStr.Contains($_) } | Select-Object -First 1 | ForEach-Object { $os_map[$_] }
}
catch {
toLog_ifDebug -l "[WARN]" -m "Neither PS OS detection commands nor uname were found, OS detection failed. OS type will be set to 'unknown'."
$script:OS_TYPE = 'unknown'
}
toLog_ifDebug -l "[DEBUG]" -m "OS type detected: $script:OS_TYPE"
}
# Function to detect OS architecture and set the relative Docker architecture
function detect_architecture {
toLog_ifDebug -l "[DEBUG]" -m "Detecting system architecture..."
try {
# Try to use the new PowerShell command
if (Get-Command 'System.Runtime.InteropServices.RuntimeInformation::OSArchitecture' -ErrorAction SilentlyContinue) {
$archStr = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLower()
}
# Fallback to using uname if on a Unix-like system
elseif (Get-Command 'uname' -ErrorAction SilentlyContinue) {
$archStr = (uname -m).ToLower()
}
# Final fallback to older PowerShell/Windows method
else {
$archStr = $env:PROCESSOR_ARCHITECTURE.ToLower()
}
$script:ARCH = $archStr
$script:DKARCH = $arch_map[$archStr]
if ($null -eq $script:DKARCH) {
$script:DKARCH = "unknown"
}
}
catch {
toLog_ifDebug -l "[DEBUG]" -m "Neither PS arch detection commands nor uname were found, architecture detection failed. Architecture will be set to 'unknown'."
$script:ARCH = 'unknown'
$script:DKARCH = 'unknown'
}
toLog_ifDebug -l "[DEBUG]" -m "System architecture detected: $script:ARCH, Docker architecture has been set to $script:DKARCH"
}
# experimanetal function that provide support for installing packages using Chocolatey
function fn_install_packages {
param(
[Parameter(Mandatory = $true)]
[string[]] $REQUIRED_PACKAGES
)
if ($script:OS_TYPE -eq "Windows") {
# Check if Chocolatey is installed
if (-not(Get-Command 'choco' -ErrorAction SilentlyContinue)) {
colorprint "Yellow" "Chocolatey is not installed, this script will now attempt to install it for you."
colorprint "Yellow" "Installing Chocolatey..."
$ProgressPreference = 'SilentlyContinue'
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
$ProgressPreference = 'Continue'
# check if the installation was successful
if (-not(Get-Command 'choco' -ErrorAction SilentlyContinue)) {
fn_fail "Chocolatey installation failed. Please install Chocolatey manually and then try again."
}
colorprint "Green" "Chocolatey installed successfully."
}
# Install required packages
foreach ($package in $REQUIRED_PACKAGES) {
if (-not(choco list --local-only --exact $package)) {
colorprint "Yellow" "$package not installed, Trying to install it now..."
$ProgressPreference = 'SilentlyContinue'
if (-not (choco install $package -y)) {
colorprint "Red" "Failed to install $package. Please install it manually and then try again."
}
$ProgressPreference = 'Continue'
else {
colorprint "Green" "$package installed successfully."
}
}
else {
colorprint "Green" "$package already installed."
}
}
}
elseif ($script:OS_TYPE -eq "MacOS") {
# Check if Homebrew is installed
if (-not(Get-Command 'brew' -ErrorAction SilentlyContinue)) {
colorprint "Yellow" "Homebrew is not installed, this script will now attempt to install it for you."
colorprint "Yellow" "Installing Homebrew..."
$ProgressPreference = 'SilentlyContinue'
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
$ProgressPreference = 'Continue'
# check if the installation was successful
if (-not(Get-Command 'brew' -ErrorAction SilentlyContinue)) {
fn_fail "Homebrew installation failed. Please install Homebrew manually and then try again."
}
else {
colorprint "Green" "Homebrew installed successfully."
}
}
# Install required packages
foreach ($package in $REQUIRED_PACKAGES) {
if (-not(brew list --versions $package)) {
print_and_log "Default" "$package not installed, Trying to install it now..."
$ProgressPreference = 'SilentlyContinue'
if (-not (brew install $package)) {
print_and_log "Failed to install $package. Please install it manually and then try again."
}
$ProgressPreference = 'Continue'
else {
colorprint "Green" "$package installed successfully."
}
}
else {
colorprint "Green" "$package already installed."
}
}
}
elseif ($script:OS_TYPE -eq "Linux") {
# Check which package manager is installed
if (Get-Command apt -ErrorAction SilentlyContinue) {
PKG_MANAGER = "apt"
PKG_CHECK="dpkg -l"
PKG_INSTALL="sudo apt install -y"
}
elseif (Get-Command yum -ErrorAction SilentlyContinue) {
PKG_MANAGER = "yum"
PKG_CHECK="rpm -qa"
PKG_INSTALL="sudo yum install -y"
}
elseif (Get-Command dnf -ErrorAction SilentlyContinue) {
PKG_MANAGER = "dnf"
PKG_CHECK="rpm -q"
PKG_INSTALL="sudo dnf install -y"
}
elseif (Get-Command pacman -ErrorAction SilentlyContinue) {
PKG_MANAGER = "pacman"
PKG_CHECK="pacman -Q"
PKG_INSTALL="sudo pacman -S --noconfirm"
}
elseif (Get-Command zypper -ErrorAction SilentlyContinue) {
PKG_MANAGER = "zypper"
PKG_CHECK="rpm -q"
PKG_INSTALL="sudo zypper install -y"
}
elseif (Get-Command apk -ErrorAction SilentlyContinue) {
PKG_MANAGER = "apk"
PKG_CHECK="apk info"
PKG_INSTALL="sudo apk add"
}
elseif (Get-Command emerge -ErrorAction SilentlyContinue) {
PKG_MANAGER = "emerge"
PKG_CHECK="qlist -I"
PKG_INSTALL="sudo emerge --ask n"
}
else {
print_and_log "Red" "Your package manager has not been recognized by this script. Please install the following packages manually: $($REQUIRED_PACKAGES -join ', ')"
Read-Input -Prompt "Press enter to continue"
return
}
toLog_ifDebug -l "[DEBUG]" -m "Package manager detected: $PKG_MANAGER"
# Install required packages
foreach ($package in $REQUIRED_PACKAGES) {
# Using Invoke-Expression to execute the package check command
if (-not (Invoke-Expression "$PKG_CHECK $package")) {
print_and_log "Default" "$package not installed, Trying to install it now..."
$ProgressPreference = 'SilentlyContinue'
# Using Invoke-Expression to execute the package install command
if (-not (Invoke-Expression "$PKG_INSTALL $package")) {
print_and_log "Red" "Failed to install $package. Please install it manually and then try again."
}
else {
colorprint "Green" "$package installed successfully."
}
$ProgressPreference = 'Continue'
}
else {
colorprint "Green" "$package already installed."
}
}
}
else {
print_and_log "Red" "Your operating system has not been recognized or is not supported by this function. Please install the following packages manually: $($REQUIRED_PACKAGES -join ', ')"
Read-Input -Prompt "Press enter to continue"
return
}
toLog_ifDebug -l "[DEBUG]" -m "Required packages installation completed."
}
### Sub-menu Functions ###
# Shows the liks of the apps
function fn_showLinks {
Clear-Host
toLog_ifDebug -l "[DEBUG]" -m "Showing apps links"
colorprint "Green" "Use CTRL+Click to open links or copy them:"
$configPath = Join-Path -Path $CONFIG_DIR -ChildPath $APP_CONFIG_JSON_FILE
$configData = Get-Content -Path $configPath -Raw | ConvertFrom-Json
# Iterate over the top-level keys (app types) in the JSON
foreach ($appType in $configData.PSObject.Properties.Name) {
colorprint "Yellow" "---$appType---"
# Iterate over the apps in each type
foreach ($app in $configData.$appType) {
colorprint "Default" $app.name
colorprint "Cyan" $app.link
}
}
Read-Host -Prompt "Press Enter to go back to mainmenu"
toLog_ifDebug -l "[DEBUG]" -m "Links shown, going back to main menu."
}
<#
.SYNOPSIS
Function that will attempt to install Docker on different OSs
.DESCRIPTION
This function will attempt to install Docker on different OSs. It will ask the user to choose the OS and then it will launch the appropriate script to install Docker on the selected OS. If Docker is already installed it will ask the user if he wants to proceed with the installation anyway.
.EXAMPLE
Just call fn_dockerInstall
.NOTES
This function has been tested until v 2.0.0 on windows and mac but not on linux yet. The new version has not been tested as its assume that the logic is the same as the previous one just more refined.
#>
function fn_dockerInstall {
Clear-Host
toLog_ifDebug -l "[DEBUG]" -m "DockerInstall function started"
colorprint "Yellow" "This menu item will launch a script that will attempt to install Docker"
colorprint "Yellow" "Use it only if you do not know how to perform the manual Docker installation described at https://docs.docker.com/get-docker/ as the automatic script in some cases and depending on the OS you are using may fail to install Docker correctly."
while ($true) {
$yn = (Read-Host -Prompt "Do you wish to proceed with the Docker automatic installation Y/N?").ToLower()
if ($yn -eq 'y' -or $yn -eq 'yes') {
toLog_ifDebug -l "[DEBUG]" -m "User decided to install Docker through the script. Checking if Docker is already installed."
try {
$dockerVersion = docker --version
if ($dockerVersion) {
toLog_ifDebug -l "[DEBUG]" -m "Docker is already installed. Asking user if he wants to continue with the installation anyway."
while ($true) {
colorprint "Yellow" "Docker seems to be installed already. Do you want to continue with the installation anyway? (Y/N)"
$yn = (Read-Host).ToLower()
if ($yn -eq 'n' -or $yn -eq 'no') {
toLog_ifDebug -l "[DEBUG]" -m "User decided to abort the Docker re-install."
colorprint "Blue" "Returning to main menu..."
Start-Sleep -Seconds $SLEEP_TIME
return
}
elseif ($yn -eq 'y' -or $yn -eq 'yes' ) {
toLog_ifDebug -l "[DEBUG]" -m "User decided to continue with the Docker re-install anyway."
break
}
else {
colorprint "Red" "Please answer yes or no."
}
}
}
}
catch {
print_and_log "DEFAULT" "Proceeding with Docker installation."
}
Clear-Host
print_and_log "Yellow" "Installing Docker for $script:OS_TYPE."
$InstallStatus = $false;
Switch ($script:OS_TYPE) {
"Linux" {
Clear-Host
print_and_log "Yellow" "Starting Docker for Linux auto installation script"
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest https://get.docker.com -o "$SCRIPTS_DIR/get-docker.sh"
$ProgressPreference = 'Continue'
sudo sh get-docker.sh;
$InstallStatus = $true;
}
"Windows" {
Clear-Host
print_and_log "Yellow" "Starting Docker for Windows auto installation script"
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest $DKINST_WIN_SRC -o "$SCRIPTS_DIR\install-docker-win.ps1"
$ProgressPreference = 'Continue'
Start-Process PowerShell -Verb RunAs "-noprofile -executionpolicy bypass -command `"$SCRIPTS_DIR\install-docker-win.ps1 -filesPath $FILES_DIR`"" -Wait
$InstallStatus = $true;
}
"MacOS" {
Clear-Host
print_and_log "Yellow" "Starting Docker for MacOS auto installation script"
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest $DKINST_MAC_SRC -o "$SCRIPTS_DIR\install-docker-mac.ps1"
$ProgressPreference = 'Continue'
colorprint "Yellow" "Select your CPU type"
colorprint "Yellow" "1) Apple silicon M1, M2...CPUs"
colorprint "Yellow" "2) Intel i5, i7...CPUs"
$cpuSel = Read-Host
switch ($cpuSel) {
1 {
Start-Process PowerShell -Verb RunAs "-noprofile -executionpolicy bypass -command `"$SCRIPTS_DIR\install-docker-mac.ps1 -filesPath $FILES_DIR`"" -Wait
$InstallStatus = $true;
}
2 {
Start-Process PowerShell -Verb RunAs "-noprofile -executionpolicy bypass -command `"$SCRIPTS_DIR\install-docker-mac.ps1 -filesPath $FILES_DIR -IntelCPU `"" -Wait
$InstallStatus = $true;
}
Default { fn_unknown "$cpuSel" }
}
}
DEFAULT {
print_and_log "Red" "Your operating system (${OSTYPE}) has not been recognized or is not supported by this function. Please install Docker manually and then try again."
}
}
if ($InstallStatus) {
colorprint "Green" "Script completed. If no errors appeared Docker should be installed. Please restart your machine and then proceed to ${ENV_FILENAME} file config and stack startup."
}
else {
colorprint "Red" "Something went wrong (maybe bad choice or incomplete installation), failed to install Docker automatically. Please try to install Docker manually by following the instructions on Docker website."
}
Read-Host -Prompt "Press enter to go back to mainmenu"
break
}
elseif ($yn -eq 'n' -or $yn -eq 'no') {
Clear-Host
colorprint "Blue" "Docker unattended installation canceled. Make sure you have Docker installed before proceeding with the other steps."
Read-Host -prompt "Press enter to go back to the menu"
return
}
else {
colorprint "Red" "Please answer yes or no."
}
}
}
<#
.SYNOPSIS
Function that will setup notifications about containers updates using shoutrrr
.DESCRIPTION
This function will setup notifications about containers updates using shoutrrr. It will ask the user to enter a link for notifications and then it will update the ${ENV_FILENAME} file and the docker-compose.yaml file accordingly.
.EXAMPLE
Just call fn_setupNotifications
.NOTES
This function has been tested until v 2.0.0. The new version has not been tested as its assume that the logic is the same as the previous one just more refined.
#>
function fn_setupNotifications {
toLog_ifDebug -l "[DEBUG]" -m "SetupNotifications function started"
Clear-Host
while ($true) {
colorprint "Yellow" "Do you wish to setup notifications about apps images updates (Yes to receive notifications and apply updates, No to just silently apply updates) Y/N?"
$yn = Read-Host
$yn = $yn.ToLower()
if ($yn -eq 'y' -or $yn -eq 'yes') {
toLog_ifDebug -l "[DEBUG]" -m "User decided to setup notifications about apps images updates."
colorprint "Yellow" "This step will setup notifications about containers updates using shoutrrr"
colorprint "Default" "The resulting SHOUTRRR_URL should have the format: <app>://<token>@<webhook>."
colorprint "Default" "Where <app> is one of the supported messaging apps on Shoutrrr (e.g. Discord), and <token> and <webhook> are specific to your messaging app."
colorprint "Default" "To obtain the SHOUTRRR_URL, create a new webhook for your messaging app and rearrange its URL to match the format above."
colorprint "Default" "For more details, visit https://containrrr.dev/shoutrrr/ and select your messaging app."
colorprint "Default" "Now a Discord notification setup example will be shown (Remember: you can also use a different supported app)."
Read-Host -Prompt "Press enter to continue"
Clear-Host
colorprint "magenta" "Create a new Discord server, go to server settings > integrations, and create a webhook."
colorprint "magenta" "Your Discord Webhook-URL will look like this: https://discordapp.com/api/webhooks/YourWebhookid/YourToken."
colorprint "magenta" "To obtain the SHOUTRRR_URL, rearrange it to look like this: discord://YourToken@YourWebhookid."
Read-Host -Prompt "Press enter to proceed with the setup"
Clear-Host
while ($true) {
colorprint "Yellow" "NOW INSERT BELOW THE LINK FOR NOTIFICATIONS using THE SAME FORMAT WRITTEN ABOVE e.g.: discord://yourToken@yourWebhookid"
$SHOUTRRR_URL = Read-Host
if ($SHOUTRRR_URL -match '^[a-zA-Z]+://') {
# Replace the lines in ${ENV_FILENAME} and $DKCOM_FILENAME
(Get-Content .\${ENV_FILENAME}).replace('# SHOUTRRR_URL=', "SHOUTRRR_URL=") | Set-Content .\${ENV_FILENAME}
$CURRENT_VALUE = (Get-Content .\${ENV_FILENAME} | Select-String -Pattern "SHOUTRRR_URL=" -SimpleMatch).ToString().Split("=")[1]
(Get-Content .\${ENV_FILENAME}).replace("SHOUTRRR_URL=${CURRENT_VALUE}", "SHOUTRRR_URL=${SHOUTRRR_URL}") | Set-Content .\${ENV_FILENAME}
(Get-Content .\$DKCOM_FILENAME).replace('# - WATCHTOWER_NOTIFICATIONS=shoutrrr', "- WATCHTOWER_NOTIFICATIONS=shoutrrr") | Set-Content .\$DKCOM_FILENAME
(Get-Content .\$DKCOM_FILENAME).replace('# - WATCHTOWER_NOTIFICATION_URL', "- WATCHTOWER_NOTIFICATION_URL") | Set-Content .\$DKCOM_FILENAME
(Get-Content .\${ENV_FILENAME}).replace("NOTIFICATIONS_CONFIGURATION_STATUS=0", "NOTIFICATIONS_CONFIGURATION_STATUS=1") | Set-Content .\${ENV_FILENAME}
colorprint "DEFAULT" "Notifications setup complete. If the link is correct, you will receive a notification for each update made on the app container images."
Read-Host -p "Press enter to continue"
break
}
else {
colorprint "Red" "Invalid link format. Please make sure to use the correct format."
while ($true) {
colorprint "Yellow" "Do you wish to try again or leave the notifications disabled and continue with the setup script? (Yes to try again, No to continue without notifications) Y/N?"
$yn = Read-Host
$yn = $yn.ToLower()
if ($yn -eq 'y' -or $yn -eq 'yes') {
break
}
elseif ($yn -eq 'n' -or $yn -eq 'no') {
toLog_ifDebug -l "[DEBUG]" -m "User choose to not retry the notifications setup. Notifications wsetup will now return"
colorprint "Blue" "Noted: all updates will be applied automatically and silently"
Start-Sleep -Seconds $SLEEP_TIME
return
}
else {
colorprint "Red" "Please answer yes or no."
}
}
}
}
break
}
elseif ($yn -eq 'n' -or $yn -eq 'no') {
toLog_ifDebug -l "[DEBUG]" -m "User choose to skip notifications setup"
colorprint "Blue" "Noted: all updates will be applied automatically and silently"
Start-Sleep -Seconds $SLEEP_TIME
break
}
else {
colorprint "Red" "Please answer yes or no."
}
}
Clear-Host
toLog_ifDebug -l "[DEBUG]" -m "Notifications setup ended."
}
<#
.SYNOPSIS
This function will manage the setup of each app in the stack
.DESCRIPTION
This function will manage the setup of each app in the stack. It will ask the user to enter the required data for each app and then it will update the ${ENV_FILENAME} file and the docker-compose.yaml file accordingly.
.PARAMETER app
App name and image are required parameters. The app name is used to identify the app in the setup process.
.PARAMETER image
the image is used to feryfy if the image supports the current architecture and to update the docker-compose.yaml file accordingly.
.PARAMETER flags
Optional parameter. If the app requires an email to be setup, this parameter will be used to update the ${ENV_FILENAME} file.
.EXAMPLE
fn_setupApp -app "HONEYGAIN" -image "honeygain/honeygain" -email "email" -password "password"
.NOTES
This function has been tested until v 2.0.0. The new version has not been tested as its assume that the logic is the same as the previous one just more refined.
#>
function fn_setupApp() {
param(
[Parameter(Mandatory = $true)]
[string]$app_json,
[Parameter(Mandatory = $false)]
[string]$dk_compose_filename = "docker-compose.yaml"
)
toLog_ifDebug -l "[DEBUG]" -m "SetupApp function started"
toLog_ifDebug -l "[DEBUG]" -m "SetupApp function parameters: app_json=$app_json, dk_compose_filename=$dk_compose_filename"
$app_json_obj = $app_json | ConvertFrom-Json
$name = $app_json_obj.name
$link = $app_json_obj.link
$app_image = $app_json_obj.image
$flags_raw = $app_json_obj.flags.PSObject.Properties.Name
$flags = @()
foreach ($flag in $flags_raw) {
$flags += $flag
}
$claimURLBase = if ($app_json_obj.claimURLBase) { $app_json_obj.claimURLBase } else { $link }
$CURRENT_APP = $name.ToUpper()
while ($true) {
# Check if the ${CURRENT_APP} is already enabled in the ${dk_compose_filename} file and if it is not (if there is a #ENABLE_$CURRENTAPP) then ask the user if they want to enable it
toLog_ifDebug -l "[DEBUG]" -m "Checking if the ${CURRENT_APP} app is already enabled in the ${dk_compose_filename} file"
if ((Get-content $dk_compose_filename) -match "#ENABLE_${CURRENT_APP}") {
toLog_ifDebug -l "[DEBUG]" -m "The ${CURRENT_APP} app is not enabled in the ${dk_compose_filename} file, asking user if they want to enable it"
# Show the generic message before asking the user if they want to enable the app
colorprint "YELLOW" "PLEASE REGISTER ON THE PLATFORMS USING THE LINKS THAT WILL BE PROVIDED, YOU'LL THEN NEED TO ENTER SOME DATA BELOW:"
# Ask the user if they want to enable the ${CURRENT_APP}
colorprint "Yellow" "Do you wish to enable the ${CURRENT_APP} app? (Y/N)"
$yn = Read-Host
$yn = $yn.ToLower()
if ($yn -eq 'y' -or $yn -eq 'yes') {
toLog_ifDebug -l "[DEBUG]" -m "User decided to enable the ${CURRENT_APP} app"
colorprint "Cyan" "Go to ${CURRENT_APP} ${link} and register"
colorprint "Green" "Use CTRL+Click to open links or copy them:"
Read-Host -Prompt "When you are done press Enter to continue"
toLog_ifDebug -l "[DEBUG]" -m "Enabling ${CURRENT_APP} app. The parameters received are: name=$name, link=$link, image=$app_image, flags=$flags, claimURLBase=$claimURLBase"
# Read the flags in the array and execute the relative logic using the case statement
foreach ($flag_name in $flags) {
#$flag_details = ($app_json_obj.flags | Get-Member -MemberType NoteProperty | Where-Object { $_.Name -eq $flag_name }).Value
$flag_details = $app_json_obj.flags.$flag_name
toLog_ifDebug -l "[DEBUG]" -m "Result of flag_details reading: $flag_details"
if ($null -ne $flag_details) {
$flag_params_keys = $flag_details.PSObject.Properties.Name
toLog_ifDebug -l "[DEBUG]" -m "Result of flag_params_keys reading: $flag_params_keys"
}
else {
toLog_ifDebug -l "[DEBUG]" -m "No flag details found for flag: $flag_name"
}
switch ($flag_name) {
"--email" {
toLog_ifDebug -l "[DEBUG]" -m "Starting email setup for ${CURRENT_APP} app"
while ($true) {
colorprint "GREEN" "Enter your ${CURRENT_APP} Email:"
$APP_EMAIL = Read-Host
if ($APP_EMAIL -match '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,}$') {
(Get-Content ${ENV_FILENAME}) -replace "your${CURRENT_APP}Mail", $APP_EMAIL | Set-Content ${ENV_FILENAME}
break
}
else {
colorprint "RED" "Invalid email address. Please try again."
}
}
}
"--password" {
toLog_ifDebug -l "[DEBUG]" -m "Starting password setup for ${CURRENT_APP} app"
while ($true) {
colorprint "DEFAULT" "Note: If you are using login with Google, remember to set also a password for your ${CURRENT_APP} account!"
colorprint "GREEN" "Enter your ${CURRENT_APP} Password:"
$APP_PASSWORD = Read-Host
if ($APP_PASSWORD) {
(Get-Content ${ENV_FILENAME}) -replace "your${CURRENT_APP}Pw", $APP_PASSWORD | Set-Content ${ENV_FILENAME}
break
}
else {
colorprint "RED" "Password cannot be empty. Please try again."
}
}
}
"--apikey" {
toLog_ifDebug -l "[DEBUG]" -m "Starting APIKey setup for ${CURRENT_APP} app"
while ($true) {
colorprint "DEFAULT" "Find/Generate your APIKey inside your ${CURRENT_APP} dashboard/profile."
colorprint "GREEN" "Enter your ${CURRENT_APP} APIKey:"
$APP_APIKEY = Read-Host
if ($APP_APIKEY) {
(Get-Content ${ENV_FILENAME}) -replace "your${CURRENT_APP}APIKey", $APP_APIKEY | Set-Content ${ENV_FILENAME}
break
}
else {
colorprint "RED" "APIKey cannot be empty. Please try again."
}
}
}
"--userid" {
toLog_ifDebug -l "[DEBUG]" -m "Starting UserID setup for ${CURRENT_APP} app"
while ($true) {
colorprint "DEFAULT" "Find your UserID inside your ${CURRENT_APP} dashboard/profile."
colorprint "GREEN" "Enter your ${CURRENT_APP} UserID:"
$APP_USERID = Read-Host
if ($APP_USERID) {
(Get-Content ${ENV_FILENAME}) -replace "your${CURRENT_APP}UserID", $APP_USERID | Set-Content ${ENV_FILENAME}
break
}
else {
colorprint "RED" "UserID cannot be empty. Please try again."
}
}
}
"--uuid" {
toLog_ifDebug -l "[DEBUG]" -m "Starting UUID setup for ${CURRENT_APP} app"
colorprint "DEFAULT" "Starting UUID generation/import for ${CURRENT_APP}"
# Read all the parameters for the uuid flag , if one of them is the case length then save it in a variable
if ($null -ne $flag_params_keys) {
foreach ($flag_param_key in $flag_params_keys) {
toLog_ifDebug -l "[DEBUG]" -m "Reading flag parameter: $flag_param_key"
switch ($flag_param_key) {
'length' {
toLog_ifDebug -l "[DEBUG]" -m "Reading flag parameter length"
$flag_length_param = $app_json_obj.flags.$flag_name.$flag_param_key
toLog_ifDebug -l "[DEBUG]" -m "Result of flag_length_param reading: $flag_length_param"
}
default {
toLog_ifDebug -l "[DEBUG]" -m "Unknown flag parameter: $flag_param_key"
}
}
}
}
else {
toLog_ifDebug -l "[DEBUG]" -m "No flag parameters found for flag: $flag_name as flag_params_keys array is empty"
}
# Check if the flag_length_param exists and if is a number (i.e., the desired length)
if (($null -ne $flag_length_param) -and ($flag_length_param -match "^\d+$")) {
$DESIRED_LENGTH = $flag_length_param
toLog_ifDebug -l "[DEBUG]" -m "Desired length for UUID generation/import passed as argument of the uuid flag (read from json), its value is: $DESIRED_LENGTH"
}
else {
# If no length is provided, ask the user
toLog_ifDebug -l "[DEBUG]" -m "No desired length for UUID generation/import passed as argument of the uuid flag, asking the user"
colorprint "GREEN" "Enter desired length for the UUID (default is 32, press Enter to use default):"
$DESIRED_LENGTH_INPUT = Read-Host
$DESIRED_LENGTH = if ($DESIRED_LENGTH_INPUT) { $DESIRED_LENGTH_INPUT } else { 32 } # Defaulting to 32 if no input provided