forked from ExtremeFiretop/MerlinAutoUpdate-Router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerlinAU.sh
More file actions
12121 lines (10823 loc) · 423 KB
/
MerlinAU.sh
File metadata and controls
12121 lines (10823 loc) · 423 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/sh
###################################################################
# MerlinAU.sh (MerlinAutoUpdate)
#
# Original Creation Date: 2023-Oct-01 by @ExtremeFiretop.
# Official Co-Author: @Martinski W. - Date: 2023-Nov-01
# Last Modified: 2026-Apr-08
###################################################################
set -u
## Set version for each Production Release ##
readonly SCRIPT_VERSION=1.6.1
readonly SCRIPT_VERSTAG="26040823"
readonly SCRIPT_NAME="MerlinAU"
## Set to "master" for Production Releases ##
SCRIPT_BRANCH="master"
##----------------------------------------##
## Modified by Martinski W. [2024-Jul-03] ##
##----------------------------------------##
# Script URL Info #
readonly SCRIPT_URL_BASE="https://raw.githubusercontent.com/ExtremeFiretop/MerlinAutoUpdate-Router"
SCRIPT_URL_REPO="${SCRIPT_URL_BASE}/$SCRIPT_BRANCH"
# Firmware URL Info #
readonly FW_SFURL_BASE="https://sourceforge.net/projects/asuswrt-merlin/files"
readonly FW_SFURL_RELEASE_SUFFIX="Release"
readonly FW_GITURL_RELEASE="https://api.github.com/repos/gnuton/asuswrt-merlin.ng/releases/latest"
##----------------------------------------##
## Modified by Martinski W. [2024-May-31] ##
##----------------------------------------##
# Changelog Info #
readonly CL_URL_NG="${FW_SFURL_BASE}/Documentation/Changelog-NG.txt/download"
readonly CL_URL_386="${FW_SFURL_BASE}/Documentation/Changelog-386.txt/download"
readonly CL_URL_3006="${FW_SFURL_BASE}/Documentation/Changelog-3006.txt/download"
readonly high_risk_terms="factory default reset|features are disabled|break backward compatibility|must be manually|strongly recommended"
##----------------------------------------##
## Modified by Martinski W. [2025-Mar-24] ##
##----------------------------------------##
# For new script version updates from source repository #
DLRepoVersion=""
DLRepoVersionNum=""
DLRepoBuildNum=0
ScriptBuildNum=0
ScriptVersionNum=""
scriptUpdateNotify=0
# For router model check #
routerModelCheckFailed=false
offlineUpdateTrigger=false
# To support automatic script updates from AMTM #
doScriptUpdateFromAMTM=true
##----------------------------------------##
## Modified by Martinski W. [2025-Feb-18] ##
##----------------------------------------##
readonly NOct="\e[0m"
readonly BOLDct="\e[1m"
readonly BLKct="\e[1;30m"
readonly REDct="\e[1;31m"
readonly GRNct="\e[1;32m"
readonly YLWct="\e[1;33m"
readonly BLUEct="\e[1;34m"
readonly MGNTct="\e[1;35m" #Magenta#
readonly CYANct="\e[1;36m"
readonly WHITEct="\e[1;37m"
readonly CRITct="\e[1;41m"
readonly InvREDct="\e[41m"
readonly InvGRNct="\e[42m"
readonly InvMGNct="\e[45m"
readonly InvBREDct="\e[30;101m"
readonly InvBGRNct="\e[30;102m"
readonly InvBYLWct="\e[30;103m"
readonly InvBMGNct="\e[30;105m"
readonly ScriptFileName="${0##*/}"
readonly ScriptFNameTag="${ScriptFileName%%.*}"
readonly ScriptDirNameD="${ScriptFNameTag}.d"
if [ "$SCRIPT_BRANCH" = "master" ]
then readonly branchxStr_TAG="[Branch: $SCRIPT_BRANCH]"
else readonly branchxStr_TAG="[Branch: development]"
fi
readonly versionDev_TAG="${SCRIPT_VERSION}_${SCRIPT_VERSTAG}"
##----------------------------------------##
## Modified by Martinski W. [2025-Jan-15] ##
##----------------------------------------##
readonly ADDONS_PATH="/jffs/addons"
readonly SCRIPTS_PATH="/jffs/scripts"
readonly SETTINGS_DIR="${ADDONS_PATH}/$ScriptDirNameD"
readonly CONFIG_FILE="${SETTINGS_DIR}/custom_settings.txt"
readonly SCRIPT_VERPATH="${SETTINGS_DIR}/version.txt"
readonly HELPER_JSFILE="${SETTINGS_DIR}/CheckHelper.js"
readonly PSWD_CHECK_JS="${SETTINGS_DIR}/PswdCheckStatus.js"
readonly CHANGELOG_PATH="${SETTINGS_DIR}/changelog.txt"
readonly SHARED_SETTINGS_FILE="${ADDONS_PATH}/custom_settings.txt"
readonly SHARED_WEB_DIR="$(readlink -f /www/user)"
readonly SCRIPT_WEB_DIR="${SHARED_WEB_DIR}/$SCRIPT_NAME"
readonly SCRIPT_WEB_ASP_FILE="${SCRIPT_NAME}.asp"
readonly SCRIPT_WEB_ASP_PATH="$SETTINGS_DIR/$SCRIPT_WEB_ASP_FILE"
readonly TEMP_MENU_TREE="/tmp/menuTree.js"
readonly ORIG_MENU_TREE="/www/require/modules/menuTree.js"
readonly WEBUI_LOCKFD=386
readonly WEBUI_LOCKFILE="/tmp/addonwebui.lock"
readonly TEMPFILE="/tmp/MerlinAU_settings_$$.txt"
readonly webPageFileRegExp="user([1-9]|[1-2][0-9])[.]asp"
readonly webPageLineTabExp="\{url: \"$webPageFileRegExp\", tabName: "
readonly webPageLineRegExp="${webPageLineTabExp}\"$SCRIPT_NAME\"\},"
# Give FIRST priority to built-in binaries over any other #
export PATH="/bin:/usr/bin:/sbin:/usr/sbin:$PATH"
##-------------------------------------##
## Added by Martinski W. [2024-Sep-15] ##
##-------------------------------------##
# For handling 3rd-party add-on cron jobs #
readonly USB_OPT_DIRPATH1="/opt"
readonly USB_OPT_DIRPATH2="/tmp/opt"
readonly USB_MNT_DIRPATH1="/mnt"
readonly USB_MNT_DIRPATH2="/tmp/mnt"
readonly cronJobsRegEx1="[[:blank:]]+${ADDONS_PATH}/.* "
readonly cronJobsRegEx2="[[:blank:]]+${SCRIPTS_PATH}/.* "
readonly cronJobsRegEx3="[[:blank:]]+${USB_OPT_DIRPATH1}/.* "
readonly cronJobsRegEx4="[[:blank:]]+${USB_OPT_DIRPATH2}/.* "
readonly cronJobsRegEx5="[[:blank:]]+${USB_MNT_DIRPATH1}/.* "
readonly cronJobsRegEx6="[[:blank:]]+${USB_MNT_DIRPATH2}/.* "
readonly addonCronJobList="/home/root/addonCronJobList_$$.txt"
##----------------------------------------##
## Modified by Martinski W. [2024-Jun-05] ##
##----------------------------------------##
ScriptsDirPath="$SCRIPTS_PATH"
ScriptFilePath="${SCRIPTS_PATH}/${SCRIPT_NAME}.sh"
if [ ! -f "$ScriptFilePath" ]
then
ScriptsDirPath="$(pwd)"
ScriptFilePath="$(pwd)/$ScriptFileName"
fi
##------------------------------------------##
## Modified by ExtremeFiretop [2024-Dec-21] ##
##------------------------------------------##
#-------------------------------------------------------#
# We'll use the built-in AMTM email configuration file
# to send email notifications *IF* enabled by the user.
#-------------------------------------------------------#
readonly FW_UpdateEMailFormatTypeDefault=HTML
readonly FW_UpdateEMailNotificationDefault=DISABLED
readonly amtmMailDirPath="/jffs/addons/amtm/mail"
readonly amtmMailConfFile="${amtmMailDirPath}/email.conf"
readonly amtmMailPswdFile="${amtmMailDirPath}/emailpw.enc"
readonly tempEMailContent="/tmp/var/tmp/tempEMailContent.$$.TXT"
readonly tempNodeEMailList="/tmp/var/tmp/tempNodeEMailList.$$.TXT"
readonly tempEMailBodyMsg="/tmp/var/tmp/tempEMailBodyMsg.$$.TXT"
readonly saveEMailInfoMsg="${SETTINGS_DIR}/savedEMailInfoMsg.SAVE.TXT"
readonly theEMailDateTimeFormat="%Y-%b-%d %a %I:%M:%S %p %Z"
if [ -z "$(which crontab)" ]
then cronListCmd="cru l"
else cronListCmd="crontab -l"
fi
##----------------------------------------##
## Modified by Martinski W. [2025-Jan-22] ##
##----------------------------------------##
inMenuMode=true
webguiMode=false
isVerbose=false
isInteractive=false
FlashStarted=false
MerlinChangeLogURL=""
GnutonChangeLogURL=""
keepConfigFile=false
bypassPostponedDays=false
runLoginCredentialsTest=false
# Main LAN Network Info #
readonly myLAN_HostName="$(nvram get lan_hostname)"
readonly mainLAN_IFname="$(nvram get lan_ifname)"
readonly mainLAN_IPaddr="$(nvram get lan_ipaddr)"
readonly mainNET_IPaddr="$(ip route show | grep -E "[[:blank:]]+dev[[:blank:]]+${mainLAN_IFname}[[:blank:]]+proto[[:blank:]]+" | awk -F ' ' '{print $1}')"
# RegExp for IPv4 address #
readonly IPv4octet_RegEx="([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
readonly IPv4addrs_RegEx="(${IPv4octet_RegEx}\.){3}${IPv4octet_RegEx}"
readonly IPv4privt_RegEx="(^10\.|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-1]\.|^192\.168\.)"
##----------------------------------------##
## Modified by Martinski W. [2024-Oct-03] ##
##----------------------------------------##
readonly fwInstalledBaseVers="$(nvram get firmver | sed 's/\.//g')"
readonly fwInstalledBuildVers="$(nvram get buildno)"
readonly fwInstalledExtendNum="$(nvram get extendno)"
readonly fwInstalledInnerVers="$(nvram get innerver)"
readonly fwInstalledBranchVer="${fwInstalledBaseVers}.$(echo "$fwInstalledBuildVers" | awk -F'.' '{print $1}')"
##------------------------------------------##
## Modified by ExtremeFiretop [2026-Jan-23] ##
##------------------------------------------##
# For minimum supported firmware version check.
# *NOTE*: Due to Gnuton F/W being behind RMerlin
# F/W releases, remove support for F/W versions
# that are 5 builds behind the latest production.
#------------------------------------------------#
MinFirmwareVerCheckFailed=false
NewMinSupportedFirmwareVers="TBD"
readonly MinSupportedFW_3004_386_Ver="3004.386.13.2"
readonly MinSupportedFW_3004_388_Ver="3004.388.9.2"
readonly MinSupportedFW_3006_102_Ver="3004.388.8.4"
##----------------------------------------##
## Modified by Martinski W. [2025-Apr-09] ##
##----------------------------------------##
case "$fwInstalledBranchVer" in
"3004.386") MinSupportedFirmwareVers="$MinSupportedFW_3004_386_Ver" ;;
"3004.388") MinSupportedFirmwareVers="$MinSupportedFW_3004_388_Ver" ;;
"3006.102") MinSupportedFirmwareVers="$MinSupportedFW_3006_102_Ver" ;;
*) MinSupportedFirmwareVers="$MinSupportedFW_3004_386_Ver"
esac
##----------------------------------------##
## Modified by Martinski W. [2025-Mar-19] ##
##----------------------------------------##
aiMeshNodes_OK=false
mountWebGUI_OK=false
inMainRouterMode=false
inAccessPointMode=false
readonly nvramSWmode="$(nvram get sw_mode)"
if [ "$nvramSWmode" = "1" ]
then
mountWebGUI_OK=true
aiMeshNodes_OK=true
inMainRouterMode=true
else
if [ "$nvramSWmode" = "3" ] && \
[ "$(nvram get wlc_psta)" = "0" ]
then
mountWebGUI_OK=true
aiMeshNodes_OK=false
inAccessPointMode=true
fi
fi
readonly mainMenuReturnPromptStr="Press <Enter> to return to the Main Menu..."
readonly advnMenuReturnPromptStr="Press <Enter> to return to the Advanced Options Menu..."
readonly logsMenuReturnPromptStr="Press <Enter> to return to the Log Options Menu..."
theMenuReturnPromptMsg="$mainMenuReturnPromptStr"
readonly SEPstr="----------------------------------------------------------"
##-------------------------------------##
## Added by Martinski W. [2024-Nov-24] ##
##-------------------------------------##
# menu setup variables #
readonly padStr=" "
readonly theExitStr="${GRNct}e${NOct}=Exit to Main Menu"
readonly theMUExitStr="${GRNct}e${NOct}=Exit"
readonly theADExitStr="${GRNct}e${NOct}=Exit to Advanced Options Menu"
readonly theLGExitStr="${GRNct}e${NOct}=Exit to Log Options Menu"
readonly menuCancelAndExitStr="${GRNct}e${NOct}=Exit Menu"
readonly menuSavedThenExitStr="${GRNct}s${NOct}=Save&Exit"
readonly menuReturnToBeginStr="${GRNct}b${NOct}=Back to Top"
##-------------------------------------##
## Added by Martinski W. [2024-Aug-15] ##
##-------------------------------------##
routerLoginFailureMsg="Please try the following:
1. Confirm that you are *not* already logged into the router webGUI using a web browser.
2. Check that the \"Enable Access Restrictions\" option from the webGUI is *not* set up
to restrict access to the router webGUI from the router's IP address [${GRNct}${mainLAN_IPaddr}${NOct}].
3. Confirm your password via the \"Set Router Login Password\" option from the Main Menu."
if [ -t 0 ] && ! tty | grep -qwi "NOT"
then
isInteractive=true ; isVerbose=true
fi
##----------------------------------------##
## Modified by Martinski W. [2023-Dec-23] ##
##----------------------------------------##
userLOGFile=""
userTraceFile="${SETTINGS_DIR}/${ScriptFNameTag}_Trace.LOG"
userDebugFile="${SETTINGS_DIR}/${ScriptFNameTag}_Debug.LOG"
LOGdateFormat="%Y-%m-%d %H:%M:%S"
_LogMsgNoTime_() { _UserLogMsg_ "_NOTIME_" "$@" ; }
_UserTraceLog_()
{
local logTime="$(date +"$LOGdateFormat")"
if [ $# -eq 0 ] || [ -z "$1" ]
then
echo >> "$userTraceFile"
elif [ $# -eq 1 ]
then
echo "$logTime" "$1" >> "$userTraceFile"
elif [ "$1" = "_NOTIME_" ]
then
echo "$2" >> "$userTraceFile"
else
echo "$logTime" "${1}: $2" >> "$userTraceFile"
fi
}
_UserLogMsg_()
{
if [ -z "$userLOGFile" ] || [ ! -f "$userLOGFile" ]
then return 1 ; fi
local logTime="$(date +"$LOGdateFormat")"
if [ $# -eq 0 ] || [ -z "$1" ]
then
echo >> "$userLOGFile"
elif [ $# -eq 1 ]
then
echo "$logTime" "$1" >> "$userLOGFile"
elif [ "$1" = "_NOTIME_" ]
then
echo "$2" >> "$userLOGFile"
else
echo "$logTime" "${1}: $2" >> "$userLOGFile"
fi
}
##-------------------------------------##
## Added by Martinski W. [2026-Feb-22] ##
##-------------------------------------##
DoPrintf()
{
if "$isInteractive" && "$isVerbose"
then printf "$@"
fi
}
##----------------------------------------##
## Modified by Martinski W. [2026-Feb-22] ##
##----------------------------------------##
Say()
{
local logMsg
DoPrintf "${1}\n"
# Remove all "color escape sequences" from the system log file entries #
logMsg="$(echo "$1" | \
sed 's/\\e\[[0-1]m//g; s/\\e\[[3-4][0-9]m//g; s/\\e\[[0-1];[3-4][0-9]m//g; s/\\e\[30;10[1-9]m//g; s/\\n/ /g')"
_UserLogMsg_ "$logMsg"
printf "$logMsg" | logger -t "${SCRIPT_NAME}_[$$]"
}
##----------------------------------------##
## Modified by Martinski W. [2023-Nov-20] ##
##----------------------------------------##
_WaitForEnterKey_()
{
! "$isInteractive" && return 0
local promptStr
if [ $# -gt 0 ] && [ -n "$1" ]
then promptStr="$1"
else promptStr="Press <Enter> to continue..."
fi
printf "\n$promptStr"
read -rs EnterKEY ; echo
}
##-------------------------------------##
## Modified Martinski W. [2025-Feb-18] ##
##-------------------------------------##
_WaitForYESorNO_()
{
local defltCode=0 defltAnswer=NO promptStr
if [ $# -eq 0 ]
then defltCode=0 ; defltAnswer=NO
elif [ "$1" = "NO" ]
then defltCode=1 ; defltAnswer=NO
elif [ "$1" = "YES" ]
then defltCode=0 ; defltAnswer=YES
fi
! "$isInteractive" && return "$defltCode"
if [ $# -eq 0 ] || [ -z "$1" ] || \
echo "$1" | grep -qE "^(YES|NO)$"
then promptStr=" [yY|nN]? "
else promptStr="$1 [yY|nN]? "
fi
printf "$promptStr" ; read -r YESorNO
[ -z "$YESorNO" ] && YESorNO="$defltAnswer"
if echo "$YESorNO" | grep -qE "^([Yy](es)?|YES)$"
then echo "OK" ; return 0
else echo "NO" ; return 1
fi
}
##----------------------------------------##
## Modified by Martinski W. [2025-Jan-11] ##
##----------------------------------------##
readonly LockFilePath="/tmp/var/${ScriptFNameTag}.LOCK"
readonly LockTypeRegEx="(cliMenuLock|cliOptsLock|cliFileLock)"
_FindLockFileTypes_()
{ grep -woE "$LockTypeRegEx" "$LockFilePath" | tr '\n' ' ' | sed 's/[ ]*$//' ; }
_ReleaseLock_()
{
local lockType
if [ $# -eq 0 ] || [ -z "$1" ]
then lockType=""
else lockType="$1"
fi
if [ -s "$LockFilePath" ] && \
[ "$(wc -l < "$LockFilePath")" -gt 1 ]
then
if [ -z "$lockType" ]
then sed -i "/^$$|/d" "$LockFilePath"
else sed -i "/^$$|${1}$/d" "$LockFilePath"
fi
[ -s "$LockFilePath" ] && return 0
fi
rm -f "$LockFilePath"
}
## Defaults ##
LockSleepDelaySecs=5
LockMaxTimeoutSecs=120
LockFileMaxAgeSecs=600 #10-minutes#
if [ $# -eq 0 ] || [ -z "$1" ]
then
#Interactive Mode#
LockMaxTimeoutSecs=3
LockFileMaxAgeSecs=1200
else
case "$1" in
run_now|amtmupdate|resetLockFile)
LockSleepDelaySecs=2
LockMaxTimeoutSecs=1
LockFileMaxAgeSecs=1200
;;
startup|addCronJob)
LockMaxTimeoutSecs=600
LockFileMaxAgeSecs=900
;;
esac
fi
##----------------------------------------##
## Modified by Martinski W. [2025-Jan-15] ##
##----------------------------------------##
_AcquireLock_()
{
local retCode waitTimeoutSecs
local lockFileSecs ageOfLockSecs oldPID
local lockTypeReq lockTypeFound savedVerbose
if [ $# -gt 0 ] && [ -n "$1" ]
then lockTypeReq="$1"
else lockTypeReq="cliAnyLock"
fi
_CreateLockFile_()
{ echo "$$|$lockTypeReq" > "$LockFilePath" ; }
if [ ! -f "$LockFilePath" ]
then _CreateLockFile_ ; return 0
fi
retCode=1
lockTypeFound=""
waitTimeoutSecs=0
savedVerbose="$isVerbose" ; isVerbose=true
while true
do
if [ -s "$LockFilePath" ]
then
oldPID="$(head -n1 "$LockFilePath" | awk -F '|' '{print $1}')"
if [ -n "$oldPID" ] && ! pidof "$ScriptFileName" | grep -qow "$oldPID"
then sed -i "/^${oldPID}|/d" "$LockFilePath"
fi
lockFileSecs="$(date +%s -r "$LockFilePath")"
lockTypeFound="$(_FindLockFileTypes_)"
if [ "$lockTypeReq" != "cliAnyLock" ] && \
! echo "$lockTypeFound" | grep -qw "$lockTypeReq"
then # Specific "Lock Type" NOT found #
echo "$$|$lockTypeReq" >> "$LockFilePath"
retCode=0 ; break
fi
[ -z "$lockTypeFound" ] && lockTypeFound="noTypeLock"
else
_CreateLockFile_
retCode=0 ; break
fi
ageOfLockSecs="$(($(date +%s) - lockFileSecs))"
if [ "$ageOfLockSecs" -gt "$LockFileMaxAgeSecs" ]
then
Say "Stale Lock Found (older than $LockFileMaxAgeSecs secs). Resetting lock file..."
if [ -n "$oldPID" ] && \
pidof "$ScriptFileName" | grep -qow "$oldPID" && \
kill -EXIT "$oldPID" 2>/dev/null
then
kill -TERM "$oldPID" ; wait "$oldPID"
fi
_CreateLockFile_
retCode=0 ; break
elif [ "$waitTimeoutSecs" -le "$LockMaxTimeoutSecs" ]
then
if [ "$((waitTimeoutSecs % 10))" -eq 0 ]
then
Say "Lock Found [$lockTypeFound: $ageOfLockSecs secs]. Waiting for script [PID=$oldPID] to exit [Timer: $waitTimeoutSecs secs]"
fi
sleep "$LockSleepDelaySecs"
waitTimeoutSecs="$((waitTimeoutSecs + LockSleepDelaySecs))"
else
Say "${REDct}**ERROR**${NOct}: The shell script ${ScriptFileName} [PID=$oldPID] is already running [$lockTypeFound: $ageOfLockSecs secs]"
retCode=1 ; break
fi
done
isVerbose="$savedVerbose"
return "$retCode"
}
##-------------------------------------##
## Added by Martinski W. [2026-Mar-18] ##
##-------------------------------------##
fwupMutexFLock_FD=576
fwupMutexFLock_FN="/tmp/var/${ScriptFNameTag}_FW_Update.FLock"
fwupMutexFLock_OK=false #DO NOT have FLock#
_ReleaseMutexFLock_()
{
if [ $# -gt 0 ] && \
[ "$1" = "checkLockOK" ] && \
[ "$fwupMutexFLock_OK" != "true" ]
then return 0
fi
printf '' > "$fwupMutexFLock_FN"
flock -u "$fwupMutexFLock_FD" 2>/dev/null
fwupMutexFLock_OK=false
}
##-------------------------------------##
## Added by Martinski W. [2026-Mar-18] ##
##-------------------------------------##
#--------------------------------------------------------------#
# This is a mutually exclusive, non-blocking FLOCK mechanism
# to be used when MerlinAU is perforning a F/W Update so that
# AMTM can check and prevent running automatic script updates
# while the F/W Update is in progress.
#--------------------------------------------------------------#
_AcquireMutexFLock_()
{
local retCode savedVerbose
local procInfo procName procIDno procIDof=""
savedVerbose="$isVerbose" ; isVerbose=true
if [ -s "$fwupMutexFLock_FN" ]
then
procInfo="$(head -n1 "$fwupMutexFLock_FN")"
procName="$(echo "$procInfo" | cut -d'|' -f1)"
procIDno="$(echo "$procInfo" | cut -d'|' -f2)"
if [ -n "$procName" ] && [ -n "$procIDno" ]
then procIDof="$(pidof "$procName")"
fi
if [ -z "$procIDof" ] || \
! echo "$procIDof" | grep -qow "$procIDno"
then
Say "Stale F/W Update Lock Found. Resetting lock file..."
_ReleaseMutexFLock_
fi
fi
[ ! -s "$fwupMutexFLock_FN" ] && \
eval exec "$fwupMutexFLock_FD>$fwupMutexFLock_FN"
if flock -x -n "$fwupMutexFLock_FD" 2>/dev/null
then
printf "$(basename "$0")|$$\n" > "$fwupMutexFLock_FN"
retCode=0 ; fwupMutexFLock_OK=true
else
procInfo="$(head -n1 "$fwupMutexFLock_FN")"
if [ -n "$procInfo" ]
then procInfo="$(echo "$procInfo" | sed 's/|/, PID=/')"
fi
Say "${REDct}**ERROR**${NOct}: Another process [$procInfo] has the F/W Update Lock file."
retCode=1 ; fwupMutexFLock_OK=false
fi
isVerbose="$savedVerbose"
return "$retCode"
}
##-------------------------------------##
## Added by Martinski W. [2025-Sep-01] ##
##-------------------------------------##
_EscapeChars_()
{ printf "%s" "$1" | sed 's/[][\/$.*^&-]/\\&/g' ; }
##-------------------------------------##
## Added by Martinski W. [2023-Dec-26] ##
##-------------------------------------##
_DoExit_()
{
local exitCode=0
[ $# -gt 0 ] && [ -n "$1" ] && exitCode="$1"
_ReleaseLock_
_ReleaseMutexFLock_ checkLockOK
exit "$exitCode"
}
##-------------------------------------##
## Added by Martinski W. [2025-Nov-01] ##
##-------------------------------------##
_CenterTextStr_()
{
if [ $# -lt 2 ] || [ -z "$1" ] || [ -z "$2" ] || \
! echo "$2" | grep -qE "^[1-9][0-9]+$"
then echo ; return 1
fi
local stringLen="${#1}"
local space1Len="$((($2 - stringLen)/2))"
local space2Len="$space1Len"
local totalLen="$((space1Len + stringLen + space2Len))"
if [ "$totalLen" -lt "$2" ]
then space2Len="$((space2Len + 1))"
elif [ "$totalLen" -gt "$2" ]
then space1Len="$((space1Len - 1))"
fi
if [ "$space1Len" -gt 0 ] && [ "$space2Len" -gt 0 ]
then printf "%*s%s%*s" "$space1Len" '' "$1" "$space2Len" ''
else printf "%s" "$1"
fi
}
##----------------------------------------##
## Modified by Martinski W. [2024-Nov-01] ##
##----------------------------------------##
_ShowLogo_()
{
local showBranchStr
if [ $# -gt 0 ] && [ "$1" = "true" ]
then showBranchStr=true
else showBranchStr=false
fi
local spaceLen=58 colorCT
[ "$SCRIPT_BRANCH" = "master" ] && colorCT="$GRNct" || colorCT="$MGNTct"
echo
printf "${YLWct}\n"
printf " __ __ _ _ _ _ \n"
printf " | \/ | | (_) /\ | | | | \n"
printf " | \ / | ___ _ __| |_ _ __ / \ | | | | \n"
printf " | |\/| |/ _ | '__| | | '_ \ / /\ \| | | | \n"
printf " | | | | __| | | | | | | |/ ____ | |__| | \n"
printf " |_| |_|\___|_| |_|_|_| |_/_/ \_\____/ ${GRNct}v${SCRIPT_VERSION}${NOct}\n"
"$showBranchStr" && \
printf "\n${colorCT}%s${NOct}\n" "$(_CenterTextStr_ "$branchxStr_TAG" "$spaceLen")"
echo
}
##----------------------------------------##
## Modified by Martinski W. [2025-Mar-19] ##
##----------------------------------------##
_ShowAbout_()
{
local webUI_Page webUI_URL="[Not Available]"
if "$mountWebGUI_OK"
then
webUI_Page="$(_Check_WebGUI_Page_Exists_)"
if [ "$webUI_Page" != "NONE" ]
then webUI_URL="$(_GetRouterURL_)/$webUI_Page"
fi
fi
clear
_ShowLogo_ true
printf "About ${MGNTct}${SCRIPT_VERS_INFO}${NOct}\n"
cat <<EOF
$SCRIPT_NAME is a tool for automating firmware updates on AsusWRT-Merlin,
ensuring your router stays up-to-date with the latest features and
security patches. It greatly simplifies the firmware update process
by automatically checking for, downloading, and applying the latest
firmware version update that is currently available.
[Developed by ExtremeFiretop and Martinski W.]
WebUI Tab URL
$webUI_URL
License
$SCRIPT_NAME is free to use under the GNU General Public License
version 3 (GPL-3.0) https://opensource.org/licenses/GPL-3.0
Help & Support
https://www.snbforums.com/forums/asuswrt-merlin-addons.60/?prefix_id=41
Wiki page:
https://github.com/ExtremeFiretop/MerlinAutoUpdate-Router/wiki
Source code
https://github.com/ExtremeFiretop/MerlinAutoUpdate-Router
EOF
echo
_DoExit_ 0
}
##----------------------------------------##
## Modified by Martinski W. [2025-Feb-22] ##
##----------------------------------------##
_ShowHelp_()
{
clear
_ShowLogo_ true
printf "HELP ${MGNTct}${SCRIPT_VERS_INFO}${NOct}\n"
cat <<EOF
Available commands:
${SCRIPT_NAME}.sh about describe add-on functionality
${SCRIPT_NAME}.sh help show available commands & Wiki URL
${SCRIPT_NAME}.sh checkupdates check for available MerlinAU updates
${SCRIPT_NAME}.sh forceupdate update to latest MerlinAU version
${SCRIPT_NAME}.sh run_now run F/W update process
${SCRIPT_NAME}.sh processNodes run update check on nodes
${SCRIPT_NAME}.sh develop switch to development branch
${SCRIPT_NAME}.sh stable switch to stable master branch
${SCRIPT_NAME}.sh startup run startup initialization actions
${SCRIPT_NAME}.sh install install MerlinAU files
${SCRIPT_NAME}.sh uninstall uninstall MerlinAU files
Wiki page:
https://github.com/ExtremeFiretop/MerlinAutoUpdate-Router/wiki
EOF
echo
_DoExit_ 0
}
##----------------------------------------##
## Modified by Martinski W. [2024-May-31] ##
##----------------------------------------##
## To support new "3006" F/W Basecode ##
if [ "$fwInstalledBaseVers" -ge 3006 ]
then readonly nvramLEDsVar=AllLED
else readonly nvramLEDsVar=led_disable
fi
# Save initial LEDs state to put it back later #
readonly LEDsInitState="$(nvram get "$nvramLEDsVar")"
LEDsToggleState="$LEDsInitState"
Toggle_LEDs_PID=""
# To enable/disable the built-in "F/W Update Check" #
FW_UpdateCheckState="$(nvram get firmware_check_enable)"
FW_UpdateCheckScript="/usr/sbin/webs_update.sh"
##-------------------------------------##
## Added by Martinski W. [2023-Nov-24] ##
##-------------------------------------##
#---------------------------------------------------------#
# The USB-attached drives can have multiple partitions
# with different file systems (NTFS, ext3, ext4, etc.),
# which means that multiple mount points can be found.
# So for the purpose of choosing a default value here
# we will simply select the first mount point found.
# Users can later on change it by typing a different
# mount point path or directory using the Main Menu.
#---------------------------------------------------------#
_GetDefaultUSBMountPoint_()
{
local mountPointPath retCode=0
local mountPointRegExp="^/dev/sd.* /tmp/mnt/.*"
mountPointPath="$(grep -m1 "$mountPointRegExp" /proc/mounts | awk -F ' ' '{print $2}')"
[ -z "$mountPointPath" ] && retCode=1
echo "$mountPointPath" ; return "$retCode"
}
##----------------------------------------##
## Modified by Martinski W. [2024-May-31] ##
##----------------------------------------##
# Background function to create a blinking LED effect #
_Toggle_LEDs_()
{
if [ -z "$LEDsToggleState" ]
then
sleep 1
Toggle_LEDs_PID=""
return 1
fi
if [ $# -eq 0 ] || [ -z "$1" ] || \
! echo "$1" | grep -qE "^[2-5]$"
then blinkRateSecs=2
else blinkRateSecs="$1"
fi
while true
do
LEDsToggleState="$((! LEDsToggleState))"
nvram set ${nvramLEDsVar}="$LEDsToggleState"
/sbin/service restart_leds > /dev/null 2>&1
sleep "$blinkRateSecs"
done
return 0
}
##----------------------------------------##
## Modified by Martinski W. [2024-May-31] ##
##----------------------------------------##
_Reset_LEDs_()
{
local doTrace=false
[ $# -gt 0 ] && [ "$1" -eq 1 ] && doTrace=false
if "$doTrace"
then
Say "START _Reset_LEDs_"
_UserTraceLog_ "START _Reset_LEDs_"
fi
# Check if the process with that PID is still running #
if [ -n "$Toggle_LEDs_PID" ] && \
kill -EXIT "$Toggle_LEDs_PID" 2>/dev/null
then
kill -TERM "$Toggle_LEDs_PID"
wait "$Toggle_LEDs_PID"
# Set LEDs to their "initial state" #
nvram set ${nvramLEDsVar}="$LEDsInitState"
/sbin/service restart_leds >/dev/null 2>&1
sleep 2
fi
Toggle_LEDs_PID=""
if "$doTrace"
then
Say "EXIT _Reset_LEDs_"
_UserTraceLog_ "EXIT _Reset_LEDs_"
fi
}
##----------------------------------------##
## Modified by Martinski W. [2024-Apr-06] ##
##----------------------------------------##
_GetRouterURL_()
{
local urlProto urlDomain urlPort
if [ "$(nvram get http_enable)" = "1" ]
then urlProto="https"
else urlProto="http"
fi
urlDomain="$(nvram get lan_domain)"
if [ -z "$urlDomain" ]
then urlDomain="$mainLAN_IPaddr"
else urlDomain="${myLAN_HostName}.$urlDomain"
fi
urlPort="$(nvram get "${urlProto}_lanport")"
if [ "$urlPort" -eq 80 ] || [ "$urlPort" -eq 443 ]
then urlPort=""
else urlPort=":$urlPort"
fi
echo "${urlProto}://${urlDomain}${urlPort}"
}
##----------------------------------------------##
## Added/Modified by Martinski W. [2023-Nov-20] ##
##----------------------------------------------##
_GetRouterModelID_()
{
local retCode=1 routerModelID=""
local nvramModelKeys="odmpid wps_modelnum model build_name"
for nvramKey in $nvramModelKeys
do
routerModelID="$(nvram get "$nvramKey")"
[ -n "$routerModelID" ] && retCode=0 && break
done
echo "$routerModelID" ; return "$retCode"
}
##----------------------------------------------##
## Added/Modified by Martinski W. [2023-Nov-20] ##
##----------------------------------------------##
_GetRouterProductID_()
{
local retCode=1 routerProductID=""
local nvramProductKeys="productid build_name odmpid"
for nvramKey in $nvramProductKeys
do
routerProductID="$(nvram get "$nvramKey")"
[ -n "$routerProductID" ] && retCode=0 && break
done
echo "$routerProductID" ; return "$retCode"
}
##-------------------------------------##
## Added by Martinski W. [2023-Nov-28] ##
##-------------------------------------##
_ScriptVersionStrToNum_()
{
if [ $# -eq 0 ] || [ -z "$1" ] ; then echo 0 ; return 1 ; fi
local verNum verStr
verStr="$(echo "$1" | awk -F '_' '{print $1}')"
verNum="$(echo "$verStr" | awk -F '.' '{printf ("%d%03d%03d\n", $1,$2,$3);}')"
verNum="$(echo "$verNum" | sed 's/^0*//')"
echo "$verNum" ; return 0
}
##----------------------------------------##
## Modified by Martinski W. [2024-Aug-11] ##
##----------------------------------------##
_GetFirmwareVariantFromRouter_()
{
local hasGNUtonFW=false
##FOR TESTING/DEBUG ONLY##
if false # Change to true for forcing GNUton flag #
then echo "true" ; return 0 ; fi
##FOR TESTING/DEBUG ONLY##
# Check if installed F/W NVRAM vars contain "gnuton" #
if echo "$fwInstalledInnerVers" | grep -iq "gnuton" || \
echo "$fwInstalledExtendNum" | grep -iq "gnuton"
then hasGNUtonFW=true ; fi
echo "$hasGNUtonFW" ; return 0
}
##-------------------------------------------##
## Modified by ExtremeFiretop [2025-July-24] ##
##-------------------------------------------##
_FWVersionStrToNum_()
{
if [ $# -lt 2 ] || [ -z "$1" ] || [ -z "$2" ]
then echo ; return 1 ; fi
USE_BETA_WEIGHT="$(Get_Custom_Setting FW_Allow_Beta_Production_Up)"
local verNum verStr="$1"
local fwBasecodeVers="" numOfFields prodFlag tagRank
local stableRank=2 betaRank=1 alphaRank=0 buildDigits=0
# If beta weight is NOT enabled, all tags get the same rank (0) #
if [ "$USE_BETA_WEIGHT" != "ENABLED" ]
then
stableRank=0 ; betaRank=0 ; alphaRank=0
fi
tagRank="$stableRank"
#--------------------------------------------------------------
# Handle any 'alpha/beta' in the version string to be sure
# that we always get good numerical values for comparison.
#--------------------------------------------------------------
if echo "$verStr" | grep -qiE '(alpha|beta)'
then
if echo "$verStr" | grep -qi 'alpha'; then tagRank="$alphaRank"
elif echo "$verStr" | grep -qi 'beta' ; then tagRank="$betaRank"
fi
# Replace '.alpha|.beta' and anything following it with ".0" #
verStr="$(echo "$verStr" | sed 's/[.][Aa]lpha.*/.0/ ; s/[.][Bb]eta.*/.0/')"
# Remove 'alpha|beta' and anything following it #
verStr="$(echo "$verStr" | sed 's/[_-]\?[Aa]lpha.*// ; s/[_-]\?[Bb]eta.*//')"
fi
numOfFields="$(echo "$verStr" | awk -F '.' '{print NF}')"
if [ "$numOfFields" -lt "$2" ]
then fwBasecodeVers="$fwInstalledBaseVers" ; fi
#-----------------------------------------------------------
# Temporarily remove Basecode version to avoid issues with
# integers greater than the maximum 32-bit signed integer
# when doing arithmetic computations with shell cmds.
#-----------------------------------------------------------
if [ "$numOfFields" -gt 3 ]
then
fwBasecodeVers="$(echo "$verStr" | cut -d'.' -f1)"
verStr="$(echo "$verStr" | cut -d'.' -f2-)"
fi
#-----------------------------------------------------------
# FIX: capture trailing build-suffix digits ONLY if there is
# a non-digit-and-non-dot char before them (e.g. "-gnuton2").
# Plain "388.9.2" should NOT set buildDigits.
#-----------------------------------------------------------
if printf '%s' "$verStr" | grep -q '[^0-9.]'