]> Git [git.vados.ru] :: Repos - Mikrotiks/backups.git/commitdiff
Backup for MikroYellow sucessfully creatd at Mar 12 11:31:46.
authorvados-dev <192440777+vados-dev@users.noreply.github.com>
Thu, 12 Mar 2026 08:31:46 +0000 (11:31 +0300)
committervados-dev <192440777+vados-dev@users.noreply.github.com>
Thu, 12 Mar 2026 08:31:46 +0000 (11:31 +0300)
Binary.backup
MikroYellow/20260312/20260312113134-Config.rsc [new file with mode: 0644]
MikroYellow/history/20260312/20260312113134-Diff-Config.rsc [new file with mode: 0644]

index bd95f666d16f51cd912111041a7ee7f2ba424319..5c0df33b95e54e35115424628768a82cde5272b3 100644 (file)
Binary files a/Binary.backup and b/Binary.backup differ
diff --git a/MikroYellow/20260312/20260312113134-Config.rsc b/MikroYellow/20260312/20260312113134-Config.rsc
new file mode 100644 (file)
index 0000000..6544d7e
--- /dev/null
@@ -0,0 +1,3969 @@
+# 2026-03-12 11:31:34 by RouterOS 7.21.3\r
+# software id = A8L5-07YF\r
+#\r
+# model = RB952Ui-5ac2nD\r
+# serial number = D3D50CEDCD38\r
+/interface bridge\r
+add name=Bridge-LAN port-cost-mode=short\r
+/interface wireless\r
+# managed by CAPsMAN\r
+# channel: 2422/20-Ce/gn(18dBm), SSID: vados, local forwarding\r
+set [ find default-name=wlan1 ] disabled=no ssid=MikroTik\r
+# managed by CAPsMAN\r
+# channel: 5200/20-eCee/ac/P(21dBm), SSID: vados5g, local forwarding\r
+set [ find default-name=wlan2 ] disabled=no ssid=MikroTik\r
+/disk\r
+add slot=tmpfs tmpfs-max-size=22369621 type=tmpfs\r
+/interface list\r
+add name=WAN\r
+add name=LAN\r
+/interface wireless security-profiles\r
+set [ find default=yes ] supplicant-identity=MikroTik\r
+/user group\r
+add name=backup policy="telnet,ssh,ftp,read,write,policy,test,sniff,sensitive,\\r
+    !local,!reboot,!winbox,!password,!web,!api,!romon,!rest-api"\r
+/caps-man manager interface\r
+set [ find default=yes ] forbid=yes\r
+/certificate settings\r
+set builtin-trust-store=fetch crl-store=system\r
+/interface bridge port\r
+add bridge=Bridge-LAN interface=ether1 internal-path-cost=10 path-cost=10\r
+add bridge=Bridge-LAN interface=ether2 internal-path-cost=10 path-cost=10\r
+add bridge=Bridge-LAN interface=ether3 internal-path-cost=10 path-cost=10\r
+add bridge=Bridge-LAN interface=ether4 internal-path-cost=10 path-cost=10\r
+add bridge=Bridge-LAN interface=ether5 internal-path-cost=10 path-cost=10\r
+add bridge=Bridge-LAN interface=wlan2 internal-path-cost=10 path-cost=10\r
+add bridge=Bridge-LAN interface=wlan1 internal-path-cost=10 path-cost=10\r
+/ip firewall connection tracking\r
+set udp-timeout=10s\r
+/ipv6 settings\r
+set disable-ipv6=yes disable-link-local-address=yes\r
+/interface list member\r
+add interface=ether1 list=WAN\r
+add interface=ether2 list=LAN\r
+add interface=ether3 list=LAN\r
+add interface=ether4 list=LAN\r
+add interface=ether5 list=LAN\r
+add interface=wlan2 list=LAN\r
+add interface=wlan1 list=LAN\r
+/interface ovpn-server server\r
+add mac-address=FE:9B:F4:E6:40:D9 name=ovpn-server1\r
+/interface wifi capsman\r
+set package-path="" require-peer-certificate=no\r
+/interface wireless cap\r
+# \r
+set bridge=Bridge-LAN caps-man-certificate-common-names=CAPsMAN-A2A7DF3D5EE6 \\r
+    certificate=CAP-488F5A8E1ABC discovery-interfaces=Bridge-LAN enabled=yes \\r
+    interfaces=wlan1,wlan2 lock-to-caps-man=yes\r
+/ip address\r
+add address=10.30.30.86/24 interface=ether2 network=10.30.30.0\r
+/ip dns\r
+set servers=10.30.30.81\r
+/ip hotspot profile\r
+set [ find default=yes ] html-directory=hotspot\r
+/ip ipsec profile\r
+set [ find default=yes ] dpd-interval=2m dpd-maximum-failures=5\r
+/ip service\r
+set ftp disabled=yes\r
+set telnet disabled=yes\r
+set www disabled=yes\r
+set ssh port=2222\r
+set api disabled=yes\r
+set api-ssl disabled=yes\r
+/ip service webserver\r
+set acme-plain=no crl-plain=no graphs-plain=no graphs-secure=no index-plain=\\r
+    no index-secure=no rest-plain=no rest-secure=no scep-plain=no \\r
+    webfig-plain=no webfig-secure=no\r
+/ip ssh\r
+set forwarding-enabled=both publickey-authentication-options=verify-required \\r
+    strong-crypto=yes\r
+/ipv6 nd\r
+set [ find default=yes ] advertise-dns=yes\r
+/system clock\r
+set time-zone-autodetect=no time-zone-name=Europe/Moscow\r
+/system clock manual\r
+set time-zone=+03:00\r
+/system identity\r
+set name=MikroYellow\r
+/system ntp client\r
+set enabled=yes\r
+/system ntp server\r
+set enabled=yes manycast=yes multicast=yes\r
+/system ntp client servers\r
+add address=10.30.30.81\r
+add address=10.30.30.10\r
+add address=0.ru.pool.ntp.org\r
+add address=1.ru.pool.ntp.org\r
+add address=2.ru.pool.ntp.org\r
+add address=3.ru.pool.ntp.org\r
+/system scheduler\r
+add interval=1w name=BackupEveryWeek on-event=BackupAndUpdate policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon \\r
+    start-date=2025-07-07 start-time=04:39:32\r
+add comment="CloudFlare Certificate Update" interval=1w name=\\r
+    Certificate_CloudFlare_Update on-event=Certificate_CloudFlare policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon \\r
+    start-date=2025-11-28 start-time=05:45:40\r
+add comment="Setup Global Environment for scripts" name=AM-SetGlobalEnv \\r
+    on-event="/system/script { run AM-GlobalConfig; run AM-GlobalFunc; }" \\r
+    policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon \\r
+    start-time=startup\r
+add comment="Every Day Check For Update Scripts" interval=1d name=\\r
+    AM-ScriptInstallUpdate on-event=\\r
+    ":global ScriptInstallUpdate; \$ScriptInstallUpdate;" policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon \\r
+    start-time=startup\r
+/system script\r
+add dont-require-permissions=no name=BackupAndUpdate owner=vados policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="#\\r
+    \_Script name: BackupAndUpdate\r\\r
+    \n#\r\\r
+    \n# SCRIPT INFORMATION\r\\r
+    \n#\r\\r
+    \n# Script:  Mikrotik RouterOS automatic backup & update\r\\r
+    \n# Version: 25.04.15\r\\r
+    \n# Created: 07/08/2018\r\\r
+    \n# Updated: 15/04/2025\r\\r
+    \n# Author:  Alexander Tebiev\r\\r
+    \n# Website: https://github.com/beeyev\r\\r
+    \n# You can contact me by e-mail at tebiev@mail.com\r\\r
+    \n#\r\\r
+    \n# IMPORTANT!\r\\r
+    \n# Minimum supported RouterOS version is v6.43.7\r\\r
+    \n#\r\\r
+    \n# --- MODIFY THIS SECTION AS NEEDED ---\r\\r
+    \n# Notification e-mail\r\\r
+    \n# (Make sure you have configured Email settings in Tools -> Email)\r\\r
+    \n:local emailAddress \"vados@vados.ru\";\r\\r
+    \n\r\\r
+    \n# Script mode, possible values: backup, osupdate, osnotify.\r\\r
+    \n# backup    -   Only backup will be performed. (default value, if none p\\r
+    rovided)\r\\r
+    \n#\r\\r
+    \n# osupdate  -   Installs new RouterOS if available and creates backups b\\r
+    efore/after update (ignores `forceBackup`)\r\\r
+    \n#               Sends email only when an update is found.\r\\r
+    \n#               Set `forceBackup` to true to always create backups, even\\r
+    \_without updates\r\\r
+    \n#\r\\r
+    \n# osnotify  -   Sends email only if a new RouterOS update is found (no b\\r
+    ackups)\r\\r
+    \n#               Set `forceBackup` to always create backups on every run\\r
+    \r\\r
+    \n:local scriptMode \"osupdate\"\r\\r
+    \n\r\\r
+    \n# Additional parameter if you set `scriptMode` to `osupdate` or `osnotif\\r
+    y`\r\\r
+    \n# Set `true` if you want the script to perform backup every time its fir\\r
+    ed, whatever script mode is set.\r\\r
+    \n:local forceBackup true\r\\r
+    \n\r\\r
+    \n# Backup encryption password, no encryption if no password.\r\\r
+    \n:local backupPassword \"Peskar55\"\r\\r
+    \n\r\\r
+    \n# If true, passwords will be included in exported config.\r\\r
+    \n:local sensitiveDataInConfig true\r\\r
+    \n\r\\r
+    \n## Update channel. Possible values: stable, long-term, testing, developm\\r
+    ent\r\\r
+    \n:local updateChannel \"stable\"\r\\r
+    \n\r\\r
+    \n# Installs patch updates only (scriptMode = \"osupdate\").\r\\r
+    \n# Works for `stable` and `long-term` channels.\r\\r
+    \n# Updates only if MAJOR.MINOR match (e.g. 6.43.2 > 6.43.6 allowed, 6.44.\\r
+    1 skipped).\r\\r
+    \n# Sends info if a newer (non-patch) version is found.\r\\r
+    \n:local installOnlyPatchUpdates false\r\\r
+    \n\r\\r
+    \n# Include public IP info in email if set to true\r\\r
+    \n:local detectPublicIpAddress true\r\\r
+    \n\r\\r
+    \n## Allow anonymous statistics collection. (script mode and generic non-s\\r
+    ensitive device info)\r\\r
+    \n:local anonStats false\r\\r
+    \n\r\\r
+    \n#  !!! DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU\E2\80\99RE D\\r
+    OING !!!\r\\r
+    \n\r\\r
+    \n:local scriptVersion \"25.04.15\"\r\\r
+    \n\r\\r
+    \n# default and fallback public IP detection services\r\\r
+    \n:local ipAddressDetectServiceDefault \"https://ipv4.mikrotik.ovh/\"\r\\r
+    \n:local ipAddressDetectServiceFallback \"https://api.ipify.org/\"\r\\r
+    \n\r\\r
+    \n#Script messages prefix\r\\r
+    \n:local SMP \"Bkp&Upd:\"\r\\r
+    \n\r\\r
+    \n:local exitErrorMessage \"\$SMP script stopped due to an error. Please c\\r
+    heck logs for more details.\"\r\\r
+    \n:log info \"\\n\\n\$SMP Script \\\"Mikrotik RouterOS automatic backup & \\r
+    update\\\" v.\$scriptVersion started.\"\r\\r
+    \n:log info \"\$SMP Script Mode: `\$scriptMode`, Update channel: `\$update\\r
+    Channel`, Force backup: `\$forceBackup`, Install only patch updates: `\$in\\r
+    stallOnlyPatchUpdates`\"\r\\r
+    \n\r\\r
+    \n## vv FUNCTIONS vv ##\r\\r
+    \n\r\\r
+    \n# Returns currently running RouterOS version\r\\r
+    \n# :put [\$FuncGetRunningOsVersion]  # Output: 6.48.1\r\\r
+    \n:local FuncGetRunningOsVersion do={\r\\r
+    \n  :local runningOsAndChannel [/system resource get version]\r\\r
+    \n\r\\r
+    \n  :local spacePos [:find \$runningOsAndChannel \" \"]\r\\r
+    \n  :if ([:len \$spacePos] = 0) do={\r\\r
+    \n    :log error \"Bkp&Upd: Could not extract installed OS version string:\\r
+    \_`\$runningOsAndChannel`.\"\r\\r
+    \n    :error \"Bkp&Upd: error, check logs\"\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :local versionOnly [:pick \$runningOsAndChannel 0 \$spacePos]\r\\r
+    \n\r\\r
+    \n  :return \$versionOnly\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Returns currently running RouterOS channel\r\\r
+    \n# :put [\$FuncGetRunningOsChannel]  # Output: stable\r\\r
+    \n:local FuncGetRunningOsChannel do={\r\\r
+    \n  :local runningOsAndChannel [/system resource get version]\r\\r
+    \n\r\\r
+    \n  :local open [:find \$runningOsAndChannel \"(\"]\r\\r
+    \n  :if ([:len \$open] = 0) do={\r\\r
+    \n    :log error \"Bkp&Upd: Could not extract installed OS channel from ve\\r
+    rsion string: `\$runningOsAndChannel`.\"\r\\r
+    \n    :error \"Bkp&Upd: error, check logs\"\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :local rest [:pick \$runningOsAndChannel (\$open+1) [:len \$runningOsA\\r
+    ndChannel]]\r\\r
+    \n  :local close [:find \$rest \")\"]\r\\r
+    \n  :local channel [:pick \$rest 0 \$close]\r\\r
+    \n\r\\r
+    \n  :return \$channel\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Checks if two RouterOS version strings differ only by the patch versio\\r
+    n\r\\r
+    \n# :put [\$FuncIsPatchUpdateOnly \"6.2.1\" \"6.2.4\"]  # Output: true\r\\r
+    \n# :put [\$FuncIsPatchUpdateOnly \"6.2.1\" \"6.3.1\"]  # Output: false\r\\r
+    \n:local FuncIsPatchUpdateOnly do={\r\\r
+    \n  :local ver1 \$1\r\\r
+    \n  :local ver2 \$2\r\\r
+    \n\r\\r
+    \n  # Extract the major and minor components from a version\r\\r
+    \n  :local extractMajorMinor do={\r\\r
+    \n    :local ver \$1\r\\r
+    \n    :local dot1 [:find \$ver \".\"]\r\\r
+    \n    :if (\$dot1 = -1) do={ :return \$ver }\r\\r
+    \n\r\\r
+    \n    :local major [:pick \$ver 0 \$dot1]\r\\r
+    \n    :local rest [:pick \$ver (\$dot1 + 1) [:len \$ver]]\r\\r
+    \n    :local dot2 [:find \$rest \".\"]\r\\r
+    \n    :local minor \$rest\r\\r
+    \n    :if (\$dot2 >= 0) do={ :set minor [:pick \$rest 0 \$dot2] }\r\\r
+    \n\r\\r
+    \n    :return (\$major . \".\" . \$minor)\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  # Compare the major and minor components of both version strings\r\\r
+    \n  :if ([\$extractMajorMinor \$ver1] = [\$extractMajorMinor \$ver2]) do={\\r
+    \r\\r
+    \n    :return true\r\\r
+    \n  }\r\\r
+    \n  :return false\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Creates backups and returns array of names\r\\r
+    \n# Possible arguments:\r\\r
+    \n#  \$1 - file name, without extension\r\\r
+    \n#  \$2 - password (optional)\r\\r
+    \n#  \$3 - sensitive data in config (optional, default: false)\r\\r
+    \n# Example:\r\\r
+    \n# :put [\$FuncCreateBackups \"daily-backup\"]\r\\r
+    \n:local FuncCreateBackups do={\r\\r
+    \n  :local backupName \$1\r\\r
+    \n  :local backupPassword \$2\r\\r
+    \n  :local sensitiveDataInConfig \$3\r\\r
+    \n\r\\r
+    \n  #Script messages prefix\r\\r
+    \n  :local SMP \"Bkp&Upd:\"\r\\r
+    \n  :local exitErrorMessage \"\$SMP script stopped due to an error. Please\\r
+    \_check logs for more details.\"\r\\r
+    \n  :log info (\"\$SMP global function `FuncCreateBackups` started, input:\\r
+    \_`\$backupName`\")\r\\r
+    \n\r\\r
+    \n  # validate required parameter: backupName\r\\r
+    \n  :if ([:typeof \$backupName] != \"str\" or [:len \$backupName] = 0) do=\\r
+    {\r\\r
+    \n    :log error \"\$SMP parameter 'backupName' is required and must be a \\r
+    non-empty string\"\r\\r
+    \n    :error \$exitErrorMessage\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :local backupFileSys \"\$backupName.backup\"\r\\r
+    \n  :local backupFileConfig \"\$backupName.rsc\"\r\\r
+    \n  :local backupNames {\$backupFileSys;\$backupFileConfig}\r\\r
+    \n\r\\r
+    \n  ## Perform system backup\r\\r
+    \n  :if ([:len \$backupPassword] = 0) do={\r\\r
+    \n    :log info (\"\$SMP starting backup without password, backup name: `\\r
+    \$backupName`\")\r\\r
+    \n    /system backup save dont-encrypt=yes name=\$backupName\r\\r
+    \n  } else={\r\\r
+    \n    :log info (\"\$SMP starting backup with password, backup name: `\$ba\\r
+    ckupName`\")\r\\r
+    \n    /system backup save password=\$backupPassword name=\$backupName\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :log info (\"\$SMP system backup created: `\$backupFileSys`\")\r\\r
+    \n\r\\r
+    \n    ## Export config file\r\\r
+    \n  :if (\$sensitiveDataInConfig = true) do={\r\\r
+    \n    :log info (\"\$SMP starting export config with sensitive data, backu\\r
+    p name: `\$backupName`\")\r\\r
+    \n    # Since RouterOS v7 it needs to be explicitly set that we want to ex\\r
+    port sensitive data\r\\r
+    \n    :if ([:pick [/system resource get version] 0 1] < 7) do={\r\\r
+    \n      :execute \"/export compact terse file=\$backupName\"\r\\r
+    \n    } else={\r\\r
+    \n      :execute \"/export compact show-sensitive terse file=\$backupName\\r
+    \"\r\\r
+    \n    }\r\\r
+    \n  } else={\r\\r
+    \n    :log info (\"\$SMP starting export config without sensitive data, ba\\r
+    ckup name: `\$backupName`\")\r\\r
+    \n    /export compact hide-sensitive terse file=\$backupName\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :log info (\"\$SMP Config export complete: `\$backupFileConfig`\")\r\\r
+    \n  :log info (\"\$SMP Waiting a little to ensure backup files are written\\r
+    \")\r\\r
+    \n\r\\r
+    \n  :delay 20s\r\\r
+    \n\r\\r
+    \n  :if ([:len [/file find name=\$backupFileSys]] > 0) do={\r\\r
+    \n    :log info (\"\$SMP system backup file successfully saved to the file\\r
+    \_system: `\$backupFileSys`\")\r\\r
+    \n  } else={\r\\r
+    \n    :log error (\"\$SMP system backup was not created, file does not exi\\r
+    st: `\$backupFileSys`\")\r\\r
+    \n    :error \$exitErrorMessage\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :if ([:len [/file find name=\$backupFileConfig]] > 0) do={\r\\r
+    \n    :log info (\"\$SMP config backup file successfully saved to the file\\r
+    \_system: `\$backupFileConfig`\")\r\\r
+    \n  } else={\r\\r
+    \n    :log error (\"\$SMP config backup was not created, file does not exi\\r
+    st: `\$backupFileConfig`\")\r\\r
+    \n    :error \$exitErrorMessage\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :log info (\"\$SMP global function `FuncCreateBackups` finished. Creat\\r
+    ed backups, system: `\$backupFileSys`, config: `\$backupFileConfig`\")\r\\r
+    \n\r\\r
+    \n  :return \$backupNames\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Sends an email\r\\r
+    \n# Parameters:\r\\r
+    \n#  \$1 - to (email address)\r\\r
+    \n#  \$2 - subject\r\\r
+    \n#  \$3 - body\r\\r
+    \n#  \$4 - file attachments (optional; pass \"\" if not needed)\r\\r
+    \n#\r\\r
+    \n# Example:\r\\r
+    \n# \$FuncSendEmailSafe \"admin@domain.com\" \"Backup Done\" \"Backup comp\\r
+    lete.\" \"backup1.backup\"\r\\r
+    \n:local FuncSendEmailSafe do={\r\\r
+    \n\r\\r
+    \n  :local emailTo \$1\r\\r
+    \n  :local emailSubject \$2\r\\r
+    \n  :local emailBody \$3\r\\r
+    \n  :local emailAttachments \$4\r\\r
+    \n\r\\r
+    \n  :local SMP \"Bkp&Upd:\"\r\\r
+    \n  :local exitErrorMessage \"\$SMP script stopped due to an error. Please\\r
+    \_check logs for more details.\"\r\\r
+    \n\r\\r
+    \n  :log info \"\$SMP Attempting to send email to `\$emailTo`\"\r\\r
+    \n\r\\r
+    \n  # SAFETY: wait for any previously queued email to finish\r\\r
+    \n  :local waitTimeoutPre 60\r\\r
+    \n  :local waitCounterPre 0\r\\r
+    \n  :while (([/tool e-mail get last-status] = \"resolving-dns\" or [/tool \\r
+    e-mail get last-status] = \"in-progress\")) do={\r\\r
+    \n    :if (\$waitCounterPre >= \$waitTimeoutPre) do={\r\\r
+    \n      :log error \"\$SMP Email send aborted: previous send did not compl\\r
+    ete after \$waitTimeoutPre seconds\"\r\\r
+    \n      :error \$exitErrorMessage\r\\r
+    \n    }\r\\r
+    \n\r\\r
+    \n    :log info \"\$SMP Waiting for previous email to finish (status: \$[/\\r
+    tool e-mail get last-status])...\"\r\\r
+    \n    :delay 1s\r\\r
+    \n    :set waitCounterPre (\$waitCounterPre + 1)\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  # Send the email\r\\r
+    \n  :do {\r\\r
+    \n    /tool e-mail send to=\$emailTo subject=\$emailSubject body=\$emailBo\\r
+    dy file=\$emailAttachments\r\\r
+    \n  } on-error={\r\\r
+    \n    :log error \"\$SMP Email send command failed to execute. Check logs \\r
+    and verify email settings.\"\r\\r
+    \n    :error \$exitErrorMessage\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  # Wait for send status to change from \"in-progress\" / \"resolving-dn\\r
+    s\"\r\\r
+    \n  :local waitTimeout 60\r\\r
+    \n  :local waitCounter 0\r\\r
+    \n  :local emailStatus \"\"\r\\r
+    \n  :log info \"\$SMP Waiting for email to be sent, timeout in `\$waitTime\\r
+    out` seconds...\"\r\\r
+    \n  :while (\$waitCounter < \$waitTimeout) do={\r\\r
+    \n    :set emailStatus [/tool e-mail get last-status]\r\\r
+    \n    :if (\$emailStatus != \"in-progress\" and \$emailStatus != \"resolvi\\r
+    ng-dns\") do={\r\\r
+    \n      :log info \"\$SMP Email send status received: \$emailStatus\"\r\\r
+    \n\r\\r
+    \n      # exit loop\r\\r
+    \n      :set waitCounter \$waitTimeout\r\\r
+    \n    } else={\r\\r
+    \n      :delay 1s\r\\r
+    \n      :set waitCounter (\$waitCounter + 1)\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  # Final decision based on last status\r\\r
+    \n  :if (\$emailStatus = \"succeeded\") do={\r\\r
+    \n    :log info  \"\$SMP Email successfully sent to `\$emailTo`\"\r\\r
+    \n  } else={\r\\r
+    \n    :log error \"\$SMP Email failed to send. Status: `\$emailStatus`. Ch\\r
+    eck logs for more details and verify email settings.\"\r\\r
+    \n    :error \$exitErrorMessage\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Global variable to track current update step\r\\r
+    \n# They need to be initialized here first to be available in the script\r\\r
+    \n:global buGlobalVarTargetOsVersion\r\\r
+    \n\r\\r
+    \n:global buGlobalVarScriptStep\r\\r
+    \n:local scriptStep \$buGlobalVarScriptStep\r\\r
+    \n:do {/system script environment remove buGlobalVarScriptStep} on-error={\\r
+    }\r\\r
+    \n:if ([:len \$scriptStep] = 0) do={\r\\r
+    \n  :set scriptStep 1\r\\r
+    \n}\r\\r
+    \n## ^^ FUNCTIONS ^^ ##\r\\r
+    \n\r\\r
+    \n\r\\r
+    \n#\r\\r
+    \n# Initial validation\r\\r
+    \n#\r\\r
+    \n\r\\r
+    \n## Check email settings\r\\r
+    \n:if ([:len \$emailAddress] < 3) do={\r\\r
+    \n  :log error (\"\$SMP Parameter `\\\$emailAddress` is not set, or contai\\r
+    ns invalid value. Script stopped.\")\r\\r
+    \n  :error \$exitErrorMessage\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Values will be defined later in the script\r\\r
+    \n:local emailServer \"\"\r\\r
+    \n:local emailFromAddress [/tool e-mail get from]\r\\r
+    \n\r\\r
+    \n:log info \"\$SMP Validating email settings...\"\r\\r
+    \n:do {\r\\r
+    \n  :set emailServer [/tool e-mail get server]\r\\r
+    \n} on-error={\r\\r
+    \n  # This is a workaround for the RouterOS v7.12 and older versions\r\\r
+    \n  :set emailServer [/tool e-mail get address]\r\\r
+    \n}\r\\r
+    \n:if (\$emailServer = \"0.0.0.0\") do={\r\\r
+    \n  :log error (\"\$SMP Email server address is not correct: `\$emailServe\\r
+    r`, check `Tools -> Email`. Script stopped.\");\r\\r
+    \n  :error \$exitErrorMessage\r\\r
+    \n}\r\\r
+    \n:if ([:len \$emailFromAddress] < 3) do={\r\\r
+    \n  :log error (\"\$SMP Email configuration FROM address is not correct: `\\r
+    \$emailFromAddress`, check `Tools -> Email`. Script stopped.\");\r\\r
+    \n  :error \$exitErrorMessage\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Script mode validation\r\\r
+    \n:if (\$scriptMode != \"backup\" and \$scriptMode != \"osupdate\" and \$s\\r
+    criptMode != \"osnotify\") do={\r\\r
+    \n  :log error (\"\$SMP Script parameter `\\\$scriptMode` is not set, or c\\r
+    ontains invalid value: `\$scriptMode`. Script stopped.\")\r\\r
+    \n  :error \$exitErrorMessage\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Update channel validation\r\\r
+    \n:if (\$updateChannel != \"stable\" and \$updateChannel != \"long-term\" \\r
+    and \$updateChannel != \"testing\" and \$updateChannel != \"development\")\\r
+    \_do={\r\\r
+    \n  :log error (\"\$SMP Script parameter `\\\$updateChannel` is not set, o\\r
+    r contains invalid value: `\$updateChannel`. Script stopped.\")\r\\r
+    \n  :error \$exitErrorMessage\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Verify if script is set to install patch updates and if the update cha\\r
+    nnel is valid\r\\r
+    \n:if (\$scriptMode = \"osupdate\" and \$installOnlyPatchUpdates = true) d\\r
+    o={\r\\r
+    \n  :if (\$updateChannel != \"stable\" and \$updateChannel != \"long-term\\r
+    \") do={\r\\r
+    \n    :log error (\"\$SMP Patch-only updates enabled, but update channel `\\r
+    \$updateChannel` is invalid. Only `stable` and `long-term` are supported. \\r
+    Script stopped\")\r\\r
+    \n    :error \$exitErrorMessage\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :local susRunningOsChannel [\$FuncGetRunningOsChannel]\r\\r
+    \n\r\\r
+    \n  :if (\$susRunningOsChannel != \"stable\" and \$susRunningOsChannel != \\r
+    \"long-term\") do={\r\\r
+    \n    :log error (\"\$SMP Script is set to install only patch updates, but\\r
+    \_the installed RouterOS version is not from `stable` or `long-term` chann\\r
+    el: `\$susRunningOsChannel`. Script stopped\")\r\\r
+    \n    :error \$exitErrorMessage\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n#\r\\r
+    \n# Get current date and time\r\\r
+    \n#\r\\r
+    \n:local rawTime [/system clock get time]\r\\r
+    \n:local rawDate [/system clock get date]\r\\r
+    \n\r\\r
+    \n# Current time in specific format `hh-mm-ss`\r\\r
+    \n:local currentTime ([:pick \$rawTime 0 2] . \"-\" . [:pick \$rawTime 3 5\\r
+    ] . \"-\" . [:pick \$rawTime 6 8])\r\\r
+    \n\r\\r
+    \n# Current date `YYYY-MM-DD` or `YYYY-Mon-DD`\r\\r
+    \n:local currentDate \"undefined\"\r\\r
+    \n\r\\r
+    \n# Check if the date is in the old format\r\\r
+    \n:if ([:len [:tonum [:pick \$rawDate 0 1]]] = 0) do={\r\\r
+    \n  # Convert old format `nov/11/2023` > `2023-nov-11`\r\\r
+    \n  :set currentDate ([:pick \$rawDate 7 11] . \"-\" . [:pick \$rawDate 0 \\r
+    3] . \"-\" . [:pick \$rawDate 4 6])\r\\r
+    \n} else={\r\\r
+    \n  # Use new format as is `YYYY-MM-DD`\r\\r
+    \n  :set currentDate \$rawDate\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:local currentDateTime (\$currentDate . \"-\" . \$currentTime)\r\\r
+    \n\r\\r
+    \n:local deviceBoardName [/system resource get board-name]\r\\r
+    \n\r\\r
+    \n## Check if it's a cloud hosted router\r\\r
+    \n:local isCloudHostedRouter false;\r\\r
+    \n:if ([:pick \$deviceBoardName 0 3] = \"CHR\" or [:pick \$deviceBoardName\\r
+    \_0 3] = \"x86\") do={\r\\r
+    \n  :set isCloudHostedRouter true;\r\\r
+    \n};\r\\r
+    \n\r\\r
+    \n:local deviceIdentityName     [/system identity get name];\r\\r
+    \n:local deviceIdentityNameShort  [:pick \$deviceIdentityName 0 18]\r\\r
+    \n\r\\r
+    \n:local deviceRbModel        \"CloudHostedRouter\";\r\\r
+    \n:local deviceRbSerialNumber \"--\"\r\\r
+    \n:local deviceRbCurrentFw    \"--\"\r\\r
+    \n:local deviceRbUpgradeFw    \"--\"\r\\r
+    \n\r\\r
+    \n:if (\$isCloudHostedRouter = false) do={\r\\r
+    \n  :set deviceRbModel        [/system routerboard get model]\r\\r
+    \n  :set deviceRbSerialNumber [/system routerboard get serial-number]\r\\r
+    \n  :set deviceRbCurrentFw    [/system routerboard get current-firmware]\r\\r
+    \n  :set deviceRbUpgradeFw    [/system routerboard get upgrade-firmware]\r\\r
+    \n};\r\\r
+    \n\r\\r
+    \n:local runningOsChannel [\$FuncGetRunningOsChannel]\r\\r
+    \n:local runningOsVersion [\$FuncGetRunningOsVersion]\r\\r
+    \n:local deviceOsVerAndChannelRunning [/system resource get version]\r\\r
+    \n\r\\r
+    \n:local backupNameTemplate     \"backup_v\$runningOsVersion_\$runningOsCh\\r
+    annel_\$currentDateTime\"\r\\r
+    \n:local backupNameBeforeUpdate \"backup_before_update_\$backupNameTemplat\\r
+    e\"\r\\r
+    \n:local backupNameAfterUpdate  \"backup_after_update_\$backupNameTemplate\\r
+    \"\r\\r
+    \n\r\\r
+    \n## Email body template\r\\r
+    \n\r\\r
+    \n:local mailSubjectPrefix  \"\$SMP Device - `\$deviceIdentityNameShort`\"\\r
+    \r\\r
+    \n\r\\r
+    \n:local mailBodyCopyright  \"Mikrotik RouterOS automatic backup & update \\r
+    (ver. \$scriptVersion) \\nhttps://github.com/beeyev/Mikrotik-RouterOS-auto\\r
+    matic-backup-and-update\"\r\\r
+    \n:local changelogUrl     \"Check RouterOS changelog: https://mikrotik.com\\r
+    /download/changelogs/\"\r\\r
+    \n\r\\r
+    \n:local mailBodyDeviceInfo  \"\"\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"Device information:\")\\r
+    \r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\n-------------------\\r
+    --\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nName: \$deviceIdent\\r
+    ityName\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nModel: \$deviceRbMo\\r
+    del\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nBoard: \$deviceBoar\\r
+    dName\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nSerial number: \$de\\r
+    viceRbSerialNumber\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nRouterOS version: v\\r
+    \$deviceOsVerAndChannelRunning\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nBuild time: \$[/sys\\r
+    tem resource get build-time]\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nRouterboard FW: \$d\\r
+    eviceRbCurrentFw\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nDevice date-time: \\r
+    \$rawDate \$rawTime (\$[/system clock get time-zone-name ])\")\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nUptime: \$[/system \\r
+    resource get uptime]\")\r\\r
+    \n# IP address will be appended later if needed\r\\r
+    \n\r\\r
+    \n:local mailAttachments  [:toarray \"\"]\r\\r
+    \n\r\\r
+    \n## IP address detection\r\\r
+    \n:if (\$scriptStep = 1 or \$scriptStep = 3) do={\r\\r
+    \n  :if (\$scriptStep = 3) do={\r\\r
+    \n    :log info (\"\$SMP Waiting for one minute before continuing to the f\\r
+    inal step.\")\r\\r
+    \n    :delay 1m\r\\r
+    \n  }\r\\r
+    \n  # default values\r\\r
+    \n  :local publicIpAddress \"not-detected\"\r\\r
+    \n  :local telemetryDataQuery \"\"\r\\r
+    \n\r\\r
+    \n  :if (\$detectPublicIpAddress = true or \$anonStats = true) do={\r\\r
+    \n    :if (\$anonStats = true) do={\r\\r
+    \n      :set telemetryDataQuery (\"\\\?mode=\" . \$scriptMode . \"&scriptv\\r
+    er=\" . \$scriptVersion . \"&updatechannel=\" . \$updateChannel . \"&osver\\r
+    =\" . \$runningOsVersion . \"&step=\" . \$scriptStep . \"&forcebackup=\" .\\r
+    \_\$forceBackup . \"&onlypatchupdates=\" . \$installOnlyPatchUpdates . \"&\\r
+    model=\" . \$deviceRbModel . \"&deviceboard=\" . \$deviceBoardName)\r\\r
+    \n    }\r\\r
+    \n\r\\r
+    \n    :do {:set publicIpAddress ([/tool fetch http-method=\"get\" url=(\$i\\r
+    pAddressDetectServiceDefault . \$telemetryDataQuery) output=user as-value]\\r
+    ->\"data\")} on-error={\r\\r
+    \n      :if (\$detectPublicIpAddress = true) do={\r\\r
+    \n        :log warning \"\$SMP Failed to detect public IP using default se\\r
+    rvice: `\$ipAddressDetectServiceDefault`\"\r\\r
+    \n        :log warning \"\$SMP Trying fallback service: `\$ipAddressDetect\\r
+    ServiceFallback`\"\r\\r
+    \n\r\\r
+    \n        :do {:set publicIpAddress ([/tool fetch http-method=\"get\" url=\\r
+    \$ipAddressDetectServiceFallback output=user as-value]->\"data\")} on-erro\\r
+    r={\r\\r
+    \n          :log warning \"\$SMP Could not detect public IP address using \\r
+    fallback detection service: `\$ipAddressDetectServiceFallback`\"\r\\r
+    \n        }\r\\r
+    \n      }\r\\r
+    \n    }\r\\r
+    \n\r\\r
+    \n    # basic safety\r\\r
+    \n    :set publicIpAddress ([:pick \$publicIpAddress 0 15])\r\\r
+    \n\r\\r
+    \n    :if (\$detectPublicIpAddress = true) do={\r\\r
+    \n      :set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nPublic IP add\\r
+    ress: \$publicIpAddress\")\r\\r
+    \n      :log info \"\$SMP Public IP address detected: `\$publicIpAddress`\\r
+    \"\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n## STEP 1: Create backups, check for new RouterOS, and send email\r\\r
+    \n## Steps 2\E2\80\933 run only if auto-update is enabled and a new versio\\r
+    n is available\r\\r
+    \n:if (\$scriptStep = 1) do={\r\\r
+    \n  :local routerOsVersionAvailable \"0.0.0\"\r\\r
+    \n  :local isNewOsUpdateAvailable false\r\\r
+    \n  :local isLatestOsAlreadyInstalled true\r\\r
+    \n  :local isOsNeedsToBeUpdated false\r\\r
+    \n  :local isUpdateCheckSucceeded false\r\\r
+    \n  :local isEmailNeedsToBeSent false\r\\r
+    \n\r\\r
+    \n  :local mailSubjectPartAction \"\"\r\\r
+    \n  :local mailPtBodyAction \"\"\r\\r
+    \n\r\\r
+    \n  :local mailPtSubjectBackup \"\"\r\\r
+    \n  :local mailPtBodyBackup \"\"\r\\r
+    \n\r\\r
+    \n  # Checking for new version\r\\r
+    \n  :if (\$scriptMode = \"osupdate\" or \$scriptMode = \"osnotify\") do={\\r
+    \r\\r
+    \n    log info (\"\$SMP Setting update channel to `\$updateChannel`\")\r\\r
+    \n    /system package update set channel=\$updateChannel\r\\r
+    \n    log info (\"\$SMP Checking for new RouterOS version. Current install\\r
+    ed version is: `\$runningOsVersion`\")\r\\r
+    \n    /system package update check-for-updates\r\\r
+    \n\r\\r
+    \n    # Wait to allow the system to check for updates\r\\r
+    \n    :delay 5s;\r\\r
+    \n\r\\r
+    \n    :local packageUpdateStatus \"undefined\"\r\\r
+    \n\r\\r
+    \n    :set routerOsVersionAvailable [/system package update get latest-ver\\r
+    sion]\r\\r
+    \n    :set packageUpdateStatus [/system package update get status]\r\\r
+    \n\r\\r
+    \n    :if (\$packageUpdateStatus = \"New version is available\") do={\r\\r
+    \n      :log info (\"\$SMP New RouterOS version is available: `\$routerOsV\\r
+    ersionAvailable`\")\r\\r
+    \n      :set isNewOsUpdateAvailable true\r\\r
+    \n      :set isLatestOsAlreadyInstalled false\r\\r
+    \n      :set isUpdateCheckSucceeded true\r\\r
+    \n      :set isEmailNeedsToBeSent true\r\\r
+    \n\r\\r
+    \n      :set mailSubjectPartAction \"New RouterOS available\"\r\\r
+    \n      :set mailPtBodyAction  \"New RouterOS version is available, curren\\r
+    t version: v\$runningOsVersion, new version: v\$routerOsVersionAvailable. \\r
+    \\n\$changelogUrl\"\r\\r
+    \n    } else={\r\\r
+    \n      :if (\$packageUpdateStatus = \"System is already up to date\") do=\\r
+    {\r\\r
+    \n        :log info (\"\$SMP No new RouterOS version is available, the lat\\r
+    est version is already installed: `v\$runningOsVersion`\")\r\\r
+    \n        :set isUpdateCheckSucceeded true\r\\r
+    \n\r\\r
+    \n        :set mailSubjectPartAction \"No os update available\"\r\\r
+    \n        :set mailPtBodyAction  \"No new RouterOS version is available, t\\r
+    he latest version is already installed: `v\$runningOsVersion`\"\r\\r
+    \n      } else={\r\\r
+    \n        :log error (\"\$SMP Failed to check for new RouterOS version. Pa\\r
+    ckage check status: `\$packageUpdateStatus`\")\r\\r
+    \n        :set isEmailNeedsToBeSent true\r\\r
+    \n\r\\r
+    \n        :set mailSubjectPartAction \"Error unable to check new os versio\\r
+    n\"\r\\r
+    \n        :set mailPtBodyAction  \"An error occurred while checking for a \\r
+    new RouterOS version.\\nStatus returned: `\$packageUpdateStatus`\\n\\nPlea\\r
+    se review the logs on the device for more details and verify internet conn\\r
+    ectivity.\"\r\\r
+    \n      }\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  # Checking if the script needs to install new os version\r\\r
+    \n  :if (\$scriptMode = \"osupdate\" and \$isNewOsUpdateAvailable = true) \\r
+    do={\r\\r
+    \n    :if (\$installOnlyPatchUpdates = true) do={\r\\r
+    \n      :if ([\$FuncIsPatchUpdateOnly \$runningOsVersion \$routerOsVersion\\r
+    Available] = true) do={\r\\r
+    \n        :log info \"\$SMP New RouterOS version is available, and it is a\\r
+    \_patch update. Current version: v\$runningOsVersion, new version: v\$rout\\r
+    erOsVersionAvailable\"\r\\r
+    \n        :set isOsNeedsToBeUpdated true\r\\r
+    \n      } else={\r\\r
+    \n        :log info \"\$SMP The script will not install this update, becau\\r
+    se it is not a patch update. Current version: v\$runningOsVersion, new ver\\r
+    sion: v\$routerOsVersionAvailable\"\r\\r
+    \n        :set mailPtBodyAction (\$mailPtBodyAction . \"\\nThis update wil\\r
+    l not be installed, because the script is set to install only patch update\\r
+    s.\")\r\\r
+    \n      }\r\\r
+    \n    } else={\r\\r
+    \n      :set isOsNeedsToBeUpdated true\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n\r\\r
+    \n  # Checking If the script needs to create a backup\r\\r
+    \n  :if (\$forceBackup = true or \$scriptMode = \"backup\" or \$isOsNeedsT\\r
+    oBeUpdated = true) do={\r\\r
+    \n    :log info (\"\$SMP Starting backup process.\")\r\\r
+    \n\r\\r
+    \n    :set isEmailNeedsToBeSent true\r\\r
+    \n\r\\r
+    \n    :local backupName \$backupNameTemplate\r\\r
+    \n\r\\r
+    \n    # This means it's the first step where we create a backup before the\\r
+    \_update process\r\\r
+    \n    :if (\$isOsNeedsToBeUpdated = true) do={\r\\r
+    \n      :set backupName \$backupNameBeforeUpdate\r\\r
+    \n\r\\r
+    \n      #Email body if the purpose of the script is to update the device\r\\r
+    \n      :set mailSubjectPartAction \"Update preparation\"\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nThe update proces\\r
+    s for device '\$deviceIdentityName' is scheduled to upgrade RouterOS from \\r
+    version v.\$runningOsVersion to version v.\$routerOsVersionAvailable (Upda\\r
+    te channel: \$updateChannel)\")\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nPlease note: The \\r
+    update will proceed only after a successful backup.\")\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nA final report wi\\r
+    th detailed information will be sent once the update process is completed.\\r
+    \")\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nIf you do not rec\\r
+    eive a second email within the next 10 minutes, there may be an issue. Ple\\r
+    ase check your device logs for further information.\")\r\\r
+    \n    }\r\\r
+    \n\r\\r
+    \n    :do {\r\\r
+    \n      :set mailAttachments [\$FuncCreateBackups \$backupName \$backupPas\\r
+    sword \$sensitiveDataInConfig];\r\\r
+    \n\r\\r
+    \n      :set mailPtSubjectBackup \"Backup created\"\r\\r
+    \n      :set mailPtBodyBackup \"System backups have been successfully crea\\r
+    ted and attached to this email.\"\r\\r
+    \n    } on-error={\r\\r
+    \n      #failed to create backup\r\\r
+    \n      :set isOsNeedsToBeUpdated false\r\\r
+    \n\r\\r
+    \n      :set mailPtSubjectBackup \"Backup failed\"\r\\r
+    \n      :set mailPtBodyBackup \"The script failed to create backups. Pleas\\r
+    e check device logs for more details.\"\r\\r
+    \n\r\\r
+    \n      :log warning \"\$SMP Backup creation failed. Update process will b\\r
+    e canceled if automatic update is enabled\"\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :if (\$isEmailNeedsToBeSent = true) do={\r\\r
+    \n    :log info \"\$SMP Preparing to send email...\"\r\\r
+    \n\r\\r
+    \n    :local mailStep1Subject \$mailSubjectPrefix\r\\r
+    \n    :local mailStep1Body  \"\"\r\\r
+    \n\r\\r
+    \n    # subject\r\\r
+    \n    :if (\$mailSubjectPartAction != \"\")  do={:set mailStep1Subject (\$\\r
+    mailStep1Subject . \" - \" . \$mailSubjectPartAction)}\r\\r
+    \n    :if (\$mailPtSubjectBackup != \"\")  do={:set mailStep1Subject (\$ma\\r
+    ilStep1Subject . \" - \" . \$mailPtSubjectBackup)}\r\\r
+    \n    # body\r\\r
+    \n    :if (\$mailPtBodyAction != \"\") do={:set mailStep1Body (\$mailStep1\\r
+    Body . \$mailPtBodyAction . \"\\n\\n\")}\r\\r
+    \n    :if (\$mailPtBodyBackup != \"\") do={:set mailStep1Body (\$mailStep1\\r
+    Body . \$mailPtBodyBackup . \"\\n\\n\")}\r\\r
+    \n\r\\r
+    \n    :set mailStep1Body (\$mailStep1Body . \$mailBodyDeviceInfo . \"\\n\\\\r
+    n\" . \$mailBodyCopyright)\r\\r
+    \n\r\\r
+    \n    # Send email with backups\r\\r
+    \n    :do {\$FuncSendEmailSafe \$emailAddress \$mailStep1Subject \$mailSte\\r
+    p1Body \$mailAttachments} on-error={\r\\r
+    \n      :set isOsNeedsToBeUpdated false\r\\r
+    \n      :log error \"\$SMP The script will not proceed with the update pro\\r
+    cess, because the email was not sent.\"\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :if ([:len \$mailAttachments] > 0) do={\r\\r
+    \n    :log info \"\$SMP Cleaning up backup files from the file system...\"\\r
+    \r\\r
+    \n    /file remove \$mailAttachments;\r\\r
+    \n    :delay 2s;\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :if (\$isOsNeedsToBeUpdated = true) do={\r\\r
+    \n    :log info \"\$SMP everything is ready to install new RouterOS, going\\r
+    \_to start the update process and reboot the device.\"\r\\r
+    \n    :do {\r\\r
+    \n      :local nextStep 2\r\\r
+    \n      :if (\$isCloudHostedRouter = true) do={\r\\r
+    \n        :log info \"\$SMP The device is a cloud hosted router, the secon\\r
+    d step updating the Routerboard firmware will be skipped.\"\r\\r
+    \n        :set nextStep 3\r\\r
+    \n      }\r\\r
+    \n\r\\r
+    \n      :local scheduledCommand (\":delay 5s; /system scheduler remove BKP\\r
+    UPD-NEXT-BOOT-TASK; :global buGlobalVarScriptStep \$nextStep; :global buGl\\r
+    obalVarTargetOsVersion \\\"\$routerOsVersionAvailable\\\"; :delay 10s; /sy\\r
+    stem script run BackupAndUpdate;\")\r\\r
+    \n      /system scheduler add name=BKPUPD-NEXT-BOOT-TASK on-event=\$schedu\\r
+    ledCommand start-time=startup interval=0\r\\r
+    \n\r\\r
+    \n      /system package update install\r\\r
+    \n    } on-error={\r\\r
+    \n      # Failed to install new os version, remove the task\r\\r
+    \n      :do {/system scheduler remove BKPUPD-NEXT-BOOT-TASK} on-error={}\r\\r
+    \n\r\\r
+    \n      :log error \"\$SMP Failed to install new RouterOS version. Please \\r
+    check device logs for more details.\"\r\\r
+    \n\r\\r
+    \n      :local mailUpdateErrorSubject (\$mailSubjectPrefix . \" - Update f\\r
+    ailed\")\r\\r
+    \n      :local mailUpdateErrorBody \"The script was unable to install new \\r
+    RouterOS version. Please check device logs for more details.\"\r\\r
+    \n\r\\r
+    \n      # Send email with error\r\\r
+    \n      \$FuncSendEmailSafe \$emailAddress \$mailUpdateErrorSubject \$mail\\r
+    UpdateErrorBody \"\"\r\\r
+    \n\r\\r
+    \n      :error \$exitErrorMessage\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n## STEP 2: (Post-reboot) Upgrade RouterBOARD firmware\r\\r
+    \n## Runs only if auto-update is enabled and a new RouterOS version was fo\\r
+    und\r\\r
+    \n:if (\$scriptStep = 2) do={\r\\r
+    \n  :log info \"\$SMP The script is in the second step, updating Routerboa\\r
+    rd firmware.\"\r\\r
+    \n\r\\r
+    \n  :log info \"\$SMP Upgrading routerboard firmware from v.\$deviceRbCurr\\r
+    entFw to v.\$deviceRbUpgradeFw\"\r\\r
+    \n\r\\r
+    \n  /system routerboard upgrade\r\\r
+    \n  :delay 2s\r\\r
+    \n\r\\r
+    \n  :log info \"\$SMP routerboard upgrade process was completed, going to \\r
+    reboot in a moment!\";\r\\r
+    \n\r\\r
+    \n  ## Set task to send final report on the next boot\r\\r
+    \n  /system scheduler add name=BKPUPD-NEXT-BOOT-TASK on-event=\":delay 5s;\\r
+    \_/system scheduler remove BKPUPD-NEXT-BOOT-TASK; :global buGlobalVarScrip\\r
+    tStep 3; :global buGlobalVarTargetOsVersion \\\"\$buGlobalVarTargetOsVersi\\r
+    on\\\"; :delay 10s; /system script run BackupAndUpdate;\" start-time=start\\r
+    up interval=0\r\\r
+    \n\r\\r
+    \n  /system reboot;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n## STEP 3: Final report (after second reboot, with delay).\r\\r
+    \n## Runs only if auto-update is enabled and a new RouterOS version was fo\\r
+    und.\r\\r
+    \n:if (\$scriptStep = 3) do={\r\\r
+    \n  :log info (\"\$SMP The script is in the third step, sending final repo\\r
+    rt.\")\r\\r
+    \n\r\\r
+    \n  :local targetOsVersion \$buGlobalVarTargetOsVersion\r\\r
+    \n  :do {/system script environment remove buGlobalVarTargetOsVersion} on-\\r
+    error={}\r\\r
+    \n  :if ([:len \$targetOsVersion] = 0) do={\r\\r
+    \n    :log warning \"\$SMP Something is wrong, the script was unable to ge\\r
+    t the target updated OS version from the global variable.\"\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :local mailStep3Subject \$mailSubjectPrefix\r\\r
+    \n  :local mailStep3Body  \"\"\r\\r
+    \n\r\\r
+    \n  :if (\$targetOsVersion = \$runningOsVersion) do={\r\\r
+    \n    :log info \"\$SMP Successfully verified new RouterOS version: target\\r
+    : `\$targetOsVersion`, current: `\$runningOsVersion`\"\r\\r
+    \n\r\\r
+    \n    :set mailStep3Subject (\$mailStep3Subject . \" - Update completed - \\r
+    Backup created\")\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"RouterOS and routerboard upg\\r
+    rade process was completed\")\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"\\nNew RouterOS version: v.\\r
+    \$targetOsVersion, routerboard firmware: v.\$deviceRbCurrentFw\")\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"\\n\$changelogUrl\\nBackups \\r
+    of the upgraded system are in the attachment of this email.\\n\\n\$mailBod\\r
+    yDeviceInfo\\n\\n\$mailBodyCopyright\")\r\\r
+    \n\r\\r
+    \n    :set mailAttachments [\$FuncCreateBackups \$backupNameAfterUpdate \$\\r
+    backupPassword \$sensitiveDataInConfig];\r\\r
+    \n  } else={\r\\r
+    \n    :log error \"\$SMP Failed to verify new RouterOS version: target: `\\r
+    \$targetOsVersion`, current: `\$runningOsVersion`\"\r\\r
+    \n    :set mailStep3Subject (\$mailStep3Subject . \" - Update failed\")\r\\r
+    \n\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"The script was unable to ver\\r
+    ify that the new RouterOS version was installed, target version: `\$target\\r
+    OsVersion`, current version: `\$runningOsVersion`\\nCheck device logs for \\r
+    more details.\\n\\n\$mailBodyDeviceInfo\\n\\n\$mailBodyCopyright\")\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  \$FuncSendEmailSafe \$emailAddress \$mailStep3Subject \$mailStep3Body \\r
+    \$mailAttachments\r\\r
+    \n\r\\r
+    \n  :if ([:len \$mailAttachments] > 0) do={\r\\r
+    \n    :log info \"\$SMP Cleaning up backup files from the file system...\"\\r
+    \r\\r
+    \n    /file remove \$mailAttachments;\r\\r
+    \n    :delay 2s;\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :log info \"\$SMP Final report email sent successfully, and the script\\r
+    \_has finished.\"\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:log info \"\$SMP the script has finished, script step: `\$scriptStep` \\r
+    \\n\\n\""\r
+add comment="Certificates CloudFlare" dont-require-permissions=no name=\\r
+    Certificate_CloudFlare owner=vados policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="/\\r
+    tool fetch url=https://cacerts.digicert.com/DigiCertGlobalRootCA.crt.pem\r\\r
+    \n/certificate import file-name=DigiCertGlobalRootCA.crt.pem passphrase=\"\\r
+    \"\r\\r
+    \n/tool fetch url=https://cacerts.digicert.com/DigiCertGlobalG2TLSRSASHA25\\r
+    62020CA1-1.crt.pem\r\\r
+    \n/certificate import file-name=DigiCertGlobalG2TLSRSASHA2562020CA1-1.crt.\\r
+    pem passphrase=\"\"\r\\r
+    \n#/ip dns set allow-remote-requests=yes doh-max-concurrent-queries=100 do\\r
+    h-max-server-connections=20 use-doh-server=https://security.cloudflare-dns\\r
+    .com/dns-query verify-doh-cert=yes\r\\r
+    \n#/ip dns static add address=1.1.1.1 name=security.cloudflare-dns.com\r\\r
+    \n#/ip dns static add address=1.0.0.1 name=security.cloudflare-dns.com\r\\r
+    \n#/ip dns static add address=2606:4700:4700::1111 name=security.cloudflar\\r
+    e-dns.com type=AAAA\r\\r
+    \n#/ip dns static add address=2606:4700:4700::1001 name=security.cloudflar\\r
+    e-dns.com type=AAAA\r\\r
+    \n#/ip dns set servers=\"\""\r
+add dont-require-permissions=no name=Amster-Backup-UpdateEmail owner=vados \\r
+    policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon \\r
+    source="#!rsc by/// Vados\r\\r
+    \n# RouterOS script: Amster-Backup-UpdateEmail\r\\r
+    \n# Script comment: Update and Backup send notification to EMail\r\\r
+    \n#\r\\r
+    \n#\r\\r
+    \n# requires RouterOS, version>=6.43.7\r\\r
+    \n# requires device-mode, fetch\r\\r
+    \n#\r\\r
+    \n# Updated: 15/04/2025\r\\r
+    \n# Website: https://github.com/beeyev\r\\r
+    \n# Notification e-mail (Make sure you have configured Email settings in T\\r
+    ools -> Email)\r\\r
+    \n:local ExitOK false;\r\\r
+    \n:onerror Err {\r\\r
+    \n  :global GlobalConfReady; :global GlobalFuncReady;\r\\r
+    \n  :retry { :if (\$GlobalConfReady != true || \$GlobalFuncReady != true) \\r
+    \\\r\\r
+    \n      do={ :error (\"Global config and/or functions not ready.\"); }; } \\r
+    delay=500ms max=50;\r\\r
+    \n  :local ScriptName [ :jobname ];\r\\r
+    \n\r\\r
+    \n:global LogPrint;\r\\r
+    \n\r\\r
+    \n# Add scheduler\r\\r
+    \n:if ([ :len [ /system/scheduler/find where name=\$ScriptName ] ] = 0) do\\r
+    ={\r\\r
+    \n  \$LogPrint warning \$ScriptName (\"SystemScheduler NOT SET!\");\r\\r
+    \n  /system/scheduler/add name=\$ScriptName on-event=\"/system/script { ru\\r
+    n \$ScriptName; }\" comment=\"Scheduler for \$ScriptName\" interval=\"7d 0\\r
+    0:00:00\" policy=ftp,reboot,read,write,policy,test,password,sniff,sensitiv\\r
+    e,romon start-time=\"03:41:27\"; \r\\r
+    \n  :set ExitOK true;\r\\r
+    \n  :error false;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:global EmailGeneralTo;\r\\r
+    \n:global BackupAndUpdateMode;\r\\r
+    \n:global forceBackup;\r\\r
+    \n:global BackupPassword;\r\\r
+    \n:global BackupSens;\r\\r
+    \n:global updateChannel;\r\\r
+    \n:global getPubIp;\r\\r
+    \n\r\\r
+    \n# Installs patch updates only (BackupAndUpdateMode = \"osupdate\").\r\\r
+    \n# Works for `stable` and `long-term` channels.\r\\r
+    \n# Updates only if MAJOR.MINOR match (e.g. 6.43.2 > 6.43.6 allowed, 6.44.\\r
+    1 skipped).\r\\r
+    \n# Sends info if a newer (non-patch) version is found.\r\\r
+    \n:local installOnlyPatchUpdates false\r\\r
+    \n:local scriptVersion \"26.02.12\"\r\\r
+    \n\r\\r
+    \n# Include public IP info in email if set to true\r\\r
+    \n:local includePubIpAddr true;\r\\r
+    \n# default and fallback public IP detection services\r\\r
+    \n:local ipAddrDefault \"https://ipv4.mikrotik.ovh/\";\r\\r
+    \n:local ipAddrFallback \"https://api.ipify.org/\";\r\\r
+    \n\r\\r
+    \n#Script messages prefix\r\\r
+    \n:local SMP \"BkpAndUpdate:\"\r\\r
+    \n\r\\r
+    \n:local exitErrorMessage \"\$SMP script stopped due to an error. Please c\\r
+    heck logs for more details.\"\r\\r
+    \n:log info \"\\n\\n\$SMP Script \\\"Mikrotik RouterOS automatic backup & \\r
+    update\\\" v.\$scriptVersion started.\"\r\\r
+    \n:log info \"\$SMP Script Mode: `\$BackupAndUpdateMode`, Update channel: \\r
+    `\$updateChannel`, Force backup: `\$forceBackup`, Install only patch updat\\r
+    es: `\$installOnlyPatchUpdates`\"\r\\r
+    \n\r\\r
+    \n## vv FUNCTIONS vv ##\r\\r
+    \n\r\\r
+    \n# Returns currently running RouterOS version\r\\r
+    \n# :put [\$FuncGetRunningOsVersion]  # Output: 6.48.1\r\\r
+    \n:local FuncGetRunningOsVersion do={\r\\r
+    \n  :local runningOsAndChannel [/system resource get version];\r\\r
+    \n  :local spacePos [:find \$runningOsAndChannel \" \"];\r\\r
+    \n  :if ([:len \$spacePos] = 0) do={\r\\r
+    \n    :log error \"\$SMP Could not extract installed OS version string: `\\r
+    \$runningOsAndChannel`.\";\r\\r
+    \n    :error \"\$SMP error, check logs\";\r\\r
+    \n  }\r\\r
+    \n  :local versionOnly [:pick \$runningOsAndChannel 0 \$spacePos];\r\\r
+    \n  :return \$versionOnly;\r\\r
+    \n}\r\\r
+    \n# Returns currently running RouterOS channel\r\\r
+    \n# :put [\$FuncGetRunningOsChannel]  # Output: stable\r\\r
+    \n:local FuncGetRunningOsChannel do={\r\\r
+    \n  :local runningOsAndChannel [/system resource get version];\r\\r
+    \n  :local open [:find \$runningOsAndChannel \"(\"];\r\\r
+    \n  :if ([:len \$open] = 0) do={\r\\r
+    \n    :log error \"\$SMP Could not extract installed OS channel from versi\\r
+    on string: `\$runningOsAndChannel`.\";\r\\r
+    \n    :error \"\$SMP error, check logs\";\r\\r
+    \n  }\r\\r
+    \n  :local rest [:pick \$runningOsAndChannel (\$open+1) [:len \$runningOsA\\r
+    ndChannel]];\r\\r
+    \n  :local close [:find \$rest \")\"];\r\\r
+    \n  :local channel [:pick \$rest 0 \$close];\r\\r
+    \n  :return \$channel;\r\\r
+    \n}\r\\r
+    \n# Checks if two RouterOS version strings differ only by the patch versio\\r
+    n\r\\r
+    \n# :put [\$FuncIsPatchUpdateOnly \"6.2.1\" \"6.2.4\"]  # Output: true\r\\r
+    \n# :put [\$FuncIsPatchUpdateOnly \"6.2.1\" \"6.3.1\"]  # Output: false\r\\r
+    \n:local FuncIsPatchUpdateOnly do={\r\\r
+    \n  :local ver1 \$1;\r\\r
+    \n  :local ver2 \$2;\r\\r
+    \n  # Extract the major and minor components from a version\r\\r
+    \n  :local extractMajorMinor do={\r\\r
+    \n    :local ver \$1;\r\\r
+    \n    :local dot1 [:find \$ver \".\"];\r\\r
+    \n    :if (\$dot1 = -1) do={:return \$ver}\r\\r
+    \n    :local major [:pick \$ver 0 \$dot1];\r\\r
+    \n    :local rest [:pick \$ver (\$dot1 + 1) [:len \$ver]];\r\\r
+    \n    :local dot2 [:find \$rest \".\"];\r\\r
+    \n    :local minor \$rest;\r\\r
+    \n    :if (\$dot2 >= 0) do={:set minor [:pick \$rest 0 \$dot2]}\r\\r
+    \n    :return (\$major . \".\" . \$minor);\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n# Compare the major and minor components of both version strings\r\\r
+    \n:if ([\$extractMajorMinor \$ver1] = [\$extractMajorMinor \$ver2]) do={:r\\r
+    eturn true}\r\\r
+    \n :return false;\r\\r
+    \n}\r\\r
+    \n# Creates backups and returns array of names\r\\r
+    \n# Possible arguments:\r\\r
+    \n#  \$1 - file name, without extension\r\\r
+    \n#  \$2 - password (optional)\r\\r
+    \n#  \$3 - sensitive data in config (optional, default: false)\r\\r
+    \n# Example:\r\\r
+    \n#:put [\$FuncCreateBackups \$backupName]\r\\r
+    \n:local FuncCreateBackups do={\r\\r
+    \n  :local backupName [ :tostr \$1 ];\r\\r
+    \n  :local BackPass \$2;\r\\r
+    \n  :local BackSens \$3;\r\\r
+    \n\r\\r
+    \n  #Script messages prefix\r\\r
+    \n  :local SMP \"BkpAndUpdate:\";\r\\r
+    \n  :local exitErrorMessage \"\$SMP script stopped due to an error. Please\\r
+    \_check logs for more details.\";\r\\r
+    \n  :log info (\"\$SMP global function `FuncCreateBackups` started, input:\\r
+    \_`\$backupName`\");\r\\r
+    \n\r\\r
+    \n  # validate required parameter: backupName\r\\r
+    \n  :if ([:typeof \$backupName] != \"str\" or [:len \$backupName] = 0) do=\\r
+    {\r\\r
+    \n    :log error \"\$SMP parameter 'backupName' is required and must be a \\r
+    non-empty string\";\r\\r
+    \n#    :log warning \"\$SMP parameter '\\\$backupName' is required and mus\\r
+    t be a non-empty string.\\nI set '\\\$backupName' to 'default-backup'\";\r\\r
+    \n#    :set \$backupName \"default-backup\";\r\\r
+    \n    :error \$exitErrorMessage;\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :local backupFileSys \"\$backupName.backup\";\r\\r
+    \n  :local backupFileConfig \"\$backupName.rsc\";\r\\r
+    \n  :local backupNames {\$backupFileSys;\$backupFileConfig};\r\\r
+    \n\r\\r
+    \n  ## Perform system backup\r\\r
+    \n  :if ([:len \$BackPass] = 0) do={\r\\r
+    \n    :log info (\"\$SMP starting backup without password, backup name: `\\r
+    \$backupName`\");\r\\r
+    \n    /system backup save dont-encrypt=yes name=\$backupName;\r\\r
+    \n  } else={\r\\r
+    \n    :log info (\"\$SMP starting backup with password, backup name: `\$ba\\r
+    ckupName`\");\r\\r
+    \n    /system backup save password=\$BackPass name=\$backupName;\r\\r
+    \n  }\r\\r
+    \n  :log info (\"\$SMP system backup created: `\$backupFileSys`\");\r\\r
+    \n    ## Export config file\r\\r
+    \n  :if (\$BackSens = true) do={\r\\r
+    \n    :log info (\"\$SMP starting export config with sensitive data, backu\\r
+    p name: `\$backupName`\");\r\\r
+    \n    # Since RouterOS v7 it needs to be explicitly set that we want to ex\\r
+    port sensitive data\r\\r
+    \n    :if ([:pick [/system resource get version] 0 1] < 7) do={\r\\r
+    \n      :execute \"/export compact terse file=\$backupName\";\r\\r
+    \n    } else={\r\\r
+    \n      :execute \"/export compact show-sensitive terse file=\$backupName\\r
+    \";\r\\r
+    \n    }\r\\r
+    \n  } else={\r\\r
+    \n    :log info (\"\$SMP starting export config without sensitive data, ba\\r
+    ckup name: `\$backupName`\");\r\\r
+    \n    /export compact hide-sensitive terse file=\$backupName;\r\\r
+    \n  }\r\\r
+    \n  :log info (\"\$SMP Config export complete: `\$backupFileConfig`\");\r\\r
+    \n  :log info (\"\$SMP Waiting a little to ensure backup files are written\\r
+    \");\r\\r
+    \n  :delay 20;\r\\r
+    \n  :if ([:len [/file find name=\$backupFileSys]] > 0) do={\r\\r
+    \n    :log info (\"\$SMP system backup file successfully saved to the file\\r
+    \_system: `\$backupFileSys`\");\r\\r
+    \n  } else={\r\\r
+    \n    :log error (\"\$SMP system backup was not created, file does not exi\\r
+    st: `\$backupFileSys`\");\r\\r
+    \n    :error \$exitErrorMessage;\r\\r
+    \n  }\r\\r
+    \n  :if ([:len [/file find name=\$backupFileConfig]] > 0) do={\r\\r
+    \n    :log info (\"\$SMP config backup file successfully saved to the file\\r
+    \_system: `\$backupFileConfig`\");\r\\r
+    \n  } else={\r\\r
+    \n    :log error (\"\$SMP config backup was not created, file does not exi\\r
+    st: `\$backupFileConfig`\");\r\\r
+    \n    :error \$exitErrorMessage;\r\\r
+    \n  }\r\\r
+    \n  :log info (\"\$SMP global function `FuncCreateBackups` finished. Creat\\r
+    ed backups, system: `\$backupFileSys`, config: `\$backupFileConfig`\")\r\\r
+    \n  :return \$backupNames;\r\\r
+    \n}\r\\r
+    \n# Sends an email\r\\r
+    \n# Parameters:\r\\r
+    \n#  \$1 - to (email address)\r\\r
+    \n#  \$2 - subject\r\\r
+    \n#  \$3 - body\r\\r
+    \n#  \$4 - file attachments (optional; pass \"\" if not needed)\r\\r
+    \n#\r\\r
+    \n# Example:\r\\r
+    \n# \$FuncSendEmailSafe \"admin@domain.com\" \"Backup Done\" \"Backup comp\\r
+    lete.\" \"backup1.backup\"\r\\r
+    \n:local FuncSendEmailSafe do={\r\\r
+    \n  :global EmailGeneralTo;\r\\r
+    \n  :local emailSubject \$2;\r\\r
+    \n  :local emailBody \$3;\r\\r
+    \n  :local emailAttachments \$4;\r\\r
+    \n  :local SMP \"Bkp&Upd:\";\r\\r
+    \n  :local exitErrorMessage \"\$SMP script stopped due to an error. Please\\r
+    \_check logs for more details.\";\r\\r
+    \n  :log info \"\$SMP Attempting to send email to `\$EmailGeneralTo`\";\r\\r
+    \n  # SAFETY: wait for any previously queued email to finish\r\\r
+    \n  :local waitTimeoutPre 60;\r\\r
+    \n  :local waitCounterPre 0;\r\\r
+    \n  :while (([/tool e-mail get last-status] = \"resolving-dns\" or [/tool \\r
+    e-mail get last-status] = \"in-progress\")) do={\r\\r
+    \n    :if (\$waitCounterPre >= \$waitTimeoutPre) do={\r\\r
+    \n      :log error \"\$SMP Email send aborted: previous send did not compl\\r
+    ete after \$waitTimeoutPre seconds\";\r\\r
+    \n      :error \$exitErrorMessage;\r\\r
+    \n    }\r\\r
+    \n    :log info \"\$SMP Waiting for previous email to finish (status: \$[/\\r
+    tool e-mail get last-status])...\";\r\\r
+    \n    :delay 1; \r\\r
+    \n    :set waitCounterPre (\$waitCounterPre + 1);\r\\r
+    \n  }\r\\r
+    \n  # Send the email\r\\r
+    \n  :do {\r\\r
+    \n    /tool e-mail send to=\$EmailGeneralTo subject=\$emailSubject body=\$\\r
+    emailBody file=\$emailAttachments;\r\\r
+    \n  } on-error={\r\\r
+    \n    :log error \"\$SMP Email send command failed to execute. Check logs \\r
+    and verify email settings.\";\r\\r
+    \n    :error \$exitErrorMessage;\r\\r
+    \n  }\r\\r
+    \n  # Wait for send status to change from \"in-progress\" / \"resolving-dn\\r
+    s\"\r\\r
+    \n  :local waitTimeout 60;\r\\r
+    \n  :local waitCounter 0;\r\\r
+    \n  :local emailStatus \"\";\r\\r
+    \n  :log info \"\$SMP Waiting for email to be sent, timeout in `\$waitTime\\r
+    out` seconds...\";\r\\r
+    \n  :while (\$waitCounter < \$waitTimeout) do={\r\\r
+    \n    :set emailStatus [/tool e-mail get last-status];\r\\r
+    \n    :if (\$emailStatus != \"in-progress\" and \$emailStatus != \"resolvi\\r
+    ng-dns\") do={\r\\r
+    \n      :log info \"\$SMP Email send status received: \$emailStatus\";\r\\r
+    \n      # exit loop\r\\r
+    \n      :set waitCounter \$waitTimeout;\r\\r
+    \n    } else={:delay 1; :set waitCounter (\$waitCounter + 1)}\r\\r
+    \n  }\r\\r
+    \n  # Final decision based on last status\r\\r
+    \n  :if (\$emailStatus = \"succeeded\") do={\r\\r
+    \n    :log info  \"\$SMP Email successfully sent to `\$EmailGeneralTo`\";\\r
+    \r\\r
+    \n  } else={\r\\r
+    \n    :log error \"\$SMP Email failed to send. Status: `\$emailStatus`. Ch\\r
+    eck logs for more details and verify email settings.\";\r\\r
+    \n    :error \$exitErrorMessage;\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n# Global variable to track current update step\r\\r
+    \n# They need to be initialized here first to be available in the script\r\\r
+    \n:global buGlobalVarTargetOsVersion;\r\\r
+    \n:global buGlobalVarScriptStep;\r\\r
+    \n:local scriptStep \$buGlobalVarScriptStep;\r\\r
+    \n:do {/system script environment remove buGlobalVarScriptStep} on-error={\\r
+    }\r\\r
+    \n:if ([:len \$scriptStep] = 0) do={\r\\r
+    \n  :set scriptStep 1;\r\\r
+    \n}\r\\r
+    \n## ^^ FUNCTIONS ^^ ##\r\\r
+    \n#\r\\r
+    \n# Initial validation\r\\r
+    \n## Check email settings\r\\r
+    \n:if ([:len \$EmailGeneralTo] < 3) do={\r\\r
+    \n  :log error (\"\$SMP Parameter `\\\$EmailGeneralTo` is not set, or cont\\r
+    ains invalid value. Script stopped.\");\r\\r
+    \n  :error \$exitErrorMessage;\r\\r
+    \n}\r\\r
+    \n# Values will be defined later in the script\r\\r
+    \n:local emailServer \"\";\r\\r
+    \n:local emailFromAddress [/tool e-mail get from];\r\\r
+    \n:log info \"\$SMP Validating email settings...\";\r\\r
+    \n:do {\r\\r
+    \n  :set emailServer [/tool e-mail get server];\r\\r
+    \n} on-error={\r\\r
+    \n  # This is a workaround for the RouterOS v7.12 and older versions\r\\r
+    \n  :set emailServer [/tool e-mail get address];\r\\r
+    \n}\r\\r
+    \n:if (\$emailServer = \"0.0.0.0\") do={\r\\r
+    \n  :log error (\"\$SMP Email server address is not correct: `\$emailServe\\r
+    r`, check `Tools -> Email`. Script stopped.\");\r\\r
+    \n  :error \$exitErrorMessage;\r\\r
+    \n}\r\\r
+    \n:if ([:len \$emailFromAddress] < 3) do={\r\\r
+    \n  :log error (\"\$SMP Email configuration FROM address is not correct: `\\r
+    \$emailFromAddress`, check `Tools -> Email`. Script stopped.\");\r\\r
+    \n  :error \$exitErrorMessage;\r\\r
+    \n}\r\\r
+    \n# Script mode validation\r\\r
+    \n:if (\$BackupAndUpdateMode != \"backup\" and \$BackupAndUpdateMode != \"\\r
+    osupdate\" and \$BackupAndUpdateMode != \"updateOnce\" and \$BackupAndUpda\\r
+    teMode != \"osnotify\") do={\r\\r
+    \n  :log error (\"\$SMP Script parameter `\\\$BackupAndUpdateMode` is not \\r
+    set, or contains invalid value: `\$BackupAndUpdateMode`. Script stopped.\"\\r
+    );\r\\r
+    \n  :error \$exitErrorMessage;\r\\r
+    \n}\r\\r
+    \n# Update channel validation\r\\r
+    \n:if (\$updateChannel != \"stable\" and \$updateChannel != \"long-term\" \\r
+    and \$updateChannel != \"testing\" and \$updateChannel != \"development\")\\r
+    \_do={\r\\r
+    \n  :log error (\"\$SMP Script parameter `\\\$updateChannel` is not set, o\\r
+    r contains invalid value: `\$updateChannel`. Script stopped.\");\r\\r
+    \n  :error \$exitErrorMessage;\r\\r
+    \n}\r\\r
+    \n# Verify if script is set to install patch updates and if the update cha\\r
+    nnel is valid\r\\r
+    \n:if ((\$BackupAndUpdateMode = \"osupdate\" or \$BackupAndUpdateMode = \"\\r
+    updateOnce\") and \$installOnlyPatchUpdates = true) do={\r\\r
+    \n  :if (\$updateChannel != \"stable\" and \$updateChannel != \"long-term\\r
+    \") do={\r\\r
+    \n    :log error (\"\$SMP Patch-only updates enabled, but update channel `\\r
+    \$updateChannel` is invalid. Only `stable` and `long-term` are supported. \\r
+    Script stopped\");\r\\r
+    \n    :error \$exitErrorMessage;\r\\r
+    \n  }\r\\r
+    \n  :local susRunningOsChannel [\$FuncGetRunningOsChannel];\r\\r
+    \n  :if (\$susRunningOsChannel != \"stable\" and \$susRunningOsChannel != \\r
+    \"long-term\") do={\r\\r
+    \n    :log error (\"\$SMP Script is set to install only patch updates, but\\r
+    \_the installed RouterOS version is not from `stable` or `long-term` chann\\r
+    el: `\$susRunningOsChannel`. Script stopped\");\r\\r
+    \n    :error \$exitErrorMessage;\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n#\r\\r
+    \n:global MiniDateTimeStamp;\r\\r
+    \n:local MDTSFix [\$MiniDateTimeStamp];\r\\r
+    \n:global Identity;\r\\r
+    \n:global IdentityShort;\r\\r
+    \n:global devBoardName;\r\\r
+    \n:global isCHR;\r\\r
+    \n:global devRbModel;\r\\r
+    \n:global devRbSerialNumber;\r\\r
+    \n:global devRbCurrentFw;\r\\r
+    \n:global devRbUpgradeFw;\r\\r
+    \n\r\\r
+    \n:local rawTime [/system clock get time];\r\\r
+    \n:local rawDate [/system clock get date];\r\\r
+    \n\r\\r
+    \n:local runningOsChannel [\$FuncGetRunningOsChannel];\r\\r
+    \n:local runningOsVersion [\$FuncGetRunningOsVersion];\r\\r
+    \n:local deviceOsVerAndChannelRunning [/system resource get version];\r\\r
+    \n\r\\r
+    \n:local backupNameTemplate     (\"backup_v\" . \$runningOsVersion . \"_\"\\r
+    \_. \$runningOsChannel . \"_\" . \$MDTSFix);\r\\r
+    \n:local backupNameBeforeUpdate (\$backupNameTemplate . \"_before_update\"\\r
+    );\r\\r
+    \n:local backupNameAfterUpdate  (\$backupNameTemplate . \"_after_update\")\\r
+    ;\r\\r
+    \n\r\\r
+    \n## Email body template\r\\r
+    \n:local mailSubjectPrefix  \"\$SMP Device - `\$IdentityShort`\";\r\\r
+    \n:local mailBodyCopyright  \"Mikrotik RouterOS automatic backup & update \\r
+    (ver. \$scriptVersion) \\nhttps://github.com/beeyev/Mikrotik-RouterOS-auto\\r
+    matic-backup-and-update\";\r\\r
+    \n:local changelogUrl     \"Check RouterOS changelog: https://mikrotik.com\\r
+    /download/changelogs/\";\r\\r
+    \n:local mailBodyDeviceInfo  \"\";\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"Device information:\")\\r
+    ;\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\n-------------------\\r
+    --\");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nName: \$Identity\")\\r
+    ;\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nModel: \$devRbModel\\r
+    \");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nBoard: \$devBoardNa\\r
+    me\");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nSerial number: \$de\\r
+    vRbSerialNumber\");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nRouterOS version: v\\r
+    \$deviceOsVerAndChannelRunning\");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nBuild time: \$[/sys\\r
+    tem resource get build-time]\");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nRouterboard FW: \$d\\r
+    evRbCurrentFw\");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nDevice date-time: \\r
+    \$rawDate \$rawTime (\$[/system clock get time-zone-name ])\");\r\\r
+    \n:set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nUptime: \$[/system \\r
+    resource get uptime]\");\r\\r
+    \n\r\\r
+    \n:local mailAttachments  [:toarray \"\"];\r\\r
+    \n:if (\$scriptStep = 1 or \$scriptStep = 3) do={\r\\r
+    \n  :if (\$scriptStep = 3) do={\r\\r
+    \n    :log info (\"\$SMP Waiting for one minute before continuing to the f\\r
+    inal step.\");\r\\r
+    \n    :delay 1m;\r\\r
+    \n  }\r\\r
+    \n## IP address detection\r\\r
+    \n  :local publicIpAddress \"not-detected\";\r\\r
+    \n  :if ([\$includePubIpAddr] = true) do={\r\\r
+    \n      :set publicIpAddress [ \$getPubIp \$ipAddrDefault ];\r\\r
+    \n      :if (([\$publicIpAddress] = false) || ([\$publicIpAddress] = \"not\\r
+    -detected\")) do={\r\\r
+    \n        :log warning \"\$SMP Failed to detect public IP using default se\\r
+    rvice: `\$ipAddrDefault`\";\r\\r
+    \n        :log warning \"\$SMP Trying fallback service: `\$ipAddrFallback`\\r
+    \";\r\\r
+    \n        :set publicIpAddress [ \$getPubIp \$ipAddrFallback ];\r\\r
+    \n        :if (([\$publicIpAddress] = false) || ([\$publicIpAddress] = \"n\\r
+    ot-detected\")) do={\r\\r
+    \n          :log warning \"\$SMP Could not detect public IP address using \\r
+    fallback detection service: `\$ipAddrFallback`\";\r\\r
+    \n        }\r\\r
+    \n      }\r\\r
+    \n    :set publicIpAddress ([ :pick \$publicIpAddress 0 15]);\r\\r
+    \n    :set mailBodyDeviceInfo (\$mailBodyDeviceInfo . \"\\nPublic IP addre\\r
+    ss: \$publicIpAddress\");\r\\r
+    \n    :log info \"\$SMP Public IP address detected: `\$publicIpAddress`\";\\r
+    \r\\r
+    \n  }  \r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n## STEP 1: Create backups, check for new RouterOS, and send email\r\\r
+    \n## Steps 2\C3\A23 run only if auto-update is enabled and a new version i\\r
+    s available\r\\r
+    \n:if (\$scriptStep = 1) do={\r\\r
+    \n  :global BackupPassword;\r\\r
+    \n  :global BackupSens;\r\\r
+    \n  :global ROsVerAvail 0.0.0;\r\\r
+    \n  :global PkgUpdStatus \"undefined\";\r\\r
+    \n  :local isNewOsUpdateAvailable false;\r\\r
+    \n  :local isLatestOsAlreadyInstalled true;\r\\r
+    \n  :local isOsNeedsToBeUpdated false;\r\\r
+    \n  :local isUpdateCheckSucceeded false;\r\\r
+    \n  :local isEmailNeedsToBeSent false;\r\\r
+    \n  :local mailSubjectPartAction \"\";\r\\r
+    \n  :local mailPtBodyAction \"\";\r\\r
+    \n  :local mailPtSubjectBackup \"\";\r\\r
+    \n  :local mailPtBodyBackup \"\";\r\\r
+    \n  # Checking for new version\r\\r
+    \n  :if (\$BackupAndUpdateMode = \"osupdate\" or \$BackupAndUpdateMode = \\r
+    \"osnotify\" or \$BackupAndUpdateMode = \"updateOnce\") do={\r\\r
+    \n    :log info (\"\$SMP Setting update channel to `\$updateChannel`\");\r\\r
+    \n     /system/package/update/set channel=\$updateChannel;\r\\r
+    \n    :log info (\"\$SMP Checking for new RouterOS version. Current instal\\r
+    led version is: `\$runningOsVersion`\");\r\\r
+    \n     /system/package/update check-for-updates;\r\\r
+    \n    :delay 5s;\r\\r
+    \n    :set PkgUpdStatus [ /system/package/update/get status ];\r\\r
+    \n    :if (\$PkgUpdStatus = \"New version is available\") do={\r\\r
+    \n      :set ROsVerAvail [/system/package/update/get latest-version];\r\\r
+    \n    }\r\\r
+    \n\r\\r
+    \n    :if (\$PkgUpdStatus = \"New version is available\") do={\r\\r
+    \n      :log info (\"\$SMP New RouterOS version is available: `\$ROsVerAva\\r
+    il`\");\r\\r
+    \n      :set isNewOsUpdateAvailable true;\r\\r
+    \n      :set isLatestOsAlreadyInstalled false;\r\\r
+    \n      :set isUpdateCheckSucceeded true;\r\\r
+    \n      :set isEmailNeedsToBeSent true;\r\\r
+    \n      :set mailSubjectPartAction \"New RouterOS available\";\r\\r
+    \n      :set mailPtBodyAction  \"New RouterOS version is available, curren\\r
+    t version: v\$runningOsVersion, new version: v\$ROsVerAvail. \\n\$changelo\\r
+    gUrl\";\r\\r
+    \n    } else={\r\\r
+    \n      :if (\$PkgUpdStatus = \"System is already up to date\") do={\r\\r
+    \n        :log info (\"\$SMP No new RouterOS version is available, the lat\\r
+    est version is already installed: `v\$runningOsVersion`\");\r\\r
+    \n        :set isUpdateCheckSucceeded true;\r\\r
+    \n        :set mailSubjectPartAction \"No os update available\";\r\\r
+    \n        :set mailPtBodyAction  \"No new RouterOS version is available, t\\r
+    he latest version is already installed: `v\$runningOsVersion`\";\r\\r
+    \n      } else={\r\\r
+    \n        :log error (\"\$SMP Failed to check for new RouterOS version. Pa\\r
+    ckage check status: `\$PkgUpdStatus`\");\r\\r
+    \n        :set isEmailNeedsToBeSent true;\r\\r
+    \n        :set mailSubjectPartAction \"Error unable to check new os versio\\r
+    n\";\r\\r
+    \n        :set mailPtBodyAction  \"An error occurred while checking for a \\r
+    new RouterOS version.\\nStatus returned: `\$PkgUpdStatus`\\n\\nPlease revi\\r
+    ew the logs on the device for more details and verify internet connectivit\\r
+    y.\";\r\\r
+    \n      }\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  # Checking if the script needs to install new os version\r\\r
+    \n  :if ((\$BackupAndUpdateMode = \"osupdate\" or \$BackupAndUpdateMode = \\r
+    \"updateOnce\") and \$isNewOsUpdateAvailable = true) do={\r\\r
+    \n    :if (\$installOnlyPatchUpdates = true) do={\r\\r
+    \n      :if ([\$FuncIsPatchUpdateOnly \$runningOsVersion \$ROsVerAvail] = \\r
+    true) do={\r\\r
+    \n        :log info \"\$SMP New RouterOS version is available, and it is a\\r
+    \_patch update. Current version: v\$runningOsVersion, new version: v\$ROsV\\r
+    erAvail\";\r\\r
+    \n        :set isOsNeedsToBeUpdated true;\r\\r
+    \n      } else={\r\\r
+    \n        :log info \"\$SMP The script will not install this update, becau\\r
+    se it is not a patch update. Current version: v\$runningOsVersion, new ver\\r
+    sion: v\$ROsVerAvail\";\r\\r
+    \n        :set mailPtBodyAction (\$mailPtBodyAction . \"\\nThis update wil\\r
+    l not be installed, because the script is set to install only patch update\\r
+    s.\");\r\\r
+    \n      }\r\\r
+    \n    } else={\r\\r
+    \n      :set isOsNeedsToBeUpdated true;\r\\r
+    \n      }\r\\r
+    \n  }\r\\r
+    \n  # Checking If the script needs to create a backup\r\\r
+    \n  :if (\$forceBackup = true or \$BackupAndUpdateMode = \"backup\" or \$i\\r
+    sOsNeedsToBeUpdated = true) do={\r\\r
+    \n    :log info (\"\$SMP Starting backup process.\");\r\\r
+    \n    :set isEmailNeedsToBeSent true;\r\\r
+    \n    :local backupName \$backupNameTemplate;\r\\r
+    \n    # This means it's the first step where we create a backup before the\\r
+    \_update process\r\\r
+    \n    :if (\$isOsNeedsToBeUpdated = true) do={\r\\r
+    \n      :set backupName \$backupNameBeforeUpdate;\r\\r
+    \n      #Email body if the purpose of the script is to update the device\r\\r
+    \n      :set mailSubjectPartAction \"Update preparation\";\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nThe update proces\\r
+    s for device '\$Identity' is scheduled to upgrade RouterOS from version v.\\r
+    \$runningOsVersion to version v.\$ROsVerAvail (Update channel: \$updateCha\\r
+    nnel)\");\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nPlease note: The \\r
+    update will proceed only after a successful backup.\");\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nA final report wi\\r
+    th detailed information will be sent once the update process is completed.\\r
+    \");\r\\r
+    \n      :set mailPtBodyAction (\$mailPtBodyAction . \"\\nIf you do not rec\\r
+    eive a second email within the next 10 minutes, there may be an issue. Ple\\r
+    ase check your device logs for further information.\");\r\\r
+    \n    }\r\\r
+    \n    :do {\r\\r
+    \n      :set mailAttachments [\$FuncCreateBackups \$backupName \$BackupPas\\r
+    sword \$BackupSens];\r\\r
+    \n      :set mailPtSubjectBackup \"Backup created\";\r\\r
+    \n      :set mailPtBodyBackup \"System backups have been successfully crea\\r
+    ted and attached to this email.\";\r\\r
+    \n    } on-error={\r\\r
+    \n      :set isOsNeedsToBeUpdated false;\r\\r
+    \n      :set mailPtSubjectBackup \"Backup failed\";\r\\r
+    \n      :set mailPtBodyBackup \"The script failed to create backups. Pleas\\r
+    e check device logs for more details.\";\r\\r
+    \n      :log warning \"\$SMP Backup creation failed. Update process will b\\r
+    e canceled if automatic update is enabled\";\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  :if (\$isEmailNeedsToBeSent = true) do={\r\\r
+    \n    :log info \"\$SMP Preparing to send email...\";\r\\r
+    \n    :local mailStep1Subject \$mailSubjectPrefix;\r\\r
+    \n    :local mailStep1Body  \"\";\r\\r
+    \n    # subject\r\\r
+    \n    :if (\$mailSubjectPartAction != \"\")  do={:set mailStep1Subject (\$\\r
+    mailStep1Subject . \" - \" . \$mailSubjectPartAction)}\r\\r
+    \n    :if (\$mailPtSubjectBackup != \"\")  do={:set mailStep1Subject (\$ma\\r
+    ilStep1Subject . \" - \" . \$mailPtSubjectBackup)}\r\\r
+    \n    # body\r\\r
+    \n    :if (\$mailPtBodyAction != \"\") do={:set mailStep1Body (\$mailStep1\\r
+    Body . \$mailPtBodyAction . \"\\n\\n\")}\r\\r
+    \n    :if (\$mailPtBodyBackup != \"\") do={:set mailStep1Body (\$mailStep1\\r
+    Body . \$mailPtBodyBackup . \"\\n\\n\")}\r\\r
+    \n    :set mailStep1Body (\$mailStep1Body . \$mailBodyDeviceInfo . \"\\n\\\\r
+    n\" . \$mailBodyCopyright);\r\\r
+    \n    # Send email with backups\r\\r
+    \n    :do {\$FuncSendEmailSafe \$EmailGeneralTo \$mailStep1Subject \$mailS\\r
+    tep1Body \$mailAttachments} on-error={\r\\r
+    \n      :set isOsNeedsToBeUpdated false;\r\\r
+    \n      :log error \"\$SMP The script will not proceed with the update pro\\r
+    cess, because the email was not sent.\";\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  :if ([:len \$mailAttachments] > 0) do={\r\\r
+    \n    :log info \"\$SMP Cleaning up backup files from the file system...\"\\r
+    ;\r\\r
+    \n    /file remove \$mailAttachments;\r\\r
+    \n    :delay 2s;\r\\r
+    \n  }\r\\r
+    \n  :if (\$isOsNeedsToBeUpdated = true) do={\r\\r
+    \n    :global OldMode;\r\\r
+    \n    :log info \"\$SMP everything is ready to install new RouterOS, going\\r
+    \_to start the update process and reboot the device.\";\r\\r
+    \n    :do {\r\\r
+    \n      :local nextStep 2;\r\\r
+    \n      :if (\$isCloudHostedRouter = true) do={\r\\r
+    \n        :log info \"\$SMP The device is a cloud hosted router, the secon\\r
+    d step updating the Routerboard firmware will be skipped.\";\r\\r
+    \n        :set nextStep 3;\r\\r
+    \n      }\r\\r
+    \n      :local scheduledCommand (\":delay 5s; /system/scheduler remove BKP\\r
+    UPD-NEXT-BOOT-TASK; \\\r\\r
+    \n       :global buGlobalVarScriptStep \$nextStep; :global buGlobalVarTarg\\r
+    etOsVersion \\\"\$ROsVerAvail\\\"; \\\r\\r
+    \n      :delay 10s; /system/script { run \$ScriptName; }\");\r\\r
+    \n      /system/scheduler add name=BKPUPD-NEXT-BOOT-TASK on-event=\$schedu\\r
+    ledCommand start-time=startup interval=0;\r\\r
+    \n      /system/package/update install;\r\\r
+    \n     } on-error={\r\\r
+    \n      # Failed to install new os version, remove the task and variables\\r
+    \r\\r
+    \n      :do {\r\\r
+    \n        /system/scheduler remove BKPUPD-NEXT-BOOT-TASK;\r\\r
+    \n        :set BackupAndUpdateMode \$OldMode;\r\\r
+    \n        :delay 2;\r\\r
+    \n        :do {\r\\r
+    \n          /system/script/environment remove [find name=\"buGlobalVarTarg\\r
+    etOsVersion\"];\r\\r
+    \n        } on-error={\r\\r
+    \n          :set \$mailSubjectPrefix (\$mailSubjectPrefix . \"ERROR Remove\\r
+    \_global variable \\\$buGlobalVarTargetOsVersion failed!\");\r\\r
+    \n        }\r\\r
+    \n        :if ([ :len \$OldMode ] > 0) do={\r\\r
+    \n          :do {\r\\r
+    \n            /system/script/environment remove [find name=\"OldMode\"];\r\\r
+    \n          } on-error={\r\\r
+    \n            :set \$mailSubjectPrefix (\$mailSubjectPrefix . \" ERROR Rem\\r
+    ove global variable \\\$OldMode failed!\");\r\\r
+    \n          }\r\\r
+    \n        }\r\\r
+    \n      } on-error={\r\\r
+    \n        :log error \"\$SMP Failed to install new RouterOS version. Pleas\\r
+    e check device logs for more details. \\\r\\r
+    \n        \\nAnd Failed to remove task and variables! Check it!\";\r\\r
+    \n        :set \$mailSubjectPrefix (\$mailSubjectPrefix . \" ERROR Remove \\r
+    task and global variables!\");\r\\r
+    \n      }\r\\r
+    \n      :log error \"\$SMP Failed to install new RouterOS version. Please \\r
+    check device logs for more details.\";\r\\r
+    \n      :local mailUpdateErrorSubject (\$mailSubjectPrefix . \" - Update f\\r
+    ailed\");\r\\r
+    \n      :local mailUpdateErrorBody \"The script was unable to install new \\r
+    RouterOS version. Please check device logs for more details.\";\r\\r
+    \n      # Send email with error\r\\r
+    \n      \$FuncSendEmailSafe \$EmailGeneralTo \$mailUpdateErrorSubject \$ma\\r
+    ilUpdateErrorBody \"\";\r\\r
+    \n      :error \$exitErrorMessage;\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n## STEP 2: (Post-reboot) Upgrade RouterBOARD firmware\r\\r
+    \n## Runs only if auto-update is enabled and a new RouterOS version was fo\\r
+    und\r\\r
+    \n:if (\$scriptStep = 2) do={\r\\r
+    \n  :log info \"\$SMP The script is in the second step, updating Routerboa\\r
+    rd firmware.\";\r\\r
+    \n  :log info \"\$SMP Upgrading routerboard firmware from v.\$deviceRbCurr\\r
+    entFw to v.\$deviceRbUpgradeFw\";\r\\r
+    \n  /system routerboard upgrade;\r\\r
+    \n  :delay 2;\r\\r
+    \n  :log info \"\$SMP routerboard upgrade process was completed, going to \\r
+    reboot in a moment!\";\r\\r
+    \n  ## Set task to send final report on the next boot\r\\r
+    \n  /system scheduler add name=BKPUPD-NEXT-BOOT-TASK on-event=\":delay 2; \\r
+    :global buGlobalVarScriptStep 3; \\\r\\r
+    \n   :global buGlobalVarTargetOsVersion \\\"\$buGlobalVarTargetOsVersion\\\\r
+    \"; :delay 10s; /system/script { run \$ScriptName; }; \\ \r\\r
+    \n   :delay 5s; /system/scheduler remove BKPUPD-NEXT-BOOT-TASK;\" start-ti\\r
+    me=startup interval=0;\r\\r
+    \n   :delay 2;\r\\r
+    \n  /system reboot;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n## STEP 3: Final report (after second reboot, with delay).\r\\r
+    \n## Runs only if auto-update is enabled and a new RouterOS version was fo\\r
+    und.\r\\r
+    \n:if (\$scriptStep = 3) do={\r\\r
+    \n  :log info (\"\$SMP The script is in the third step, sending final repo\\r
+    rt.\");\r\\r
+    \n  :local targetOsVersion \$buGlobalVarTargetOsVersion;\r\\r
+    \n  :do {\r\\r
+    \n    /system/script/environment remove [find name=\"buGlobalVarTargetOsVe\\r
+    rsion\"];\r\\r
+    \n  } on-error={\r\\r
+    \n    :set \$mailSubjectPrefix (\$mailSubjectPrefix . \" ERROR Remove glob\\r
+    al variable \\\$buGlobalVarTargetOsVersion failed!\");\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :if ([ :len \$OldMode ] != 0) do={\r\\r
+    \n    :do {\r\\r
+    \n      /system/script/environment remove [find name=\"OldMode\"];\r\\r
+    \n      } on-error={\r\\r
+    \n        :set \$mailSubjectPrefix (\$mailSubjectPrefix . \" ERROR! Remove\\r
+    \_global variable \\\$OldMode failed!\");\r\\r
+    \n       }\r\\r
+    \n  }\r\\r
+    \n  :if ([:len \$targetOsVersion] = 0) do={\r\\r
+    \n    :log warning \"\$SMP Something is wrong, the script was unable to ge\\r
+    t the target updated OS version from the global variable.\";\r\\r
+    \n  }\r\\r
+    \n  :local mailStep3Subject \$mailSubjectPrefix;\r\\r
+    \n  :local mailStep3Body  \"\";\r\\r
+    \n  :if (\$targetOsVersion = \$runningOsVersion) do={\r\\r
+    \n    :log info \"\$SMP Successfully verified new RouterOS version: target\\r
+    : `\$targetOsVersion`, current: `\$runningOsVersion`\";\r\\r
+    \n    :set mailStep3Subject (\$mailStep3Subject . \" - Update completed - \\r
+    Backup created\");\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"RouterOS and routerboard upg\\r
+    rade process was completed\");\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"\\nNew RouterOS version: v.\\r
+    \$targetOsVersion, routerboard firmware: v.\$deviceRbCurrentFw\");\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"\\n\$changelogUrl\\nBackups \\r
+    of the upgraded system are in the attachment of this email.\\n\\n\$mailBod\\r
+    yDeviceInfo\\n\\n\$mailBodyCopyright\");\r\\r
+    \n    :set mailAttachments [\$FuncCreateBackups \$backupNameAfterUpdate \$\\r
+    BackupPassword \$BackupSens];\r\\r
+    \n  } else={\r\\r
+    \n    :log error \"\$SMP Failed to verify new RouterOS version: target: `\\r
+    \$targetOsVersion`, current: `\$runningOsVersion`\";\r\\r
+    \n    :set mailStep3Subject (\$mailStep3Subject . \" - Update failed\");\r\\r
+    \n    :set mailStep3Body (\$mailStep3Body . \"The script was unable to ver\\r
+    ify that the new RouterOS version was installed, target version: `\$target\\r
+    OsVersion`, current version: `\$runningOsVersion`\\nCheck device logs for \\r
+    more details.\\n\\n\$mailBodyDeviceInfo\\n\\n\$mailBodyCopyright\");\r\\r
+    \n  }\r\\r
+    \n  \$FuncSendEmailSafe \$EmailGeneralTo \$mailStep3Subject \$mailStep3Bod\\r
+    y \$mailAttachments;\r\\r
+    \n  :if ([:len \$mailAttachments] > 0) do={\r\\r
+    \n    :log info \"\$SMP Cleaning up backup files from the file system...\"\\r
+    ;\r\\r
+    \n    /file remove \$mailAttachments;\r\\r
+    \n    :delay 2;\r\\r
+    \n  }\r\\r
+    \n  :log info \"\$SMP Final report email sent successfully, and the script\\r
+    \_has finished.\";\r\\r
+    \n}\r\\r
+    \n:log info \"\$SMP the script has finished, script step: `\$scriptStep` \\r
+    \\n\\n\";\r\\r
+    \n} do={\r\\r
+    \n  :global ExitError; \$ExitError \$ExitOK [ :jobname ] \$Err;\r\\r
+    \n}\r\\r
+    \n"\r
+add dont-require-permissions=no name=fetchCustom owner=vados policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="#\\r
+    root.mnuc.backuper\r\\r
+    \n:global GlobalScriptsUrl \"https://ros.vados.ru/\";\r\\r
+    \n/tool/fetch mode=https url=(\$GlobalScriptsUrl . \".bak/mikro_bak_rsa@10\\r
+    .30.30.86.pub\") dst-path=\"/mikro_bak_rsa@10.30.30.86.pub\";\r\\r
+    \n#/usb1/mikro_bak_rsa.pub"\r
+add dont-require-permissions=no name=testSetup owner=vados policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="#\\r
+    \r\\r
+    \n:local newFolder \"tmpfs/scripts\";\r\\r
+    \n\r\\r
+    \n:local errorMsg;\r\\r
+    \n\r\\r
+    \n#    :while (([:pick \$newFolder ([:len \$newFolder] - 1)]) = \"/\") do=\\r
+    {\r\\r
+    \n#        :set newFolder [:pick \$newFolder 0 ([:len \$newFolder] - 1)]\r\\r
+    \n#    }\r\\r
+    \n\r\\r
+    \n#    :while ([:pick \$newFolder 0] = \"/\") do={\r\\r
+    \n#        :set newFolder [:pick \$newFolder 1 [:len \$newFolder]]\r\\r
+    \n#    }\r\\r
+    \n\r\\r
+    \n\r\\r
+    \n:if ([/file find name=\$newFolder] != \"\") do={\r\\r
+    \n        :set errorMsg (\$newFolder . \" already exists.\");\r\\r
+    \n        :log warning (\$0 . \" mkdir: \" . \$errorMsg);\r\\r
+    \n        :return \$newFolder;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n\r\\r
+    \n#:put [ :len [ /file/find where name=\$Path ] ];\r\\r
+    \n\r\\r
+    \n:put [:len \$Path];\r\\r
+    \n:put [ :pick \$Path ];\r\\r
+    \n:put [ :pick \$Path ([ :len \$Path ] - 1) ];\r\\r
+    \n\r\\r
+    \n:if (\$Path != false) do={\r\\r
+    \n:put \"TRUE\";\r\\r
+    \n}"\r
+add comment="Script for setup routeros scrypt system" \\r
+    dont-require-permissions=no name=AM-setup owner=AM-setup policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="#\\r
+    !rsc by Vados\r\\r
+    \n# RouterOS script: AM-setup\r\\r
+    \n# Script comment: Script for setup routeros scrypt system\r\\r
+    \n# Copyright (c) 2005-2026 Vados <vados@vados.ru>\r\\r
+    \n#\r\\r
+    \n#\r\\r
+    \n# requires RouterOS, version=7.19\r\\r
+    \n# requires device-mode, fetch\r\\r
+    \n#\r\\r
+    \n# :local ScriptName [ :jobname ];\r\\r
+    \n# Additional commands:\r\\r
+    \n#\r\\r
+    \n# For scripts:\r\\r
+    \n#:global NewScript \"script_name\"; \r\\r
+    \n#:global GlobalScriptsUrl \"https://ros.vados.ru/\";\r\\r
+    \n#/system/script/add name=\$NewScript owner=\$NewScript source=([/tool/fe\\r
+    tch check-certificate=yes-without-crl (\$GlobalScriptsUrl . \$ScriptAdd . \\r
+    \".rsc\") output=user as-value ]->\"data\");\r\\r
+    \n#:global NewScript (a);\r\\r
+    \n#:global ScriptInstallUpdate; \$ScriptInstallUpdate;\r\\r
+    \n#\r\\r
+    \n# For run from terminal:\r\\r
+    \n#/system/script/add name=AM-setup owner=AM-Setup source=([/tool/fetch ch\\r
+    eck-certificate=yes-without-crl \"https://ros.vados.ru/AM-setup.rsc\" outp\\r
+    ut=user as-value ]->\"data\");\r\\r
+    \n#\r\\r
+    \n#:foreach Script in=[ /system/script/find where source~\"^#!rsc by Vados\\r
+    \" ] do={\r\\r
+    \n#  if (\$ScriptUpdatesCRLF = true) do={\r\\r
+    \n#   /system/script/set source=[ :tocrlf [ get \$Script source ] ] \$Scri\\r
+    pt;\r\\r
+    \n#  } else={\r\\r
+    \n#   /system/script/set source=[ :tolf [ get \$Script source ] ] \$Script\\r
+    ;\r\\r
+    \n#  }\r\\r
+    \n#}\r\\r
+    \n# /import verbose=no \$ScriptName\r\\r
+    \n:global SetupScript [ :jobname ];\r\\r
+    \n:global RemoveMe;\r\\r
+    \n:global InitSetup true;\r\\r
+    \n:global tmpfs true;\r\\r
+    \n\r\\r
+    \n{\r\\r
+    \n  :local RmMe [:tobool \$1];\r\\r
+    \n\r\\r
+    \n  :global GlobalScriptsUrl;\r\\r
+    \n  :global SetupScript;\r\\r
+    \n  :global RemoveMe;\r\\r
+    \n  :global InitSetup;\r\\r
+    \n  :global tmpfs;\r\\r
+    \n    \r\\r
+    \n  :local CertCommonName \"Root YE\";\r\\r
+    \n  :local CertFileName \"Root-YE.pem\";\r\\r
+    \n  :local CertFingerprint \"e14ffcad5b0025731006caa43a121a22d8e9700f4fb9c\\r
+    f852f02a708aa5d5666\";\r\\r
+    \n\r\\r
+    \n  :if (\$SetupScript = false) do={\r\\r
+    \n    :global SetupScript \"AM-setup\";\r\\r
+    \n  }\r\\r
+    \n  :if (\$RemoveMe != false) do={\r\\r
+    \n    :set RemoveMe true;\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :log warning (\"\\n\\\$GlobalScriptsUrl = \" . \$GlobalScriptsUrl);\r\\r
+    \n  \r\\r
+    \n  :local CertSettings [ /certificate/settings/get ];\r\\r
+    \n  :if (!(((\$CertSettings->\"builtin-trust-anchors\") = \"trusted\" || \\r
+    \\\r\\r
+    \n          (\$CertSettings->\"builtin-trust-store\") ~ \"fetch\" || \\\r\\r
+    \n          (\$CertSettings->\"builtin-trust-store\") = \"all\") && \\\r\\r
+    \n         [ :len [ /certificate/builtin/find where common-name=\$CertComm\\r
+    onName ] ] > 0)) do={\r\\r
+    \n    :put \"Importing certificate...\";\r\\r
+    \n    \r\\r
+    \n    /tool/fetch (\$GlobalScriptsUrl . \"certs/\" . \$CertFileName) dst-p\\r
+    ath=\$CertFileName as-value;\r\\r
+    \n    :delay 1s;\r\\r
+    \n    /certificate/import file-name=\$CertFileName passphrase=\"\";\r\\r
+    \n    :if ([ :len [ /certificate/find where fingerprint=\$CertFingerprint \\r
+    ] ] != 1) do={\r\\r
+    \n      :error \"Something is wrong with your certificates!\";\r\\r
+    \n    };\r\\r
+    \n    :delay 1s;\r\\r
+    \n  };\r\\r
+    \n  :put \"Thr tmpfs variable is true. Checking for tmpfs/scripts director\\r
+    y...\";\r\\r
+    \n  :if (\$tmpfs = true && [/file find name=\"tmpfs/scripts\"] != \"\") do\\r
+    ={\r\\r
+    \n    :log debug (\$0 . \"Directory tmpfs/scripts exsist.\");\r\\r
+    \n    :return \$true;\r\\r
+    \n  } else={\r\\r
+    \n    :log error (\$0 . \"Directory tmpfs/scripts does not exsist. Remove \\r
+    global variable tmpfs!\");\r\\r
+    \n    :global tmpfs (a);\r\\r
+    \n    return false;\r\\r
+    \n}\r\\r
+    \n  :put \"Renaming AM-GlobalConfig, if exists...\";\r\\r
+    \n  :local ConfOldName (\"AM-GlobalConfig-\" . [ /system/clock/get date ] \\r
+    . [ /system/clock/get time ] . \".rsc\");\r\\r
+    \n  /system/script/set name=\$ConfOldName [ find where name=\"AM-GlobalCon\\r
+    fig\" ];\r\\r
+    \n  :foreach Script in={ \"AM-GlobalConfig\"; \"AM-GlobalFunc\" } do={\r\\r
+    \n    :put \"Installing \$Script...\";\r\\r
+    \n    /system/script/remove [ find where name=\$Script ];\r\\r
+    \n    /system/script/add name=\$Script owner=\$Script source=([ /tool/fetc\\r
+    h check-certificate=yes-without-crl url=(\$GlobalScriptsUrl . \$Script . \\r
+    \".rsc\")  output=user as-value ]->\"data\");\r\\r
+    \n    \r\\r
+    \n    /system/script run \$Script;\r\\r
+    \n    :delay 2s;\r\\r
+    \n  };\r\\r
+    \n\r\\r
+    \n  :if ([ :len [ /certificate/find where fingerprint=\$CertFingerprint ] \\r
+    ] > 0) do={\r\\r
+    \n    :put \"Renaming certificate by its common-name...\";\r\\r
+    \n    :global CertificateNameByCN;\r\\r
+    \n    \$CertificateNameByCN \$CertFingerprint;\r\\r
+    \n  };\r\\r
+    \n\r\\r
+    \n  :if (\$RemoveMe = true) do={\r\\r
+    \n    :put \"Add Scheduler for remove this script...\";\r\\r
+    \n    :local OnEvent (\":delay 30s;\\n\" . \"/system/script/remove [ find \\r
+    where name=\\\"\$SetupScript\\\" ];\\n\" . \\\r\\r
+    \n    \":delay 2s;\\n\" . \"/system/scheduler/remove [ find where name=\\\\r
+    \"_RemoveSetup\\\" ];\\n\" . \\\r\\r
+    \n    \":delay 2s;\\n\" . \":global RemoveMe (a);\\n\");\r\\r
+    \n    :local Comment \"_RemoveSetup tmp scheduler for remove setup script.\\r
+    \";\r\\r
+    \n    /system/scheduler/add name=\"_RemoveSetup\" comment=\$Comment start-\\r
+    time=startup interval=30s on-event=\$OnEvent;\r\\r
+    \n      :log warning (\$0 . \"\\nI've done everything, and now I'm tired..\\r
+    . I'm leaving.\\nThere will be an error below, this is normal.\");\r\\r
+    \n    }\r\\r
+    \n    :delay 1;\r\\r
+    \n    :put \"Loading configuration and functions...\";\r\\r
+    \n    :do {      \r\\r
+    \n      :global ScriptInstallUpdate; \$ScriptInstallUpdate;\r\\r
+    \n      :put \"Normal removing temporary global environment variables.\";\\r
+    \r\\r
+    \n      :global SetupScript (a);\r\\r
+    \n      :global InitSetup (a);\r\\r
+    \n      :global RemoveMe (a);\r\\r
+    \n    } on-error={\r\\r
+    \n      :local ErrorMsg \"Loading configuration and functions error!\";\r\\r
+    \n      :log error (\$0 . \$ErrorMsg . :error);\r\\r
+    \n      :error \$ErrorMsg;\r\\r
+    \n    }\r\\r
+    \n}\r\\r
+    \n"\r
+add comment="Global Config Script" dont-require-permissions=no name=\\r
+    AM-GlobalConfig owner=AM-GlobalConfig policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="#\\r
+    !rsc by Vados\r\\r
+    \n# RouterOS script: AM-GlobalConfig\r\\r
+    \n# Script comment: Global Config Script\r\\r
+    \n# Copyright (c) 2007-2026 Vados <vados@vados.ru>\r\\r
+    \n#\r\\r
+    \n#\r\\r
+    \n# Warning: Dont touch this line!\r\\r
+    \n:global GlobalConfReady false;\r\\r
+    \n#   \\/    start edit\r\\r
+    \n#\r\\r
+    \n# Global Url For Amster scripts to fetch\r\\r
+    \n# most be defined in Amster-Init-Script\r\\r
+    \n:global GlobalScriptsUrl \"https://ros.vados.ru/\";\r\\r
+    \n:global ScriptsUrlSuffix \"\";\r\\r
+    \n:global CheckSumsVerify true;\r\\r
+    \n\r\\r
+    \n:global ScriptUpdatesCRLF true;\r\\r
+    \n:global CommentsInScripts true;\r\\r
+    \n\r\\r
+    \n# Debug output:\r\\r
+    \n:global PrintDebug true; #false;\r\\r
+    \n\r\\r
+    \n# Debug output for specific script:\r\\r
+    \n:set (\$PrintDebugOverride->\"AM-GlobalFunc\") true;\r\\r
+    \n\r\\r
+    \n# Debug logs\r\\r
+    \n# Other actions (disk, email, remote or support) can be used as well.\r\\r
+    \n# I do not recommend using echo - use debug output instead (https://rsc.\\r
+    eworm.de/main/DEBUG.html#debug-output).\r\\r
+    \n#/system/logging/add topics=script,debug action=memory;\r\\r
+    \n\r\\r
+    \n:global MikrotikUpgradeUrl \"https://upgrade.mikrotik.com/routeros\";\r\\r
+    \n:global Domain \"WORKGROUP\";\r\\r
+    \n\r\\r
+    \n:global EmailGeneralTo \"vados@vados.ru\"; #:global EmailGeneralCc \"\";\\r
+    \r\\r
+    \n\r\\r
+    \n# \$ScriptInstallUpdate mod/notification-telegram\r\\r
+    \n:global TelegramTokenId \"8390868324:AAG3_d1hfVR2M6pGAgDK6ZvhOe4J97nyopw\\r
+    \";\r\\r
+    \n:global TelegramChatId \"-1003631309063\"; #\"454403445\";\r\\r
+    \n# Use this to send notifications to a specific topic in group.\r\\r
+    \n#:global TelegramThreadId \"30\";\r\\r
+    \n# Using telegram-chat you have to define trusted chat ids (not group ids\\r
+    !)\r\\r
+    \n# or user names. Groups allow to chat with devices simultaneously.\r\\r
+    \n:global TelegramChatIdsTrusted {\r\\r
+    \n  \"454403445\"\r\\r
+    \n  \"-1003631309063\"\r\\r
+    \n  \"-5124482807\"\r\\r
+    \n  \"1087968824\";\r\\r
+    \n};\r\\r
+    \n#  \"-5294757340\";\r\\r
+    \n\r\\r
+    \n:global TelegramChatGroups \"(all)\";\r\\r
+    \n#:global TelegramChatGroups \"(all|home|office)\";\r\\r
+    \n\r\\r
+    \n:global NotificationFunctions {\r\\r
+    \n  \"email\"\r\\r
+    \n  \"telegram\";\r\\r
+    \n};\r\\r
+    \n# Toggle this to disable symbols in notifications.\r\\r
+    \n:global NotificationsWithSymbols true;\r\\r
+    \n:global TerminalColorOutput true;\r\\r
+    \n\r\\r
+    \n:global DetectIpAddrDefault \"https://ipv4.mikrotik.ovh/\";\r\\r
+    \n:global DetectIpAddrFallback \"https://api.ipify.org/\";\r\\r
+    \n\r\\r
+    \n## Update channel. Possible values: stable, long-term, testing, developm\\r
+    ent\r\\r
+    \n:global updateChannel \"stable\";\r\\r
+    \n\r\\r
+    \n# Script BackupAndUpdate mode, possible values: backup,\r\\r
+    \n# updateOnce - Update once as \"osnotify\" and back \"osnotify\" mode (i\\r
+    n terminal run :set OSUpdateMode updateOnce; \$OSUpdateMode;).  \r\\r
+    \n# osupdate - Update if available and creates backups before/after update\\r
+    \_(ignores `forceBackup`)\r\\r
+    \n#               Set `forceBackup` to true to always create backups, even\\r
+    \_without updates\r\\r
+    \n# osnotify - Set `forceBackup` to always create backups on every run\r\\r
+    \n:global DevInfoIncludeIP true;\r\\r
+    \n:global BackupAndUpdateMode \"osnotify\"\r\\r
+    \n\r\\r
+    \n:global forceBackup true;\r\\r
+    \n:global BackupPassword \"Peskar55\";\r\\r
+    \n\r\\r
+    \n# SFTP Backup Variables\r\\r
+    \n:global BackupRandomDelay 0;\r\\r
+    \n:global BackupUploadUrl \"sftp://amster.vados.ru/upload/\";\r\\r
+    \n:global BackupUploadUser \$Identity;\r\\r
+    \n:global BackupUploadPass \"root.mnuc.backuper\";\r\\r
+    \n\r\\r
+    \n:global BackupSendBinary true;\r\\r
+    \n:global BackupSendExport true;\r\\r
+    \n:global BackupSendGlobalConfig true;\r\\r
+    \n:global BackupSendScripts true;\r\\r
+    \n\r\\r
+    \n# Remove local file after uploading if no errors\r\\r
+    \n:global BackupRmLocal true;\r\\r
+    \n\r\\r
+    \n# Local Backups Root Directory \r\\r
+    \n:global BackupLocalRoot \"tmpfs\";\r\\r
+    \n\r\\r
+    \n# Encrypt Backup\r\\r
+    \n:global BackupEncrypt true;\r\\r
+    \n\r\\r
+    \n# Sensitive information in Backups\r\\r
+    \n:global BackupSens true;\r\\r
+    \n\r\\r
+    \n# User Export\r\\r
+    \n:global BackupUser true;\r\\r
+    \n\r\\r
+    \n# License Export (not for CHR, will silently skip)\r\\r
+    \n:global BackupLicense false;\r\\r
+    \n\r\\r
+    \n# SSH Keys\r\\r
+    \n:global BackupSshKeys true;\r\\r
+    \n\r\\r
+    \n# Certificate Export\r\\r
+    \n:global BackupCerts true;\r\\r
+    \n\r\\r
+    \n# Certificate Password\r\\r
+    \n:global BackupCertsPasswd \"\";\r\\r
+    \n\r\\r
+    \n# User-Manager Export\r\\r
+    \n:global BackupUserMan false;\r\\r
+    \n\r\\r
+    \n# The Dude Export\r\\r
+    \n:global BackupDude false;\r\\r
+    \n\r\\r
+    \n# User Files to export, comma-separated string or array of strings\r\\r
+    \n# User Files are not removed on backup\r\\r
+    \n# Any directory paths will be removed (/ -> _) on remote file\r\\r
+    \n# Nonpresent files are silently skipped\r\\r
+    \n:global BackupUserList \"autosupout.rif,autosupout.old.rif\";\r\\r
+    \n\r\\r
+    \n# load functions and any custom scripts\r\\r
+    \n#                    [ /system/script/find where name=\"global-config-ov\\r
+    erlay\" ], \\\r\\r
+    \n#                    [ /system/script/find where name~\"^global-config-o\\r
+    verlay\\\\.d/.\" ]\r\\r
+    \n#\r\\r
+    \n#:foreach Script in=([ /system/script/find where name=\"Amster-TGglobalV\\r
+    ars\" ], [ /system/script/find where name=\"Amster-TGglobalFunc\" ]) do={\\r
+    \r\\r
+    \n#  :onerror Err {\r\\r
+    \n#     /system/script/run \$Script;\r\\r
+    \n#     } do={\r\\r
+    \n#       :log error (\"Loading configuration from configs and functions\"\\r
+    \_. [ /system/script/get \$Script name ] . \" failed: \" . \$Err);\r\\r
+    \n#  }\r\\r
+    \n#}\r\\r
+    \n#:log info \"\\ndevMode = \$devMode\";\r\\r
+    \n#:log info \"\\ndevRunning = \$devRunning\";\r\\r
+    \n:foreach Script in=[ /system/script/find where source~\"^#!rsc by Vados \\r
+    GlobalRUN\\r\?\\n\" ] do={\r\\r
+    \n  :onerror Err {\r\\r
+    \n    /system/script/run \$Script;\r\\r
+    \n       } do={\r\\r
+    \n       :log error (\"Run script \" . [ /system/script/get \$Script name \\r
+    ] . \" width marker \\\" GlobalRUN\\\" failed: \" . \$Err);\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# signal we are ready\r\\r
+    \n:set GlobalConfReady true;\r\\r
+    \n:while (\$GlobalConfReady != true) do={:delay 500ms};\r\\r
+    \n"\r
+add comment="Global functions" dont-require-permissions=no name=AM-GlobalFunc \\r
+    owner=AM-GlobalFunc policy=\\r
+    ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source="#\\r
+    !rsc by Vados\r\\r
+    \n# RouterOS script: AM-GglobalFunc\r\\r
+    \n# Script comment: Global functions\r\\r
+    \n#\r\\r
+    \n#\r\\r
+    \n# requires RouterOS, version=7.21\r\\r
+    \n# requires device-mode, fetch, scheduler\r\\r
+    \n:local ExitOK false;\r\\r
+    \n:local ScriptName [ :jobname ];\r\\r
+    \n#:global checkRunJob \$SriptName;\r\\r
+    \n#:global fixCRLF;\r\\r
+    \n#:if (\$fixCRLF !=  false) do={\r\\r
+    \n#:foreach fixScript in=([ /system/script/find where name~\"*\" ]) do={/s\\r
+    ystem/script/set source=[ :tocrlf [ get \$fixScript source ] ] \$fixScript\\r
+    }\r\\r
+    \n#:if (\$fixCRLF !=  \"LF\") do={ /system/script/set source=[ :tocrlf [ g\\r
+    et \$fixScript source ] ] \$fixScript};};\r\\r
+    \n#}\r\\r
+    \n:global GlobalFuncReady false;\r\\r
+    \n\r\\r
+    \n# Git commit id & info, expected configuration version\r\\r
+    \n:global CommitId \"main/167/eeff9aa5\";\r\\r
+    \n:global CommitTAG \"unknown\";\r\\r
+    \n:global CommitInfo \"Autocommit in repo: ros.vados.ru, generated by owne\\r
+    r: root, in 04:24:04 12.03.2026.\";\r\\r
+    \n\r\\r
+    \n# The variables are received right here.\r\\r
+    \n:global GlobalConfVersion 138;\r\\r
+    \n\r\\r
+    \n:global SumsDirAndFileName \"tmp/checksums.json\";\r\\r
+    \n\r\\r
+    \n:global Identity [/system/identity/get name];\r\\r
+    \n:global IdentityShort [:pick \$Identity 0 18];\r\\r
+    \n\r\\r
+    \n:global devBoardName [/system/resource/get board-name];\r\\r
+    \n:global devMode [/system/device-mode/get mode];\r\\r
+    \n:global devCurArch [/system/resource/get architecture-name];\r\\r
+    \n:global devCurVersion [/system/resource/get version];\r\\r
+    \n\r\\r
+    \n# Variables defined in AM-GlobalConfig.rsc\r\\r
+    \n:global TerminalColorOutput;\r\\r
+    \n:global CommentsInScripts;\r\\r
+    \n:global DetectIpAddrDefault;\r\\r
+    \n:global DetectIpAddrFallback;\r\\r
+    \n:global updateChannel;\r\\r
+    \n:global Domain;\r\\r
+    \n:global EmailGeneralTo;\r\\r
+    \n:global BackupAndUpdateMode;\r\\r
+    \n\r\\r
+    \n# Single functions, without nested functions.\r\\r
+    \n:global GlobalEnvRemove;\r\\r
+    \n:global MiniDateTimeStamp;\r\\r
+    \n\r\\r
+    \n# Include globals \$PrintDebug and \$PrintDebugOverride\r\\r
+    \n:global LogPrint;\r\\r
+    \n\r\\r
+    \n# DeviceInfo and Updates\r\\r
+    \n:global IsCheckUpdates;\r\\r
+    \n:global WaitCheckUpdates;\r\\r
+    \n:global GetPubIp;\r\\r
+    \n\r\\r
+    \n:global GetArrDeviceInfo;\r\\r
+    \n:global WaitArrDeviceInfo;\r\\r
+    \n\r\\r
+    \n:global devModel;\r\\r
+    \n:global devRunningMode;\r\\r
+    \n\r\\r
+    \n:global devRbRevision;\r\\r
+    \n:global devRbSerialNumber;\r\\r
+    \n:global devRbVerAvail;\r\\r
+    \n\r\\r
+    \n:global runningChannelVersion;\r\\r
+    \n:global runningChannel;\r\\r
+    \n:global runningVersion;\r\\r
+    \n\r\\r
+    \n:global devBuildTime;\r\\r
+    \n#:global ROsVerAvail;\r\\r
+    \n:global PkgUpdStatus;\r\\r
+    \n:global currentUpdateChannel;\r\\r
+    \n\r\\r
+    \n:global ScriptInstallUpdate;\r\\r
+    \n\r\\r
+    \n:global DeviceInfo;\r\\r
+    \n\r\\r
+    \n:global OldMode;\r\\r
+    \n\r\\r
+    \n:global ParseKeyValueStore;\r\\r
+    \n:global RandomDelay;\r\\r
+    \n:global GetRandomNumber;\r\\r
+    \n:global EscapeForRegEx;\r\\r
+    \n:global ExitError;\r\\r
+    \n:global CleanFilePath;\r\\r
+    \n:global CleanName;\r\\r
+    \n:global CharacterReplace;\r\\r
+    \n:global CharacterMultiply;\r\\r
+    \n:global EitherOr;\r\\r
+    \n:global FormatLine;\r\\r
+    \n:global GetRandom20CharAlNum;\r\\r
+    \n:global Grep;\r\\r
+    \n:global IfThenElse;\r\\r
+    \n:global MAX;\r\\r
+    \n:global MIN;\r\\r
+    \n:global HumanReadableNum;\r\\r
+    \n\r\\r
+    \n:global IsFullyConnected;\r\\r
+    \n:global IsDNSResolving;\r\\r
+    \n:global IsTimeSync;\r\\r
+    \n:global IsTimeSyncCached;\r\\r
+    \n:global IsTimeSyncResetNtp;\r\\r
+    \n\r\\r
+    \n:global WaitDNSResolving;\r\\r
+    \n:global WaitFullyConnected;\r\\r
+    \n:global WaitTimeSync;\r\\r
+    \n:global MkDir;\r\\r
+    \n:global RmDir;\r\\r
+    \n:global RmFile;\r\\r
+    \n:global FileGet;\r\\r
+    \n:global Unix2Dos;\r\\r
+    \n:global UrlEncode;\r\\r
+    \n:global WaitForFile;\r\\r
+    \n:global ScriptLock;\r\\r
+    \n:global SendTelegram;\r\\r
+    \n:global NotificationFunctions;\r\\r
+    \n:global SendNotification;\r\\r
+    \n:global SendNotification2;\r\\r
+    \n:global SymbolForNotification;\r\\r
+    \n:global SymbolByUnicodeName;\r\\r
+    \n:global ValidateSyntax;\r\\r
+    \n:global CheckSumsVerify;\r\\r
+    \n:global GlobalConfChanges;\r\\r
+    \n:global GlobalConfMigration;\r\\r
+    \n:global VersionToNum;\r\\r
+    \n:global RequiredRouterOS;\r\\r
+    \n:global FetchLargeFiles;\r\\r
+    \n:global FetchUserAgentStr;\r\\r
+    \n:global CertificateAvailable;\r\\r
+    \n:global CertificateDownload;\r\\r
+    \n:global CertificateNameByCN;\r\\r
+    \n:global CharacterMultiply;\r\\r
+    \n\r\\r
+    \n:global InspectVar;\r\\r
+    \n:global InspectVarRet;\r\\r
+    \n:global ParseCustom;\r\\r
+    \n\r\\r
+    \n:set IsCheckUpdates do={\r\\r
+    \n  :local isInfo [:tobool \$1];\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global updateChannel;\r\\r
+    \n  :global PkgUpdStatus;\r\\r
+    \n  \$LogPrint debug \$0 (\"\\\$isInfo = \" . \$isInfo); \r\\r
+    \n  :local CurrentChannel [ /system/package/update/get channel ];\r\\r
+    \n  :if (\$CurrentChannel != \$updateChannel) do={\r\\r
+    \n    :retry command={/system/package/update set channel=\$updateChannel} \\r
+    \_delay=300ms max=5 on-error={};\r\\r
+    \n    \$LogPrint debug \$0 (\"Set updates channel to: \$updateChannel\");\\r
+    \r\\r
+    \n  }\r\\r
+    \n   \r\\r
+    \n  :local Update [ /system/package/update/get ];\r\\r
+    \n  :local Channel (\$Update->\"channel\");\r\\r
+    \n  \$LogPrint debug \$0 (\"Update Channel: \" . \$Channel . \".\");\r\\r
+    \n   \r\\r
+    \n  :local StatusPkg \"undefined\";\r\\r
+    \n  \$LogPrint debug \$0 (\"Checking for updates...\");\r\\r
+    \n  :retry command={:set \$StatusPkg ([/system/package/update/check-for-up\\r
+    dates without-paging as-value]->\"status\")} \\\r\\r
+    \n   delay=300ms max=5 on-error={};\r\\r
+    \n  \$LogPrint debug \$0 (\"\\\$StatusPkg = \" . \$StatusPkg);\r\\r
+    \n  :if (\$StatusPkg = \"New version is available\") do={ :set PkgUpdStatu\\r
+    s true; } else={ :set PkgUpdStatus false; }\r\\r
+    \n  \$LogPrint debug \$0 (\"\\\$PkgUpdStatus = \" . \$PkgUpdStatus);\r\\r
+    \n  :if (\$isInfo != false || \$PkgUpdStatus = true) do={\r\\r
+    \n    \$LogPrint debug \$0 (\"\\\$PkgUpdStatus = \" . \$PkgUpdStatus);\r\\r
+    \n    :if ([:len \$arrDeviceInfo] = 0) do={\r\\r
+    \n    :global arrDeviceInfo ({});\r\\r
+    \n    :local arrDeviceInfo ({\"section\":{\"key\":\"\"; \"value\":\"\";};}\\r
+    );\r\\r
+    \n    }\r\\r
+    \n    # else={:local arrDeviceInfo ({})}\r\\r
+    \n    :retry command={:set (\$arrDeviceInfo->\"devUpdates\") [[ :parse \"/\\r
+    system/package/update/get\" ]]} delay=500ms max=5 on-error={:log error (\"\\r
+    Error\")};\r\\r
+    \n    #:set (\$arrDeviceInfo->\"devUpdates\") {\"devCurrentChannel\"; \$Cu\\r
+    rrentChannel;};\r\\r
+    \n    #:set (\$arrDeviceInfo->\"devUpdates\") {\"devCurrentVersion\"; (\$U\\r
+    pdate->\"installed-version\");};\r\\r
+    \n    #:set (\$arrDeviceInfo->\"devUpdates\") {\"devCurrentChannelVersion\\r
+    \"; [/system/resource/get version];};\r\\r
+    \n    #:set (\$arrDeviceInfo->\"devUpdates\") {\"devUpdateChannel\"; [\$up\\r
+    dateChannel];};\r\\r
+    \n    #:set (\$arrDeviceInfo->\"devUpdates\") {\"devUpdateVersion\"; (\$Up\\r
+    date->\"latest-version\");};\r\\r
+    \n  } else={\r\\r
+    \n  :return \$PkgUpdStatus;\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set WaitArrDeviceInfo do={\r\\r
+    \n   :global GetArrDeviceInfo;\r\\r
+    \n   :while ([ \$GetArrDeviceInfo ] = false) do={\r\\r
+    \n    :delay 1s;\r\\r
+    \n   }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set GetArrDeviceInfo do={\r\\r
+    \n   :global LogPrint;\r\\r
+    \n\r\\r
+    \n   :global devBoardName;\r\\r
+    \n   :global devModel;\r\\r
+    \n   \r\\r
+    \n   :global arrDeviceInfo [:toarray {\"section\"={\"key\"=\"\"; \"value\"\\r
+    =\"\";} }];\r\\r
+    \n   #:do {:set (\$arrDeviceInfo->\"Updates\") [[ :parse \"/system/package\\r
+    /update/get\" ]]} on-error={}\r\\r
+    \n   :global devRbRevision;\r\\r
+    \n   :global devRbSerialNumber;\r\\r
+    \n   :global devRbCurrentFw;\r\\r
+    \n   :global devRbUpgradeFw;\r\\r
+    \n \r\\r
+    \n   :global devRunning;\r\\r
+    \n   :global devCurArch;\r\\r
+    \n   :global ROsVerCurrent;\r\\r
+    \n   :global ROsChannelCurrent;\r\\r
+    \n   :global ROsVerAvail;\r\\r
+    \n\r\\r
+    \n   :global ParseCustom;\r\\r
+    \n   :global runningChannelVersion;\r\\r
+    \n   :global runningChannel;\r\\r
+    \n   :global runningVersion;\r\\r
+    \n   :global devBuildTime;\r\\r
+    \n   :global GetPubIp;\r\\r
+    \n   \r\\r
+    \n   :local License [/system/license/get];\r\\r
+    \n   :local Resource [/system/resource/get];\r\\r
+    \n   :set devBuildTime (\$Resource->\"build-time\");\r\\r
+    \n   :set runningChannelVersion (\$Resource->\"version\");\r\\r
+    \n   :set runningChannel [\$ParseCustom \$runningChannelVersion \"(\" \")\\r
+    \" 1];\r\\r
+    \n   :set runningVersion [\$ParseCustom \$runningChannelVersion \" \"];\r\\r
+    \n   \r\\r
+    \n   :do {\r\\r
+    \n   :if ([:pick \$devBoardName 0 3] != \"CHR\" or [:pick \$devBoardName 0\\r
+    \_3] != \"x86\") do={\r\\r
+    \n      :local RouterBoard;\r\\r
+    \n      :do {:set RouterBoard [[ :parse \"/system/routerboard/get\" ]]} on\\r
+    -error={}\r\\r
+    \n      :set devModel (\$RouterBoard->\"model\");\r\\r
+    \n      :set devRbRevision (\$RouterBoard->\"revision\");\r\\r
+    \n      :set devRbSerialNumber (\$RouterBoard->\"serial-number\");\r\\r
+    \n      #:set devRbCurrentFw (\$RouterBoard->\"current-firmware\");\r\\r
+    \n      #:set devRbUpgradeFw (\$RouterBoard->\"upgrade-firmware\");\r\\r
+    \n      :if (\$devCurArch = \"mipsbe\" || \$devCurArch = \"arm\") do={\r\\r
+    \n         :global devRunning [ /system/device-mode/get mode ];\r\\r
+    \n         } else={\r\\r
+    \n          :global devRunning [/system/device-mode/get running];}\r\\r
+    \n    } else={\r\\r
+    \n    :set devModel \$devBoardName;\r\\r
+    \n    \r\\r
+    \n    :set devRbRevision false;\r\\r
+    \n    :set devRbSerialNumber false;\r\\r
+    \n#    :set devRbCurrentFw false;\r\\r
+    \n#    :set devRbUpgradeFw false;\r\\r
+    \n    #:set devCurrentFw \$runningVersion;#:set devUpgradeFw \$ROsVerAvail\\r
+    ;\r\\r
+    \n    :set devRunning [/system/device-mode/get running];\r\\r
+    \n    }\r\\r
+    \n   } on-error={\r\\r
+    \n    \$LogPrint error \$0 (\"Error in Function getDevice!\");\r\\r
+    \n    :return false;\r\\r
+    \n   }\r\\r
+    \n:return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set DeviceInfo do={\r\\r
+    \n  :global WaitArrDeviceInfo;\r\\r
+    \n  # \$WaitDeviceInfo;\r\\r
+    \n  :global devBoardName;\r\\r
+    \n  :global devCurArch;\r\\r
+    \n  :global devModel;\r\\r
+    \n  :global devRunning;\r\\r
+    \n  :global devRbRevision;\r\\r
+    \n  :global devRbSerialNumber;\r\\r
+    \n  :global PiblicIpAddress;\r\\r
+    \n\r\\r
+    \n  :global GlobalConfVersion;\r\\r
+    \n  :global Identity;\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :global FormatLine;\r\\r
+    \n  :local Return;\r\\r
+    \n  :local License [/system/license/get];\r\\r
+    \n  :local Resource [/system/resource/get];\r\\r
+    \n  :local Snmp [ /snmp/get ];\r\\r
+    \n  :local Update [ /system/package/update/get ];\r\\r
+    \n  \r\\r
+    \n  :set Return ([ \$FormatLine \"Hostname:\" \$Identity ] . \"\\n\" . \\\\r
+    \r\\r
+    \n    [ \$IfThenElse ([ :len (\$Snmp->\"location\") ] > 0) \\\r\\r
+    \n      ([ \$FormatLine \"Location:\" (\$Snmp->\"location\") ] . \"\\n\") \\r
+    ] . \\\r\\r
+    \n    [ \$IfThenElse ([ :len (\$Snmp->\"contact\") ] > 0) \\\r\\r
+    \n      ([ \$FormatLine \"Contact:\" (\$Snmp->\"contact\") ] . \"\\n\") ] \\r
+    . \\\r\\r
+    \n      \"Hardware:\\n\" . \\\r\\r
+    \n    [ \$FormatLine \"    Board:\" . \$devBoardName ] . \"\\n\" . \\\r\\r
+    \n    [ \$FormatLine \"    Arch:\" . \$devCurArch ] . \"\\n\" . \\\r\\r
+    \n    [ \$FormatLine \"    Model:\" \$devModel ] . \\\r\\r
+    \n      [ \$IfThenElse ([ :len \$devRbRevision ] > 0) \\\r\\r
+    \n      (\" \" . \$devRbRevision) ] . \"\\n\" . \\\r\\r
+    \n      [ \$IfThenElse ([ :len \$devRbSerialNumber ] > 0) \\\r\\r
+    \n       ([ \$FormatLine \"    Serial:\" . \$devRbSerialNumber ] . \"\\n\"\\r
+    ) ] .  \\\r\\r
+    \n    [ \$IfThenElse ([ :len (\$License->\"nlevel\") ] > 0) \\\r\\r
+    \n      ([ \$FormatLine \"    License:\" (\"level \" . (\$License->\"nleve\\r
+    l\")) ] . \"\\n\") ] . \"RouterOS:\\n\" . \\\r\\r
+    \n    [ \$IfThenElse ([ :len (\$License->\"level\") ] > 0) \\\r\\r
+    \n      ([ \$FormatLine \"    License:\" (\"level \" . (\$License->\"level\\r
+    \")) ] . \"\\n\") ] . \\\r\\r
+    \n    [ \$FormatLine \"Running Channel\" \$runningChannel ] . \"\\n\" . \\\\r
+    \r\\r
+    \n    [ \$FormatLine \"    Installed:\" (\$Update->\"installed-version\") \\r
+    ] . \"\\n\" . \\\r\\r
+    \n    [ \$IfThenElse ([ :typeof (\$Update->\"latest-version\") ] != \"noth\\r
+    ing\" && \\\r\\r
+    \n        \$Update->\"installed-version\" != \$Update->\"latest-version\")\\r
+    \_\\\r\\r
+    \n      ([ \$FormatLine \"    Available\" (\$Update->\"latest-version\") ]\\r
+    \_. \"\\n\") ] . \\\r\\r
+    \n    [ \$IfThenElse (\$RouterBoard->\"routerboard\" = true && \\\r\\r
+    \n        \$RouterBoard->\"current-firmware\" != \$RouterBoard->\"upgrade-\\r
+    firmware\") \\\r\\r
+    \n      ([ \$FormatLine \"    Firmware\" (\$RouterBoard->\"current-firmwar\\r
+    e\") ] . \"\\n\") ] . \\ \r\\r
+    \n      \"RouterOS-Scripts:\\n\" . \\\r\\r
+    \n      [ \$FormatLine \"    Commit\" [ \$CommitBrief ] ] . \"\\n\" . \\\r\\r
+    \n      [ \$FormatLine \"    Version\" \$GlobalConfVersion ]);\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:if ([ :typeof \$NotificationFunctions ] != \"array\") do={:set Notifica\\r
+    tionFunctions ({})}\r\\r
+    \n:set GetRandom20CharAlNum do={\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :return [ :rndstr length=[ \$EitherOr [ :tonum \$1 ] 20 ] from=\"ABCDE\\r
+    FGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\" ];\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:global checkRunJob;\r\\r
+    \n:set checkRunJob do={\r\\r
+    \n  :local Script [ :tostr \$1 ];\r\\r
+    \n  :global ScriptLock; \r\\r
+    \n  :if ([ \$ScriptLock \$Script ] = false) do={:return false}\r\\r
+    \n  :foreach Job in=[ /system/script/job/find where script=\$Script ] do={\\r
+    :set Job [ /system/script/job/get \$Job ];\r\\r
+    \n    :while ([ :typeof (\$Job->\"parent\") ] = \"id\") do={:set Job [ /sy\\r
+    stem/script/job/get [ find where .id=(\$Job->\"parent\") ] ]}\r\\r
+    \n     :if ((\$Job->\"type\") = \"login\") do={:return true};}; :return fa\\r
+    lse; \r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set InspectVar do={\r\\r
+    \n  :global InspectVarRet;\r\\r
+    \n  :put [ :tocrlf [ \$InspectVarRet \$1 ] ];\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set InspectVarRet do={\r\\r
+    \n  :local Input \$1;\r\\r
+    \n  :local Level (0 + [ :tonum \$2 ]);\r\\r
+    \n  :global CharacterReplace;\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :global InspectVarRet;\r\\r
+    \n  :local IndentReturn do={\r\\r
+    \n    :local Prefix [ :tostr \$1 ];\r\\r
+    \n    :local Value  [ :tostr \$2 ];\r\\r
+    \n    :local Level  [ :tonum \$3 ];\r\\r
+    \n    :global CharacterMultiply;\r\\r
+    \n    :return ([ \$CharacterMultiply \" \" (\$Level * 2) ] . \"-\" . \$Pre\\r
+    fix . \"-> \" . \$Value);\r\\r
+    \n  }\r\\r
+    \n  :local TypeOf [ :typeof \$Input ];\r\\r
+    \n  :local Len    [ :len \$Input ];\r\\r
+    \n  :local Return [ \$IndentReturn \"type\" \$TypeOf \$Level ];\r\\r
+    \n  :if (\$TypeOf = \"array\") do={\r\\r
+    \n    :foreach Key,Value in=\$Input do={\r\\r
+    \n      :set \$Return (\$Return . \"\\n\" . \\\r\\r
+    \n        [ \$IndentReturn \"key\" \$Key (\$Level + 1) ] . \"\\n\" . \\\r\\r
+    \n        [ \$InspectVarRet \$Value (\$Level + 2) ]);\r\\r
+    \n    }\r\\r
+    \n  } else={\r\\r
+    \n    :if (\$TypeOf = \"str\") do={\r\\r
+    \n      :set \$Return (\$Return . \"\\n\" . \\\r\\r
+    \n         [ \$IndentReturn \"len\" \$Len \$Level ]);\r\\r
+    \n      :if ([ :typeof [ :find \$Input (\"\\r\") ] ] = \"num\") do={\r\\r
+    \n        :set Input [ \$CharacterReplace \$Input (\"\\r\") \"\" ];\r\\r
+    \n      }\r\\r
+    \n      :if ([ :typeof [ :find \$Input (\"\\n\") ] ] = \"num\") do={\r\\r
+    \n        :set Input [ \$CharacterReplace \$Input (\"\\n\") \" \" ];\r\\r
+    \n      }\r\\r
+    \n    }\r\\r
+    \n    :if (\$TypeOf != \"nothing\") do={\r\\r
+    \n      :set \$Return (\$Return . \"\\n\" . \\\r\\r
+    \n       [ \$IndentReturn \"value\" [ \$IfThenElse ([ :len \$Input ] > 80)\\r
+    \_\\\r\\r
+    \n        ([ :pick \$Input 0 77 ] . \"...\") \$Input ] \$Level ]);\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# !!! The function is not ready !!!\r\\r
+    \n:global FetchHttpInfo do={\r\\r
+    \n  :local Mac [ :tostr \$1 ];\r\\r
+    \n  :global CertificateAvailable;\r\\r
+    \n  :global IsMacLocallyAdministered;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :local Url \"https://api.macvendors.com/\";\r\\r
+    \n  :if ([ \$IsMacLocallyAdministered \$Mac ] = true) do={:return \"locall\\r
+    y administered\";}\r\\r
+    \n  :do {\r\\r
+    \n    :if ([ \$CertificateAvailable \"GTS Root R4\" \"fetch\" ] = false) d\\r
+    o={\r\\r
+    \n      \$LogPrint warning \$0 (\"Downloading required certificate failed.\\r
+    \");\r\\r
+    \n      :error false;\r\\r
+    \n    }\r\\r
+    \n    :local Vendor ([ /tool/fetch \r\\r
+    \n     (\$Url . [ :pick \$Mac 0 8 ]) output=user as-value ]->\"data\");\r\\r
+    \n    :return \$Vendor;\r\\r
+    \n  } on-error={\r\\r
+    \n    :onerror Err {\r\\r
+    \n      /tool/fetch check-certificate=yes-without-crl (\$Url) output=none \\r
+    as-value;\r\\r
+    \n      \$LogPrint debug \$0 (\"The mac vendor is not known in database.\"\\r
+    );\r\\r
+    \n    } do={ \$LogPrint warning \$0 (\"Failed getting mac vendor: \" . \$E\\r
+    rr); }\r\\r
+    \n    :return \"unknown vendor\";\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set GetPubIp do={\r\\r
+    \n    :global DetectIpAddrDefault;\r\\r
+    \n    :global DetectIpAddrFallback;\r\\r
+    \n    :global LogPrint;\r\\r
+    \n    \r\\r
+    \n    :local PubIpAddr false;\r\\r
+    \n    :local Url \$DetectIpAddrDefault;\r\\r
+    \n\r\\r
+    \n#   :retry command={abc} delay=1 max=2 on-error={:put \"got error\"} \r\\r
+    \n    :do {\r\\r
+    \n      \$LogPrint debug \$0 (\"Trying to detect public IP using default s\\r
+    ervice: \" . \$Url . \"...\");\r\\r
+    \n       :retry command={:set PubIpAddr ([ /tool/fetch http-method=\"get\"\\r
+    \_check-certificate=yes-without-crl \$Url output=user as-value ]->\"data\"\\r
+    )} \\\r\\r
+    \n        delay=50ms max=5 on-error={\$LogPrint error [ :jobname ] (\"Fail\\r
+    ed to detect public IP using default service: \" . \$Url . \".\")}\r\\r
+    \n       #:error \"Failed to detect public IP using default service: \$Url\\r
+    .\"};\r\\r
+    \n     } on-error={\r\\r
+    \n      \$LogPrint error \$0 (\"Failed to detect public IP using default s\\r
+    ervice: \" . \$Url . \".\");\r\\r
+    \n      :set Url \$DetectIpAddrFallBack;\r\\r
+    \n      \$LogPrint debug \$0 (\"Trying to detect public IP using fallback \\r
+    service: \" . \$Url . \"...\");\r\\r
+    \n       :retry command={:set PubIpAddr ([ /tool/fetch http-method=\"get\"\\r
+    \_check-certificate=yes-without-crl \$Url output=user as-value ]->\"data\"\\r
+    )} \\\r\\r
+    \n        delay=200ms max=5 on-error={\$LogPrint error [ :jobname ] (\"Fai\\r
+    led to detect public IP using fallback service: \" . \$Url . \".\")}\r\\r
+    \n    };\r\\r
+    \n    :if (\$PubIpAddr = false) do={\r\\r
+    \n      :set PubIpAddr \"not-detected\";\r\\r
+    \n    } else={\r\\r
+    \n      :set PubIpAddr [ :pick \$PubIpAddr 0 15];\r\\r
+    \n    }\r\\r
+    \n  :return \$PubIpAddr;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set FormatLine do={\r\\r
+    \n  :local Key    [ :tostr \$1 ];\r\\r
+    \n  :local Value  [ :tostr \$2 ];\r\\r
+    \n  :local Indent [ :tonum \$3 ];\r\\r
+    \n  :local Spaces;\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :global CharacterMultiply;\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :set Indent [ \$EitherOr \$Indent 16 ];\r\\r
+    \n  :local Spaces [ \$CharacterMultiply \" \" \$Indent ];\r\\r
+    \n  :if ([ :len \$Key ] > 0) do={ :set Return (\$Key . \":\")}\r\\r
+    \n  :if ([ :len \$Key ] > (\$Indent - 2)) do={:set Return (\$Return . \"\\\\r
+    n\" . [ :pick \$Spaces 0 \$Indent ] . \$Value);\r\\r
+    \n  } else={:set Return (\$Return . [ :pick \$Spaces 0 (\$Indent - [ :len \\r
+    \$Return ]) ] . \$Value)}\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set ParseCustom do={\r\\r
+    \n  :local Str [ :tostr \$1 ];\r\\r
+    \n  :local Start [:find [ \$Str ] [:tostr \$2]];\r\\r
+    \n  :local End [ :tostr \$3 ];\r\\r
+    \n  :local Num [ :tonum \$4 ];\r\\r
+    \n  :local Return;\r\\r
+    \n  :if ([:len \$Num] = 0) do={:set Num \"0\"}\r\\r
+    \n  :local rest [:pick \$Str (\$Start+\$Num) [:len \$Str]]; \r\\r
+    \n  :if ([:len \$End ] = 0) do={:set Return [:pick \$Str \$Num \$Start]} e\\r
+    lse={\r\\r
+    \n  :set End [:find \$rest \$End];\r\\r
+    \n  :set Return [:pick \$rest 0 \$End];\r\\r
+    \n  }\r\\r
+    \n:return \$Return;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set LogPrint do={\r\\r
+    \n  :local Severity [ :tostr \$1 ];\r\\r
+    \n  :local Name     [ :tostr \$2 ];\r\\r
+    \n  :local Message  [ :tostr \$3 ];\r\\r
+    \n  :global PrintDebug;\r\\r
+    \n  :global PrintDebugOverride;\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :local Debug [ \$EitherOr (\$PrintDebugOverride->\$Name) \$PrintDebug \\r
+    ];\r\\r
+    \n  :local PrintSeverity do={\r\\r
+    \n  :global TerminalColorOutput;\r\\r
+    \n   :if (\$TerminalColorOutput != true) do={:return \$1}\r\\r
+    \n   :local Color { debug=96; info=97; warning=93; error=91 };\r\\r
+    \n   :return (\"\\1B[\" . \$Color->\$1 . \"m\" . \$1 . \"\\1B[0m\");\r\\r
+    \n}\r\\r
+    \n  :local Log ([ \$EitherOr \$Name \"<unknown>\" ] . \": \" . \$Message);\\r
+    \r\\r
+    \n  :if (\$Severity ~ (\"^(custom|debug|error|info)\\\$\")) do={\r\\r
+    \n    :if (\$Severity = \"debug\") do={:log debug \$Log}\r\\r
+    \n    :if (\$Severity = \"error\") do={:log error \$Log}\r\\r
+    \n    :if (\$Severity = \"info\" ) do={:log info  \$Log}\r\\r
+    \n  } else={:log warning \$Log; :set Severity \"warning\"}\r\\r
+    \n  :if (\$Severity != \"debug\" || \$Debug = true) do={:put ([ \$PrintSev\\r
+    erity \$Severity ] . \": \" . \$Message)}\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CertificateAvailable do={\r\\r
+    \n  :local CommonName [ :tostr \$1 ];\r\\r
+    \n  :local UseFor     [ :tostr \$2 ];\r\\r
+    \n  :global CertificateDownload;\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global ParseKeyValueStore;\r\\r
+    \n  :set UseFor [ \$EitherOr \$UseFor \"undefined\" ];\r\\r
+    \n  :if ([ /system/resource/get free-hdd-space ] < 8388608 && \\\r\\r
+    \n       [ /certificate/settings/get crl-download ] = true && \\\r\\r
+    \n       [ /certificate/settings/get crl-store ] = \"system\") do={\r\\r
+    \n    \$LogPrint warning \$0 (\"This system has low free flash space but \\r
+    \" . \\\r\\r
+    \n      \"is configured to download certificate CRLs to system!\");\r\\r
+    \n  }\r\\r
+    \n  :if ([ :len \$CommonName ] = 0) do={\r\\r
+    \n    \$LogPrint warning \$0 (\"No CommonName given!\");\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :local CertSettings [ /certificate/settings/get ];\r\\r
+    \n  :if (((\$CertSettings->\"builtin-trust-anchors\") = \"trusted\" || \\\\r
+    \r\\r
+    \n        (\$CertSettings->\"builtin-trust-store\") ~ \$UseFor || \\\r\\r
+    \n        (\$CertSettings->\"builtin-trust-store\") = \"all\") && \\\r\\r
+    \n       [ :len [ /certificate/builtin/find where common-name=\$CommonName\\r
+    \_] ] > 0) do={\r\\r
+    \n    :return true;\r\\r
+    \n  }\r\\r
+    \n  :if ([ :len [ /certificate/find where common-name=\$CommonName ] ] = 0\\r
+    ) do={\r\\r
+    \n    \$LogPrint info \$0 (\"Certificate with CommonName '\" . \$CommonNam\\r
+    e . \"' not available.\");\r\\r
+    \n    :if ([ \$CertificateDownload \$CommonName ] = false) do={:return fal\\r
+    se}\r\\r
+    \n  }\r\\r
+    \n  :if ([ :len [ /certificate/find where common-name=\$CommonName ] ] > 1\\r
+    ) do={\r\\r
+    \n    \$LogPrint info \$0 (\"There are \" . \$CertCount . \" Certificates \\r
+    with CommonName '\" . \$CommonName . \"'. Should be ok.\");\r\\r
+    \n    :return true;\r\\r
+    \n  }\r\\r
+    \n  :local CertVal [ /certificate/get [ find where common-name=\$CommonNam\\r
+    e ] ];\r\\r
+    \n  :while ((\$CertVal->\"akid\") != \"\" && (\$CertVal->\"akid\") != (\$C\\r
+    ertVal->\"skid\")) do={\r\\r
+    \n    :if ([ :len [ /certificate/find where skid=(\$CertVal->\"akid\") ] ]\\r
+    \_= 0) do={\r\\r
+    \n      :local IssuerCN ([ \$ParseKeyValueStore (\$CertVal->\"issuer\") ]-\\r
+    >\"CN\");\r\\r
+    \n      \$LogPrint info \$0 (\"Certificate chain for '\" . \$CommonName . \\r
+    \"' is incomplete, missing '\" . \$IssuerCN . \"'.\");\r\\r
+    \n      :if ([ \$CertificateDownload \$IssuerCN ] = false) do={:return fal\\r
+    se}\r\\r
+    \n    }\r\\r
+    \n    :set CertVal [ /certificate/get [ find where skid=(\$CertVal->\"akid\\r
+    \") ] ];\r\\r
+    \n  }\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CertificateDownload do={\r\\r
+    \n  :local CommonName [ :tostr \$1 ];\r\\r
+    \n  :global GlobalScriptsUrl;\r\\r
+    \n  :global GlobalScriptsUrlSuffix;\r\\r
+    \n  :global CertificateNameByCN;\r\\r
+    \n  :global CleanName;\r\\r
+    \n  :global FetchUserAgentStr;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global RmFile;\r\\r
+    \n  :global WaitForFile;\r\\r
+    \n  \r\\r
+    \n  \$LogPrint info \$0 (\"Downloading and importing certificate with Comm\\r
+    onName '\" . \$CommonName . \"'.\");\r\\r
+    \n  \r\\r
+    \n  :local FileName ([ \$CleanName \$CommonName ] . \".pem\");\r\\r
+    \n  :do {\r\\r
+    \n    /tool/fetch check-certificate=yes-without-crl http-header-field=({ [\\r
+    \_\$FetchUserAgentStr \$0 ] }) \\\r\\r
+    \n      (\$GlobalScriptsUrl . \"certs/\" . \$FileName . \$GlobalScriptsUrl\\r
+    Suffix) dst-path=\$FileName as-value;\r\\r
+    \n    \$WaitForFile \$FileName;\r\\r
+    \n  } on-error={\r\\r
+    \n    \$LogPrint warning \$0 (\"Failed downloading certificate with Common\\r
+    Name '\" . \$CommonName . \\\r\\r
+    \n      \"' from repository! Trying fallback to mkcert.org...\");\r\\r
+    \n    :do {\r\\r
+    \n      :if ([ :len [ /certificate/find where common-name=\"ISRG Root X1\"\\r
+    \_] ] = 0) do={\r\\r
+    \n        \$LogPrint error \$0 (\"Required certificate is not available.\"\\r
+    );\r\\r
+    \n        :return false;\r\\r
+    \n      }\r\\r
+    \n      /tool/fetch check-certificate=yes-without-crl http-header-field=({\\r
+    \_[ \$FetchUserAgentStr \$0 ] }) \\\r\\r
+    \n        \"https://mkcert.org/generate/\" http-data=[ :serialize to=json \\r
+    ({ \$CommonName }) ] \\\r\\r
+    \n        dst-path=\$FileName as-value;\r\\r
+    \n      \$WaitForFile \$FileName;\r\\r
+    \n      :if ([ /file/get \$FileName size ] = 0) do={\r\\r
+    \n        \$RmFile \$FileName;\r\\r
+    \n        :error false;\r\\r
+    \n      }\r\\r
+    \n    } on-error={\r\\r
+    \n      \$LogPrint warning \$0 (\"Failed downloading certificate with Comm\\r
+    onName '\" . \$CommonName . \"'!\");\r\\r
+    \n      :return false;\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  /certificate/import file-name=\$FileName passphrase=\"\" as-value;\r\\r
+    \n  :delay 1s;\r\\r
+    \n  \$RmFile \$FileName;\r\\r
+    \n\r\\r
+    \n  :if ([ :len [ /certificate/find where common-name=\$CommonName ] ] = 0\\r
+    ) do={\r\\r
+    \n    /certificate/remove [ find where name~(\"^\" . \$FileName . \"_[0-9]\\r
+    +\\\$\") ];\r\\r
+    \n    \$LogPrint warning \$0 (\"Certificate with CommonName '\" . \$Common\\r
+    Name . \"' still unavailable!\");\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :foreach Cert in=[ /certificate/find where name~(\"^\" . \$FileName . \\r
+    \"_[0-9]+\\\$\") ] do={\r\\r
+    \n    \$CertificateNameByCN [ /certificate/get \$Cert common-name ];\r\\r
+    \n  }\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CertificateNameByCN do={\r\\r
+    \n  :local Match [ :tostr \$1 ];\r\\r
+    \n  :global CleanName;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :local Cert ([ /certificate/find where (common-name=\$Match or fingerp\\r
+    rint=\$Match or name=\$Match) ]->0);\r\\r
+    \n  :if ([ :len \$Cert ] = 0) do={\r\\r
+    \n    \$LogPrint warning \$0 (\"No matching certificate found.\");\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :local CommonName [ /certificate/get \$Cert common-name ];\r\\r
+    \n  /certificate/set \$Cert name=[ \$CleanName \$CommonName ];\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CharacterMultiply do={\r\\r
+    \n  :local Str [ :tostr \$1 ];\r\\r
+    \n  :local Num [ :tonum \$2 ];\r\\r
+    \n  :if (\$Num = 0) do={:return \"\"}\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :for I from=1 to=\$Num do={:set Return (\$Return . \$Str)}\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set ScriptInstallUpdate do={ :onerror Err {\r\\r
+    \n  :local Scripts    [ :toarray \$1 ];\r\\r
+    \n  :local NewComment [ :tostr   \$2 ];\r\\r
+    \n  :global InitSetup;\r\\r
+    \n\r\\r
+    \n  :global ScriptUpdatesCRLF;\r\\r
+    \n  :global GlobalConfVersion;\r\\r
+    \n  :global Identity;\r\\r
+    \n  :global CertificateAvailable;\r\\r
+    \n  :global CheckSumsVerify;\r\\r
+    \n  :global GlobalScriptsUrl;\r\\r
+    \n  :global SumsDirAndFileName;\r\\r
+    \n  :global GlobalScriptsUrlSuffix;\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :global FetchUserAgentStr;\r\\r
+    \n  :global Grep;\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global ParseKeyValueStore;\r\\r
+    \n  :global RequiredRouterOS;\r\\r
+    \n  :global SendNotification2;\r\\r
+    \n  :global SymbolForNotification;\r\\r
+    \n  :global ValidateSyntax;\r\\r
+    \n  :global CommentsInScripts;\r\\r
+    \n\r\\r
+    \n  :if ([ \$CertificateAvailable \"Root YE\" \"fetch\" ] = false) do={\r\\r
+    \n    \$LogPrint warning \$0 (\"Downloading certificate failed, trying wit\\r
+    hout.\");\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :foreach Script in=\$Scripts do={\r\\r
+    \n    :if ([ :len [ /system/script/find where name=\$Script ] ] = 0) do={\\r
+    \r\\r
+    \n      \$LogPrint info \$0 (\"Adding new script: \" . \$Script);\r\\r
+    \n      /system/script/add name=\$Script owner=\$Script source=\"#!rsc by \\r
+    Vados\\n\" comment=\$NewComment;\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n\r\\r
+    \n  :local GlobalConfVersionBefore \$GlobalConfVersion;\r\\r
+    \n  :local ReloadGlobal false;\r\\r
+    \n  :local DeviceMode [ /system/device-mode/get ];\r\\r
+    \n\r\\r
+    \n  :if (\$CheckSumsVerify = true) do={\r\\r
+    \n    :local CheckSums ({});\r\\r
+    \n     :do {\r\\r
+    \n     :local Url (\$GlobalScriptsUrl . \$SumsDirAndFileName . \$GlobalScr\\r
+    iptsUrlSuffix);\r\\r
+    \n      \$LogPrint debug \$0 (\"Fetching checksums from url: \" . \$Url);\\r
+    \r\\r
+    \n      :set CheckSums [ :deserialize from=json ([ /tool/fetch check-certi\\r
+    ficate=yes-without-crl \\\r\\r
+    \n        http-header-field=({ [ \$FetchUserAgentStr \$0 ] }) \$Url output\\r
+    =user as-value ]->\"data\") ];\r\\r
+    \n    } on-error={ \$LogPrint warning \$0 (\"Err = \" . \$Err); }\r\\r
+    \n    }\r\\r
+    \n\r\\r
+    \n  :foreach Script in=[ /system/script/find where source~\"^#!rsc by Vado\\r
+    s\" ] do={\r\\r
+    \n    :local ScriptVal [ /system/script/get \$Script ];\r\\r
+    \n    :local ScriptInfo [ \$ParseKeyValueStore (\$ScriptVal->\"comment\") \\r
+    ];\r\\r
+    \n    :local SourceNew;\r\\r
+    \n\r\\r
+    \n    :foreach Scheduler in=[ /system/scheduler/find where on-event~(\"\\\\r
+    \\b\" . \$ScriptVal->\"name\" . \"\\\\b\") ] do={\r\\r
+    \n      :local SchedulerVal [ /system/scheduler/get \$Scheduler ];\r\\r
+    \n      :if (\$ScriptVal->\"policy\" != \$SchedulerVal->\"policy\") do={\r\\r
+    \n        \$LogPrint warning \$0 (\"Policies differ for script '\" . \$Scr\\r
+    iptVal->\"name\" . \"' and its scheduler '\" . \$SchedulerVal->\"name\" . \\r
+    \"'!\");\r\\r
+    \n        }\r\\r
+    \n    }\r\\r
+    \n    :do {\r\\r
+    \n      :if (\$ScriptInfo->\"ignore\" = true) do={\r\\r
+    \n        \$LogPrint debug \$0 (\"Ignoring script '\" . \$ScriptVal->\"nam\\r
+    e\" . \"', as requested.\");\r\\r
+    \n        :error true;\r\\r
+    \n      }\r\\r
+    \n      :if (\$CheckSumsVerify = true) do={\r\\r
+    \n        :local CheckSum (\$CheckSums->(\$ScriptVal->\"name\"));\r\\r
+    \n        :if ([ :len (\$ScriptInfo->\"base-url\") ] = 0 && [ :len (\$Scri\\r
+    ptInfo->\"url-suffix\") ] = 0 && \\\r\\r
+    \n             [ :convert transform=md5 to=hex [ :tolf (\$ScriptVal->\"sou\\r
+    rce\") ] ] = \$CheckSum) do={\r\\r
+    \n          \$LogPrint debug \$0 (\"Checksum for script '\" . \$ScriptVal-\\r
+    >\"name\" . \"' matches, ignoring.\");\r\\r
+    \n          :error true;\r\\r
+    \n        }\r\\r
+    \n      }\r\\r
+    \n      :if ([ :len (\$ScriptInfo->\"certificate\") ] > 0) do={\r\\r
+    \n        :if ([ \$CertificateAvailable (\$ScriptInfo->\"certificate\") \"\\r
+    fetch\" ] = false) do={\r\\r
+    \n          \$LogPrint warning \$0 (\"Downloading certificate failed, tryi\\r
+    ng without.\");\r\\r
+    \n        }\r\\r
+    \n      }\r\\r
+    \n      :onerror Err {\r\\r
+    \n        :local BaseUrl [ \$EitherOr (\$ScriptInfo->\"base-url\") \$Globa\\r
+    lScriptsUrl ];\r\\r
+    \n        :local UrlSuffix [ \$EitherOr (\$ScriptInfo->\"url-suffix\") \$G\\r
+    lobalScriptsUrlSuffix ];\r\\r
+    \n        :local Url (\$BaseUrl . \$ScriptVal->\"name\" . \".rsc\" . \$Url\\r
+    Suffix);\r\\r
+    \n        \$LogPrint warning \$0 (\"Fetching script '\" . (\$ScriptVal->\"\\r
+    name\") . \"' from url: \" . \$Url);\r\\r
+    \n        :local Result [ /tool/fetch check-certificate=yes-without-crl \\\\r
+    \r\\r
+    \n          http-header-field=({ [ \$FetchUserAgentStr \$0 ] }) \$Url outp\\r
+    ut=user as-value ];\r\\r
+    \n        :if (\$Result->\"status\" = \"finished\") do={\r\\r
+    \n          :set SourceNew [ :tolf (\$Result->\"data\") ];\r\\r
+    \n        } \r\\r
+    \n      } do={\r\\r
+    \n        \$LogPrint warning \$0 (\"Failed fetching script '\" . \$ScriptV\\r
+    al->\"name\" . \"': \" . \$Err);\r\\r
+    \n        :if (\$Err != \"Fetch failed with status 404\") do={\r\\r
+    \n          :error false;\r\\r
+    \n        }\r\\r
+    \n        :if (\$ScriptVal->\"source\" = \"#!rsc by Vados\") do={\r\\r
+    \n          \$LogPrint warning \$0 (\"Removing dummy. Typo on installation\\r
+    \?\");\r\\r
+    \n          /system/script/remove \$Script;\r\\r
+    \n          :error false;\r\\r
+    \n        }\r\\r
+    \n        :if (\$CheckSumsVerify = true) do={\r\\r
+    \n          :if ([ :len (\$ScriptInfo->\"base-url\") ] = 0 && [ :len (\$Sc\\r
+    riptInfo->\"url-suffix\") ] = 0 && \\\r\\r
+    \n               [ :len \$CheckSum ] = 0) do={\r\\r
+    \n            \$LogPrint warning \$0 (\"Added the script manually\? Skip u\\r
+    pdates with 'ignore=true' in comment.\");\r\\r
+    \n          }\r\\r
+    \n        }\r\\r
+    \n        :error false;\r\\r
+    \n      }\r\\r
+    \n\r\\r
+    \n      :if ([ :len \$SourceNew ] = 0) do={\r\\r
+    \n        \$LogPrint debug \$0 (\"No update for script '\" . (\$ScriptVal-\\r
+    >\"name\") . \"'.\");\r\\r
+    \n        :error false;\r\\r
+    \n      }\r\\r
+    \n\r\\r
+    \n      :local SourceCRLF [ :tocrlf \$SourceNew ];\r\\r
+    \n      :if (\$InitSetup != true && ((\$ScriptVal->\"name\") != \"AM-Globa\\r
+    lConfig\" || (\$ScriptVal->\"name\") != \"AM-GlobalFunc\")) do={\r\\r
+    \n        :if (\$SourceNew = (\$ScriptVal->\"source\") || \$SourceCRLF = (\\r
+    \$ScriptVal->\"source\")) do={\r\\r
+    \n          \$LogPrint debug \$0 (\"Script '\" .  (\$ScriptVal->\"name\") \\r
+    . \"' source did not change. End of lines set to CRLF.\");\r\\r
+    \n          if (\$ScriptUpdatesCRLF = false) do={\r\\r
+    \n            :put [ :tolf \$SourceNew ];\r\\r
+    \n            \$LogPrint debug \$0 (\"Script '\" .  (\$ScriptVal->\"name\"\\r
+    ) . \"' source update end of lines to LF.\");\r\\r
+    \n          }\r\\r
+    \n        :error false;\r\\r
+    \n        }\r\\r
+    \n      }\r\\r
+    \n\r\\r
+    \n      :if ([ :pick \$SourceNew 0 14 ] != \"#!rsc by Vados\") do={\r\\r
+    \n        \$LogPrint warning \$0 (\"Looks like new script '\" . \$ScriptVa\\r
+    l->\"name\" . \"' is not valid (missing shebang = '\$shebang') Ignoring!\"\\r
+    );\r\\r
+    \n        :error false;\r\\r
+    \n      }\r\\r
+    \n\r\\r
+    \n      :if (\$CommentsInScripts = true) do={\r\\r
+    \n         :local CommentLine [ \$Grep \$SourceNew (\"\\23 Script comment:\\r
+    \_\") ];\r\\r
+    \n         :if ([ :len \$CommentLine ] = 0) do={\r\\r
+    \n           \$LogPrint debug \$0 (\"The search in new script '\" . (\$Scr\\r
+    iptVal->\"name\") . \"' for comment in script body, is not found result Ig\\r
+    noring!\");\r\\r
+    \n           :error false;\r\\r
+    \n         } else={\r\\r
+    \n           :if ([ :len (\$ScriptVal->\"comment\")] = 0 || [ :len (\$Scri\\r
+    ptVal->\"comment\")] != [ :pick \$CommentLine ([ :find \$CommentLine \":\"\\r
+    ] + 2) [ :len \$CommentLine] ]) do={\r\\r
+    \n             \$LogPrint debug \$0 (\"Exsiting comment for script '\" . (\\r
+    \$ScriptVal->\"name\") . \"' is '\" . (\$ScriptVal->\"comment\") . \"'.\")\\r
+    ;\r\\r
+    \n             :set (\$ScriptVal->\"comment\") [ :pick \$CommentLine ([ :f\\r
+    ind \$CommentLine \":\"] + 2) [ :len \$CommentLine] ];\r\\r
+    \n             \$LogPrint debug \$0 (\"New comment (\" . (\$ScriptVal->\"c\\r
+    omment\") . \") for script '\" . (\$ScriptVal->\"name\") . \"' has been ad\\r
+    ded!\");\r\\r
+    \n           } else={\r\\r
+    \n             \$LogPrint debug \$0 (\"Comment for script '\" . (\$ScriptV\\r
+    al->\"name\") . \"' did not change.\");\r\\r
+    \n             :error false;\r\\r
+    \n           }\r\\r
+    \n         }   \r\\r
+    \n      }\r\\r
+    \n\r\\r
+    \n      :local RequiredROS ([ \$ParseKeyValueStore [ \$Grep \$SourceNew (\\r
+    \"\\23 requires RouterOS, \") ] ]->version);\r\\r
+    \n      :if ([ \$RequiredRouterOS \$0 [ \$EitherOr \$RequiredROS \"0.0\" ]\\r
+    \_false ] = false) do={\r\\r
+    \n        \$LogPrint warning \$0 (\"The script '\" . (\$ScriptVal->\"name\\r
+    \") . \"' requires RouterOS \" . \\\r\\r
+    \n            \$RequiredROS . \", which is not met by your installation. I\\r
+    gnoring!\");\r\\r
+    \n        :error false;\r\\r
+    \n      }\r\\r
+    \n      :local RequiredDM [ \$ParseKeyValueStore [ \$Grep \$SourceNew (\"\\r
+    \\23 requires device-mode, \") ] ];\r\\r
+    \n      :local MissingDM ({});\r\\r
+    \n      :foreach Feature,Value in=\$RequiredDM do={\r\\r
+    \n        :if ([ :typeof (\$DeviceMode->\$Feature) ] = \"bool\" && (\$Devi\\r
+    ceMode->\$Feature) = false) do={\r\\r
+    \n          :set MissingDM (\$MissingDM, \$Feature);\r\\r
+    \n        }\r\\r
+    \n      }\r\\r
+    \n      :if ([ :len \$MissingDM ] > 0) do={\r\\r
+    \n        \$LogPrint warning \$0 (\"The script '\" . (\$ScriptVal->\"name\\r
+    \") . \"' requires disabled \" . \\\r\\r
+    \n            \"device-mode features (\" . [ :tostr \$MissingDM ] . \"). I\\r
+    gnoring!\");\r\\r
+    \n        :error false;\r\\r
+    \n      }\r\\r
+    \n\r\\r
+    \n      :if ([ \$ValidateSyntax \$SourceNew ] = false) do={\r\\r
+    \n        \$LogPrint warning \$0 (\"Syntax validation for script '\" . (\$\\r
+    ScriptVal->\"name\") . \"' failed! Ignoring!\");\r\\r
+    \n        :error false;\r\\r
+    \n      }\r\\r
+    \n      \r\\r
+    \n      :log info (\"Updating script: \" . (\$ScriptVal->\"name\") . \" Sc\\r
+    ript comment: \" . (\$ScriptVal->\"comment\"));\r\\r
+    \n\r\\r
+    \n      /system/script/set owner=(\$ScriptVal->\"name\") comment=(\$Script\\r
+    Val->\"comment\") \\\r\\r
+    \n          source=[ \$IfThenElse (\$ScriptUpdatesCRLF = true) \$SourceCRL\\r
+    F \$SourceNew ] \$Script;\r\\r
+    \n      :if (\$ScriptVal->\"name\" = \"AM-GlobalConfig\" || \\\r\\r
+    \n           \$ScriptVal->\"name\" = \"AM-GlobalFunc\" || \\\r\\r
+    \n           \$ScriptVal->\"name\" ~ (\"^(AM-GlobalFunc\\\\.d|mod)/.\")) d\\r
+    o={\r\\r
+    \n        :set ReloadGlobal true;\r\\r
+    \n      }\r\\r
+    \n    } on-error={ }\r\\r
+    \n  }\r\\r
+    \n  :if (\$ReloadGlobal = true) do={\r\\r
+    \n    \$LogPrint info \$0 (\"Reloading global configuration and functions.\\r
+    \");\r\\r
+    \n    :onerror Err {\r\\r
+    \n      :global InitSetup (a);\r\\r
+    \n      /system/script {run AM-GlobalConfig; run AM-GlobalFunc;};\r\\r
+    \n    } do={\$LogPrint error \$0 (\"Reloading global configuration and fun\\r
+    ctions failed! \" . \$Err)}\r\\r
+    \n  }\r\\r
+    \n  :if (\$GlobalConfVersionBefore > \$GlobalConfVersion) do={\r\\r
+    \n    \$LogPrint warning \$0 (\"The configuration version decreased from \\r
+    \" . \\\r\\r
+    \n      \$GlobalConfVersionBefore . \" to \" . \$GlobalConfVersion . \\\r\\r
+    \n      \". Installed an older version\?\");\r\\r
+    \n  }\r\\r
+    \n    :if (\$GlobalConfVersionBefore < \$GlobalConfVersion) do={\r\\r
+    \n    :global GlobalConfChanges;\r\\r
+    \n    :global GlobalConfMigration;\r\\r
+    \n    :local ChangeLogCode;\r\\r
+    \n    :if ([ :len \$ChangeLogCode ] > 0) do={\r\\r
+    \n      :if ([ \$ValidateSyntax \$ChangeLogCode ] = true) do={\r\\r
+    \n        :onerror Err {\r\\r
+    \n          [ :parse \$ChangeLogCode ];\r\\r
+    \n        } do={\$LogPrint warning \$0 (\"The changelog failed to run: \" \\r
+    . \$Err)}\r\\r
+    \n      } else={\$LogPrint warning \$0 (\"The changelog failed syntax vali\\r
+    dation!\")}\r\\r
+    \n    }\r\\r
+    \n    :if ([ :len \$GlobalConfMigration ] > 0) do={\r\\r
+    \n      :for I from=(\$GlobalConfVersionBefore + 1) to=\$GlobalConfVersion\\r
+    \_do={\r\\r
+    \n        :local Migration (\$GlobalConfMigration->[ :tostr \$I ]);\r\\r
+    \n        :do {\r\\r
+    \n          :if ([ :typeof \$Migration ] != \"str\") do={\r\\r
+    \n            \$LogPrint debug \$0 (\"Migration code for change \" . \$I .\\r
+    \_\" is not available.\");\r\\r
+    \n            :error false;\r\\r
+    \n          }\r\\r
+    \n          :if ([ \$ValidateSyntax \$Migration ] = false) do={\r\\r
+    \n            \$LogPrint warning \$0 (\"Migration code for change \" . \$I\\r
+    \_. \" failed syntax validation!\");\r\\r
+    \n            :error false}\r\\r
+    \n          \$LogPrint info \$0 (\"Applying migration for change \" . \$I \\r
+    . \": \" . \$Migration);\r\\r
+    \n          :onerror Err {\r\\r
+    \n            [ :parse \$Migration ];\r\\r
+    \n          } do={\$LogPrint warning \$0 (\"Migration code for change \" .\\r
+    \_\$I . \" failed to run: \" . \$Err)}\r\\r
+    \n        } on-error={ }\r\\r
+    \n      }\r\\r
+    \n    }\r\\r
+    \n    :local NotificationMessage (\"The configuration version on \" . \$Id\\r
+    entity . \" increased \" . \\\r\\r
+    \n       \"to \" . \$GlobalConfVersion . \", current configuration may nee\\r
+    d modification. \" . \\\r\\r
+    \n       \"Please review and update global-config-overlay, then re-run glo\\r
+    bal-config.\");\r\\r
+    \n    \$LogPrint info \$0 (\$NotificationMessage);\r\\r
+    \n    :if ([ :len \$GlobalConfChanges ] > 0) do={\r\\r
+    \n      :set NotificationMessage (\$NotificationMessage . \"\\n\\nChanges:\\r
+    \");\r\\r
+    \n      :for I from=(\$GlobalConfVersionBefore + 1) to=\$GlobalConfVersion\\r
+    \_do={\r\\r
+    \n        :local Change (\$GlobalConfChanges->[ :tostr \$I ]);\r\\r
+    \n        :set NotificationMessage (\$NotificationMessage . \"\\n \" . \\\\r
+    \r\\r
+    \n            [ \$SymbolForNotification \"pushpin\" \"*\" ] . \$Change);\r\\r
+    \n        \$LogPrint info \$0 (\"Change \" . \$I . \": \" . \$Change);\r\\r
+    \n      }\r\\r
+    \n    } else={:set NotificationMessage (\$NotificationMessage . \"\\n\\nNe\\r
+    ws and changes are not available.\")}\r\\r
+    \n\r\\r
+    \n    :set GlobalConfChanges;\r\\r
+    \n    :set GlobalConfMigration;\r\\r
+    \n  }\r\\r
+    \n} do={:global ExitOnError; \$ExitOnError \$0 \$Err}\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set FetchUserAgentStr do={\r\\r
+    \n  :local Caller [ :tostr \$1 ];\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :local Resource [ /system/resource/get ];\r\\r
+    \n  :return (\"User-Agent: Mikrotik/\" . \$Resource->\"version\" . \" \" .\\r
+    \_\$Resource->\"architecture-name\" . \\\r\\r
+    \n    \" \" . \$Caller . \"/Fetch (https://amster.vados.ru/; main/3419/3ee\\r
+    19780)\");\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set Grep do={\r\\r
+    \n  :local Input  ([ :tostr \$1 ] . \"\\n\");\r\\r
+    \n  :local Pattern [ :tostr \$2 ];\r\\r
+    \n  :if ([ :typeof [ :find \$Input \$Pattern ] ] = \"nil\") do={:return []\\r
+    }\r\\r
+    \n  :do {\r\\r
+    \n    :local Line [ :pick \$Input 0 [ :find \$Input \"\\n\" ] ];\r\\r
+    \n    :if ([ :typeof [ :find \$Line \$Pattern ] ] = \"num\") do={:return \\r
+    \$Line}\r\\r
+    \n    :set Input [ :pick \$Input ([ :find \$Input \"\\n\" ] + 1) [ :len \$\\r
+    Input ] ];\r\\r
+    \n  } while=([ :len \$Input ] > 0);\r\\r
+    \n  :return [];\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set HumanReadableNum do={\r\\r
+    \n  :local Input [ :tonum \$1 ];\r\\r
+    \n  :local Base  [ :tonum \$2 ];\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :local Prefix \"kMGTPE\";\r\\r
+    \n  :local Pow 1;\r\\r
+    \n  :set Base [ \$EitherOr \$Base 1024 ];\r\\r
+    \n  :local Bin [ \$IfThenElse (\$Base = 1024) \"i\" \"\" ];\r\\r
+    \n  :if (\$Input < \$Base) do={:return \$Input}\r\\r
+    \n  :for I from=0 to=[ :len \$Prefix ] do={\r\\r
+    \n    :set Pow (\$Pow * \$Base);\r\\r
+    \n    :if (\$Input / \$Base < \$Pow) do={\r\\r
+    \n      :set Prefix [ :pick \$Prefix \$I ];\r\\r
+    \n      :local Tmp1 (\$Input * 100 / \$Pow);\r\\r
+    \n      :local Tmp2 (\$Tmp1 / 100);\r\\r
+    \n      :if (\$Tmp2 >= 100) do={:return (\$Tmp2 . \$Prefix . \$Bin)}\r\\r
+    \n      :return (\$Tmp2 . \".\" . \\\r\\r
+    \n          [ :pick \$Tmp1 [ :len \$Tmp2 ] ([ :len \$Tmp1 ] - [ :len \$Tmp\\r
+    2 ] + 1) ] . \\\r\\r
+    \n          \$Prefix . \$Bin);\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CleanName do={\r\\r
+    \n  :local Input [ :tostr \$1 ];\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :for I from=0 to=([ :len \$Input ] - 1) do={\r\\r
+    \n    :local Char [ :pick \$Input \$I ];\r\\r
+    \n    :if ([ :typeof [ find \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr\\r
+    stuvwxyz0123456789\" \$Char ] ] = \"nil\") do={\r\\r
+    \n      :do {:if ([ :len \$Return ] = 0) do={:error true};\r\\r
+    \n        :if ([ :pick \$Return ([ :len \$Return ] - 1) ] = \"-\") do={:er\\r
+    ror true}; :set Char \"-\"} on-error={:set Char \"\"}; \r\\r
+    \n    };\r\\r
+    \n    :set Return (\$Return . \$Char)};\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set GetRandomNumber do={\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :return [ :rndnum from=0 to=[ \$EitherOr [ :tonum \$1 ] 4294967295 ] ]\\r
+    \r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set RandomDelay do={\r\\r
+    \n  :local Time [ :tonum \$1 ];\r\\r
+    \n  :local Unit [ :tostr \$2 ];\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :global GetRandomNumber;\r\\r
+    \n  :global MAX;\r\\r
+    \n  :if (\$Time = 0) do={:return false}\r\\r
+    \n  :delay ([ \$MAX 10 [ \$GetRandomNumber ([ :tonsec [ :totime (\$Time . \\r
+    [ \$EitherOr \$Unit \"s\" ]) ] ] / 1000000) ] ] . \"ms\");\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set EscapeForRegEx do={\r\\r
+    \n  :local Input [ :tostr \$1 ];\r\\r
+    \n  :if ([ :len \$Input ] = 0) do={:return \"\"}\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :local Chars (\"^.[]\\\$()|*+\?{}\\\\\");\r\\r
+    \n  :for I from=0 to=([ :len \$Input ] - 1) do={\r\\r
+    \n    :local Char [ :pick \$Input \$I ];\r\\r
+    \n    :if ([ :find \$Chars \$Char ]) do={:set Char (\"\\\\\" . \$Char)}\r\\r
+    \n    :set Return (\$Return . \$Char);\r\\r
+    \n  }\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n:set ExitError do={\r\\r
+    \n  :local ExitOK [ :tostr \$1 ];\r\\r
+    \n  :local Name   [ :tostr \$2 ];\r\\r
+    \n  :local Error  [ :tostr \$3 ];\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :if (\$ExitOK = \"false\") do={\r\\r
+    \n    \$LogPrint error \$Name ([ \$IfThenElse ([ :pick \$Name 0 1 ] = \"\\\\r
+    \$\") \\\r\\r
+    \n        \"Function\" \"Script\" ] . \" '\" . \$Name . \"' exited with er\\r
+    ror\" . \\\r\\r
+    \n        [ \$IfThenElse (!(\$Error ~ \"^(|true|false)\\\$\")) (\": \" . \\r
+    \$Error) \".\" ]);\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set MiniDateTimeStamp do={\r\\r
+    \n    /system/clock;\r\\r
+    \n    :local vdate [get date];\r\\r
+    \n    :local vtime [get time];\r\\r
+    \n    :local vdoff [:toarray \"0,4,5,7,8,10\"];\r\\r
+    \n    :local MM    [:pick \$vdate (\$vdoff->2) (\$vdoff->3)];\r\\r
+    \n    :local M     [:tonum \$MM];\r\\r
+    \n    :if (\$vdate ~ \".../../....\") do={\r\\r
+    \n        :set vdoff [:toarray \"7,11,1,3,4,6\"];\r\\r
+    \n        :set M     ([:find \"xxanebarprayunulugepctovecANEBARPRAYUNULUGE\\r
+    PCTOVEC\" [:pick \$vdate (\$vdoff->2) (\$vdoff->3)] -1] / 2);\r\\r
+    \n        :if (\$M>12) do={:set M (\$M - 12)}\r\\r
+    \n        :set MM    [:pick (100 + \$M) 1 3];\r\\r
+    \n    }\r\\r
+    \n    :local yyyy [:pick \$vdate (\$vdoff->0) (\$vdoff->1)];\r\\r
+    \n    :local dd   [:pick \$vdate (\$vdoff->4) (\$vdoff->5)];\r\\r
+    \n    :local HH   [:pick \$vtime 0  2];\r\\r
+    \n    :local mm   [:pick \$vtime 3  5];\r\\r
+    \n    :local ss   [:pick \$vtime 6  8];\r\\r
+    \n    :return ([\$yyyy] . [\$MM] . [\$dd] . [\$HH] . [\$mm] . [\$ss]);\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set WaitForFile do={\r\\r
+    \n  :local FileName [ :tostr  \$1 ];\r\\r
+    \n  :local WaitTime [ :totime \$2 ];\r\\r
+    \n  :global CleanFilePath;\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :global MAX;\r\\r
+    \n  :set FileName [ \$CleanFilePath \$FileName ];\r\\r
+    \n  :local Delay ([ \$MAX [ \$EitherOr \$WaitTime 2s ] 100ms ] / 9);\r\\r
+    \n  :do {\r\\r
+    \n    :retry {\r\\r
+    \n      /file/get \$FileName;\r\\r
+    \n      :return true;\r\\r
+    \n    } delay=\$Delay max=10;\r\\r
+    \n  } on-error={ }\r\\r
+    \n  :while ([ :len [ /file/find where name=\$FileName ] ] > 0) do={\r\\r
+    \n    :do {\r\\r
+    \n      /file/get \$FileName;\r\\r
+    \n      :return true;\r\\r
+    \n    } on-error={ }\r\\r
+    \n    :delay \$Delay;\r\\r
+    \n    :set Delay (\$Delay * 3 / 2);\r\\r
+    \n  }\r\\r
+    \n  :return false;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set FileGet do={\r\\r
+    \n  :local FileName [ :tostr \$1 ];\r\\r
+    \n  :global WaitForFile;\r\\r
+    \n  :if ([ \$WaitForFile \$FileName 0s ] = false) do={:return false}\r\\r
+    \n  :local FileVal false;\r\\r
+    \n  :do {:set FileVal [ /file/get \$FileName ];\r\\r
+    \n   } on-error={ }\r\\r
+    \n  :return \$FileVal;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set RmDir do={\r\\r
+    \n  :local DirName [ :tostr \$1 ];\r\\r
+    \n  :global FileGet;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  \$LogPrint debug \$0 (\"Removing directory: \". \$DirName);\r\\r
+    \n  :local DirVal [ \$FileGet \$DirName ];\r\\r
+    \n  :if (\$DirVal = false) do={\$LogPrint debug \$0 (\"... which does not \\r
+    exist.\"); :return true};\r\\r
+    \n  :if (\$DirVal->\"type\" != \"directory\") do={\$LogPrint error \$0 (\"\\r
+    Directory '\" . \$DirName . \"' is not a directory.\"); :return false};\r\\r
+    \n  :onerror Err {/file/remove \$DirName} do={\$LogPrint error \$0 (\"Remo\\r
+    ving directory '\" . \$DirName . \"' failed: \" . \$Err); :return false};\\r
+    \r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set RmFile do={\r\\r
+    \n  :local FileName [ :tostr \$1 ];\r\\r
+    \n  :global FileGet;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  \$LogPrint debug \$0 (\"Removing file: \". \$FileName);\r\\r
+    \n  :local FileVal [ \$FileGet \$FileName ];\r\\r
+    \n  :if (\$FileVal = false) do={\$LogPrint debug \$0 (\"... which does not\\r
+    \_exist.\"); :return true}\r\\r
+    \n  :if (\$FileVal->\"type\" = \"directory\" || \$FileVal->\"type\" = \"di\\r
+    sk\") do={\r\\r
+    \n    \$LogPrint error \$0 (\"File '\" . \$FileName . \"' is not a file.\"\\r
+    ); :return false}\r\\r
+    \n  :onerror Err {\r\\r
+    \n    /file/remove \$FileName;\r\\r
+    \n  } do={\$LogPrint error \$0 (\"Removing file '\" . \$FileName . \"' fai\\r
+    led: \" . \$Err); :return false}\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set MkDir do={\r\\r
+    \n  :local Path [ :tostr \$1 ];\r\\r
+    \n  :global CleanFilePath;\r\\r
+    \n  :global FileGet;\r\\r
+    \n  :global RmDir;\r\\r
+    \n  :global WaitForFile;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :local MkTmpfs do={\r\\r
+    \n   :global WaitForFile;\r\\r
+    \n   :local TmpFs [ /disk/find where slot=tmpfs type=tmpfs ];\r\\r
+    \n   :if ([ :len \$TmpFs ] = 1) do={\r\\r
+    \n     :if ([ /disk/get \$TmpFs disabled ] = true) do={\r\\r
+    \n       \$LogPrint info \$0 (\"The tmpfs is disabled, enabling.\");\r\\r
+    \n       /disk/enable \$TmpFs;\r\\r
+    \n      }\r\\r
+    \n      :return true;\r\\r
+    \n    }\r\\r
+    \n    \$LogPrint info \$0 (\"Creating disk of type tmpfs.\");\r\\r
+    \n    \$RmDir \"tmpfs\";\r\\r
+    \n    :onerror Err {\r\\r
+    \n      /disk/add slot=tmpfs type=tmpfs tmpfs-max-size=([ /system/resource\\r
+    /get total-memory ] / 3);\r\\r
+    \n      \$WaitForFile \"tmpfs\";\r\\r
+    \n    } do={\r\\r
+    \n      \$LogPrint warning \$0 (\"Creating disk of type tmpfs failed: \" .\\r
+    \_\$Err);\r\\r
+    \n      :return false;\r\\r
+    \n    }\r\\r
+    \n    :return true;\r\\r
+    \n  }\r\\r
+    \n  :set Path [ \$CleanFilePath \$Path ];\r\\r
+    \n  :if (\$Path = \"\") do={\r\\r
+    \n    :return true;\r\\r
+    \n  }\r\\r
+    \n  \$LogPrint debug \$0 (\"Making directory: \" . \$Path);\r\\r
+    \n  :local PathVal [ \$FileGet \$Path ];\r\\r
+    \n  :if (\$PathVal->\"type\" = \"directory\") do={\r\\r
+    \n    \$LogPrint debug \$0 (\"... which already exists.\");\r\\r
+    \n    :return true;\r\\r
+    \n  }\r\\r
+    \n  :if ([ :pick \$Path 0 5 ] = \"tmpfs\") do={\r\\r
+    \n    :if ([ \$MkTmpfs ] = false) do={\r\\r
+    \n      :return false;\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  :onerror Err {\r\\r
+    \n    /file/add type=\"directory\" name=\$Path;\r\\r
+    \n    \$WaitForFile \$Path;\r\\r
+    \n  } do={\r\\r
+    \n    \$LogPrint warning \$0 (\"Making directory '\" . \$Path . \"' failed\\r
+    : \" . \$Err);\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set MAX do={:if (\$1 > \$2) do={:return \$1}\r\\r
+    \n :return \$2;\r\\r
+    \n}\r\\r
+    \n:set MIN do={:if (\$1 < \$2) do={:return \$1}\r\\r
+    \n :return \$2;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CharacterMultiply do={\r\\r
+    \n  :local Str [ :tostr \$1 ];\r\\r
+    \n  :local Num [ :tonum \$2 ];\r\\r
+    \n  :if (\$Num = 0) do={:return \"\"}\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :for I from=1 to=\$Num do={:set Return (\$Return . \$Str)}\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CharacterReplace do={\r\\r
+    \n  :local String [ :tostr \$1 ];\r\\r
+    \n  :local ReplaceFrom [ :tostr \$2 ];\r\\r
+    \n  :local ReplaceWith [ :tostr \$3 ];\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :if (\$ReplaceFrom = \"\") do={:return \$String}\r\\r
+    \n  :while ([ :typeof [ :find \$String \$ReplaceFrom ] ] != \"nil\") do={\\r
+    \r\\r
+    \n    :local Pos [ :find \$String \$ReplaceFrom ];\r\\r
+    \n    :set Return (\$Return . [ :pick \$String 0 \$Pos ] . \$ReplaceWith);\\r
+    \r\\r
+    \n    :set String [ :pick \$String (\$Pos + [ :len \$ReplaceFrom ]) [ :len\\r
+    \_\$String ] ];\r\\r
+    \n  }\r\\r
+    \n  :return (\$Return . \$String);\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set CleanFilePath do={\r\\r
+    \n  :local Path [ :tostr \$1 ];\r\\r
+    \n  :global CharacterReplace;\r\\r
+    \n  :while (\$Path ~ \"//\") do={:set \$Path [ \$CharacterReplace \$Path \\r
+    \"//\" \"/\" ]};\r\\r
+    \n  :if ([ :pick \$Path 0 ] = \"/\") do={:set Path [ :pick \$Path 1 [ :len\\r
+    \_\$Path ] ]};\r\\r
+    \n  :if ([ :pick \$Path ([ :len \$Path ] - 1) ] = \"/\") do={:set Path [ :\\r
+    pick \$Path 0 ([ :len \$Path ] - 1) ]};\r\\r
+    \n  :return \$Path;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set IfThenElse do={\r\\r
+    \n  :if ([ :tostr \$1 ] = \"true\" || [ :tobool \$1 ] = true) do={:return \\r
+    \$2};\r\\r
+    \n  :return \$3;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set EitherOr do={\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :if ([ :typeof \$1 ] = \"num\") do={:return [ \$IfThenElse (\$1 != 0) \\r
+    \$1 \$2 ]}\r\\r
+    \n  :if ([ :typeof \$1 ] = \"time\") do={:return [ \$IfThenElse (\$1 > 0s)\\r
+    \_\$1 \$2 ]}\r\\r
+    \n# this works for boolean values, literal ones with parentheses\r\\r
+    \n  :return [ \$IfThenElse ([ :len [ :tostr \$1 ] ] > 0) \$1 \$2 ];\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n:set ParseKeyValueStore do={\r\\r
+    \n  :local Source \$1;\r\\r
+    \n  :if ([ :pick \$Source 0 1 ] = \"{\") do={\r\\r
+    \n    :do {\r\\r
+    \n      :return [ :deserialize from=json \$Source ];\r\\r
+    \n    } on-error={ }\r\\r
+    \n  }   \r\\r
+    \n  :if ([ :typeof \$Source ] != \"array\") do={:set Source [ :tostr \$1 ]\\r
+    }\r\\r
+    \n  :local Result ({});\r\\r
+    \n  :foreach KeyValue in=[ :toarray \$Source ] do={\r\\r
+    \n    :if ([ :find \$KeyValue \"=\" ]) do={\r\\r
+    \n      :local Key [ :pick \$KeyValue 0 [ :find \$KeyValue \"=\" ] ];\r\\r
+    \n      :local Value [ :pick \$KeyValue ([ :find \$KeyValue \"=\" ] + 1) [\\r
+    \_:len \$KeyValue ] ];\r\\r
+    \n      :if (\$Value=\"true\") do={:set Value true}\r\\r
+    \n      :if (\$Value=\"false\") do={:set Value false}\r\\r
+    \n      :set (\$Result->\$Key) \$Value;\r\\r
+    \n      } else={:set (\$Result->\$KeyValue) true}\r\\r
+    \n  }\r\\r
+    \n  :return \$Result;\r\\r
+    \n}\r\\r
+    \n:set RequiredRouterOS do={\r\\r
+    \n  :local Caller   [ :tostr \$1 ];\r\\r
+    \n  :local Required [ :tostr \$2 ];\r\\r
+    \n  :local Warn     [ :tostr \$3 ];\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global VersionToNum;\r\\r
+    \n  :if (!(\$Required ~ \"^\\\\d+\\\\.\\\\d+((alpha|beta|rc|\\\\.)\\\\d+|)\\r
+    \\\$\")) do={\r\\r
+    \n    \$LogPrint error \$0 (\"No valid RouterOS version: \" . \$Required);\\r
+    \r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :if ([ \$VersionToNum \$Required ] > [ \$VersionToNum [ /system/packag\\r
+    e/update/get installed-version ] ]) do={\r\\r
+    \n    :if (\$Warn = \"true\") do={\r\\r
+    \n      \$LogPrint warning \$0 (\"This \" . [ \$IfThenElse ([ :pick \$Call\\r
+    er 0 ] = (\"\\\$\")) \"function\" \"script\" ] . \\\r\\r
+    \n        \" '\" . \$Caller . \"' (at least specific functionality) requir\\r
+    es RouterOS \" . \$Required . \". Please update!\");\r\\r
+    \n    }\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n:set VersionToNum do={\r\\r
+    \n  :local Input [ :tostr \$1 ];\r\\r
+    \n  :local Multi 0x1000000;\r\\r
+    \n  :local Return 0;\r\\r
+    \n  :global CharacterReplace;\r\\r
+    \n  :set Input [ \$CharacterReplace \$Input \".\" \",\" ];\r\\r
+    \n  :foreach I in={ \"zero\"; \"alpha\"; \"beta\"; \"rc\" } do={\r\\r
+    \n    :set Input [ \$CharacterReplace \$Input \$I (\",\" . \$I . \",\") ];\\r
+    \r\\r
+    \n  }\r\\r
+    \n  :foreach Value in=([ :toarray \$Input ], 0) do={\r\\r
+    \n    :local Num [ :tonum \$Value ];\r\\r
+    \n    :if (\$Multi = 0x100) do={\r\\r
+    \n      :if ([ :typeof \$Num ] = \"num\") do={\r\\r
+    \n        :set Return (\$Return + 0xff00);\r\\r
+    \n        :set Multi (\$Multi / 0x100);\r\\r
+    \n      } else={\r\\r
+    \n        :if (\$Value = \"zero\") do={ }\r\\r
+    \n        :if (\$Value = \"alpha\") do={ :set Return (\$Return + 0x3f00); \\r
+    }\r\\r
+    \n        :if (\$Value = \"beta\") do={ :set Return (\$Return + 0x5f00); }\\r
+    \r\\r
+    \n        :if (\$Value = \"rc\") do={ :set Return (\$Return + 0x7f00); }\r\\r
+    \n      }\r\\r
+    \n    }\r\\r
+    \n    :if ([ :typeof \$Num ] = \"num\") do={ :set Return (\$Return + (\$Va\\r
+    lue * \$Multi)); }\r\\r
+    \n    :set Multi (\$Multi / 0x100);\r\\r
+    \n  }\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n:set ScriptLock do={\r\\r
+    \n  :local Script  [ :tostr  \$1 ];\r\\r
+    \n  :local WaitMax [ :totime \$2 ];\r\\r
+    \n  :global GetRandom20CharAlNum;\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global ScriptLockOrder;\r\\r
+    \n  :if ([ :typeof \$ScriptLockOrder ] = \"nothing\") do={\r\\r
+    \n    :set ScriptLockOrder ({});\r\\r
+    \n  }\r\\r
+    \n  :if ([ :typeof (\$ScriptLockOrder->\$Script) ] = \"nothing\") do={\r\\r
+    \n    :set (\$ScriptLockOrder->\$Script) ({});\r\\r
+    \n  }\r\\r
+    \n  :local JobCount do={\r\\r
+    \n    :local Script [ :tostr \$1 ];\r\\r
+    \n    :return [ :len [ /system/script/job/find where script=\$Script ] ];\\r
+    \r\\r
+    \n  }\r\\r
+    \n  :local TicketCount do={\r\\r
+    \n    :local Script [ :tostr \$1 ];\r\\r
+    \n    :global ScriptLockOrder;\r\\r
+    \n    :local Count 0;\r\\r
+    \n    :foreach Ticket in=(\$ScriptLockOrder->\$Script) do={\r\\r
+    \n      :if ([ :typeof \$Ticket ] != \"nothing\") do={:set Count (\$Count \\r
+    + 1)}\r\\r
+    \n    }\r\\r
+    \n    :return \$Count;\r\\r
+    \n  }\r\\r
+    \n  :local IsFirstTicket do={\r\\r
+    \n    :local Script [ :tostr \$1 ];\r\\r
+    \n    :local Check  [ :tostr \$2 ];\r\\r
+    \n    :global ScriptLockOrder;\r\\r
+    \n    :foreach Ticket in=(\$ScriptLockOrder->\$Script) do={\r\\r
+    \n      :if (\$Ticket = \$Check) do={:return true}\r\\r
+    \n      :if ([ :typeof \$Ticket ] != \"nothing\" && \$Ticket != \$Check) d\\r
+    o={:return false}\r\\r
+    \n    }\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :local AddTicket do={\r\\r
+    \n    :local Script [ :tostr \$1 ];\r\\r
+    \n    :local Add    [ :tostr \$2 ];\r\\r
+    \n    :global ScriptLockOrder;\r\\r
+    \n    :while (true) do={\r\\r
+    \n      :local Pos [ :len (\$ScriptLockOrder->\$Script) ];\r\\r
+    \n      :set (\$ScriptLockOrder->\$Script->\$Pos) \$Add;\r\\r
+    \n      :delay 10ms;\r\\r
+    \n      :if ((\$ScriptLockOrder->\$Script->\$Pos) = \$Add) do={:return tru\\r
+    e}\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  :local RemoveTicket do={\r\\r
+    \n    :local Script [ :tostr \$1 ];\r\\r
+    \n    :local Remove [ :tostr \$2 ];\r\\r
+    \n    :global ScriptLockOrder;\r\\r
+    \n    :foreach Id,Ticket in=(\$ScriptLockOrder->\$Script) do={\r\\r
+    \n      :while ((\$ScriptLockOrder->\$Script->\$Id) = \$Remove) do={\r\\r
+    \n        :set (\$ScriptLockOrder->\$Script->\$Id);\r\\r
+    \n        :delay 10ms;\r\\r
+    \n      }\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  :local CleanupTickets do={\r\\r
+    \n    :local Script [ :tostr \$1 ];\r\\r
+    \n    :global ScriptLockOrder;\r\\r
+    \n    :foreach Ticket in=(\$ScriptLockOrder->\$Script) do={\r\\r
+    \n      :if ([ :typeof \$Ticket ] != \"nothing\") do={:return false}\r\\r
+    \n    }\r\\r
+    \n    :set (\$ScriptLockOrder->\$Script) ({});\r\\r
+    \n  }\r\\r
+    \n  :if ([ :typeof \$WaitMax ] = \"nil\" ) do={:set WaitMax 0s}\r\\r
+    \n  :if ([ :len [ /system/script/find where name=\$Script ] ] = 0) do={\r\\r
+    \n    \$LogPrint error \$0 (\"A script named '\" . \$Script . \"' does not\\r
+    \_exist!\");\r\\r
+    \n    :error false;\r\\r
+    \n  }\r\\r
+    \n  :if ([ \$JobCount \$Script ] = 0) do={\r\\r
+    \n    \$LogPrint error \$0 (\"No script '\" . \$Script . \"' is running!\"\\r
+    );\r\\r
+    \n    :error false;\r\\r
+    \n  }\r\\r
+    \n  :if ([ \$TicketCount \$Script ] >= [ \$JobCount \$Script ]) do={\r\\r
+    \n    \$LogPrint error \$0 (\"More tickets than running scripts '\" . \$Sc\\r
+    ript . \"', resetting!\");\r\\r
+    \n    :set (\$ScriptLockOrder->\$Script) ({});\r\\r
+    \n    /system/script/job/remove [ find where script=\$Script ];\r\\r
+    \n  }\r\\r
+    \n  :local MyTicket [ \$GetRandom20CharAlNum 6 ];\r\\r
+    \n  \$AddTicket \$Script \$MyTicket;\r\\r
+    \n  :local WaitInterval (\$WaitMax / 20);\r\\r
+    \n  :local WaitTime \$WaitMax;\r\\r
+    \n  :while (\$WaitTime > 0 && \\\r\\r
+    \n      ([ \$IsFirstTicket \$Script \$MyTicket ] = false || \\\r\\r
+    \n      [ \$TicketCount \$Script ] < [ \$JobCount \$Script ])) do={\r\\r
+    \n    :set WaitTime (\$WaitTime - \$WaitInterval);\r\\r
+    \n    :delay \$WaitInterval;\r\\r
+    \n  }\r\\r
+    \n  :if ([ \$IsFirstTicket \$Script \$MyTicket ] = true && \\\r\\r
+    \n      [ \$TicketCount \$Script ] = [ \$JobCount \$Script ]) do={\r\\r
+    \n    \$RemoveTicket \$Script \$MyTicket;\r\\r
+    \n    \$CleanupTickets \$Script;\r\\r
+    \n    :return true;\r\\r
+    \n  }\r\\r
+    \n  \$RemoveTicket \$Script \$MyTicket;\r\\r
+    \n  \$LogPrint debug \$0 (\"Script '\" . \$Script . \"' started more than \\r
+    once\" . \\\r\\r
+    \n    [ \$IfThenElse (\$WaitTime < \$WaitMax) \" and timed out waiting for\\r
+    \_lock\" \"\" ] . \"...\");\r\\r
+    \n  :return false;\r\\r
+    \n}\r\\r
+    \n:set SendNotification do={ :onerror Err {\r\\r
+    \n  :global SendNotification2;\r\\r
+    \n  \$SendNotification2 ({ origin=\$0; subject=\$1; message=\$2; link=\$3;\\r
+    \_silent=\$4 });\r\\r
+    \n} do={:global ExitOnError; \$ExitOnError \$0 \$Err}\r\\r
+    \n}\r\\r
+    \n:set SendNotification2 do={\r\\r
+    \n  :local Notification \$1;\r\\r
+    \n  :global NotificationFunctions;\r\\r
+    \n  :foreach FunctionName,Discard in=\$NotificationFunctions do={\r\\r
+    \n    (\$NotificationFunctions->\$FunctionName) (\"\\\$NotificationFunctio\\r
+    ns->\\\"\" . \$FunctionName . \"\\\"\") \$Notification;\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n:set SymbolByUnicodeName do={\r\\r
+    \n  :local Name [ :tostr \$1 ];\r\\r
+    \n  :global EitherOr;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global SymbolsExtra;\r\\r
+    \n  :local Symbols ({\r\\r
+    \n    \"abacus\"=\"\\F0\\9F\\A7\\AE\";\r\\r
+    \n    \"alarm-clock\"=\"\\E2\\8F\\B0\";\r\\r
+    \n    \"arrow-down\"=\"\\E2\\AC\\87\";\r\\r
+    \n    \"arrow-up\"=\"\\E2\\AC\\86\";\r\\r
+    \n    \"calendar\"=\"\\F0\\9F\\93\\85\";\r\\r
+    \n    \"card-file-box\"=\"\\F0\\9F\\97\\83\";\r\\r
+    \n    \"chart-decreasing\"=\"\\F0\\9F\\93\\89\";\r\\r
+    \n    \"chart-increasing\"=\"\\F0\\9F\\93\\88\";\r\\r
+    \n    \"cloud\"=\"\\E2\\98\\81\";\r\\r
+    \n    \"cross-mark\"=\"\\E2\\9D\\8C\";\r\\r
+    \n    \"earth\"=\"\\F0\\9F\\8C\\8D\";\r\\r
+    \n    \"fire\"=\"\\F0\\9F\\94\\A5\";\r\\r
+    \n    \"floppy-disk\"=\"\\F0\\9F\\92\\BE\";\r\\r
+    \n    \"gear\"=\"\\E2\\9A\\99\";\r\\r
+    \n    \"heart\"=\"\\E2\\99\\A5\";\r\\r
+    \n    \"high-voltage-sign\"=\"\\E2\\9A\\A1\";\r\\r
+    \n    \"incoming-envelope\"=\"\\F0\\9F\\93\\A8\";\r\\r
+    \n    \"information\"=\"\\E2\\84\\B9\";\r\\r
+    \n    \"large-orange-circle\"=\"\\F0\\9F\\9F\\A0\";\r\\r
+    \n    \"large-red-circle\"=\"\\F0\\9F\\94\\B4\";\r\\r
+    \n    \"link\"=\"\\F0\\9F\\94\\97\";\r\\r
+    \n    \"lock-with-ink-pen\"=\"\\F0\\9F\\94\\8F\";\r\\r
+    \n    \"memo\"=\"\\F0\\9F\\93\\9D\";\r\\r
+    \n    \"mobile-phone\"=\"\\F0\\9F\\93\\B1\";\r\\r
+    \n    \"pushpin\"=\"\\F0\\9F\\93\\8C\";\r\\r
+    \n    \"scissors\"=\"\\E2\\9C\\82\";\r\\r
+    \n    \"scroll\"=\"\\F0\\9F\\93\\9C\";\r\\r
+    \n    \"smiley-partying-face\"=\"\\F0\\9F\\A5\\B3\";\r\\r
+    \n    \"smiley-smiling-face\"=\"\\E2\\98\\BA\";\r\\r
+    \n    \"smiley-winking-face-with-tongue\"=\"\\F0\\9F\\98\\9C\";\r\\r
+    \n    \"sparkles\"=\"\\E2\\9C\\A8\";\r\\r
+    \n    \"speech-balloon\"=\"\\F0\\9F\\92\\AC\";\r\\r
+    \n    \"star\"=\"\\E2\\AD\\90\";\r\\r
+    \n    \"warning-sign\"=\"\\E2\\9A\\A0\";\r\\r
+    \n    \"white-heavy-check-mark\"=\"\\E2\\9C\\85\"\r\\r
+    \n  }, \$SymbolsExtra);\r\\r
+    \n  :local Magic [ :pick [ /system/clock/get date ] 4 10 ];\r\\r
+    \n  :local Special {\r\\r
+    \n    \"information-04-01\"=\"\\F0\\9F\\9A\\BB\";\r\\r
+    \n    \"large-orange-circle-04-01\"=\"\\F0\\9F\\8D\\8A\";\r\\r
+    \n    \"large-orange-circle-10-31\"=\"\\F0\\9F\\8E\\83\";\r\\r
+    \n    \"large-red-circle-04-01\"=\"\\F0\\9F\\8D\\92\" };\r\\r
+    \n  :if ([ :len (\$Symbols->\$Name) ] = 0) do={\r\\r
+    \n    \$LogPrint warning \$0 (\"No symbol available for name '\" . \$Name \\r
+    . \"'!\");\r\\r
+    \n    :return \"\";\r\\r
+    \n  }\r\\r
+    \n  :return ([ \$EitherOr (\$Special->(\$Name . \$Magic)) (\$Symbols->\$Na\\r
+    me) ] . \"\\EF\\B8\\8F\");\r\\r
+    \n}\r\\r
+    \n:set SymbolForNotification do={\r\\r
+    \n  :global NotificationsWithSymbols;\r\\r
+    \n  :global SymbolByUnicodeName;\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :if (\$NotificationsWithSymbols != true) do={:return [ \$IfThenElse ([\\r
+    \_:len \$2 ] > 0) ([ :tostr \$2 ] . \" \") \"\" ]}\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :foreach Symbol in=[ :toarray \$1 ] do={:set Return (\$Return . [ \$Sy\\r
+    mbolByUnicodeName \$Symbol ])}\r\\r
+    \n  :return (\$Return . \" \");\r\\r
+    \n}\r\\r
+    \n:set Unix2Dos do={:return [ :tocrlf [ :tostr \$1 ] ]}\r\\r
+    \n:set UrlEncode do={\r\\r
+    \n  :local Input [ :tostr \$1 ];\r\\r
+    \n  :if ([ :len \$Input ] = 0) do={:return \"\"}\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :local Chars (\"\\n\\r !\\\"#\\\$%&'()*+,:;<=>\?@[\\\\]^`{|}~\");\r\\r
+    \n  :local Subs { \"%0A\"; \"%0D\"; \"%20\"; \"%21\"; \"%22\"; \"%23\"; \"\\r
+    %24\"; \"%25\"; \"%26\"; \"%27\";\r\\r
+    \n         \"%28\"; \"%29\"; \"%2A\"; \"%2B\"; \"%2C\"; \"%3A\"; \"%3B\"; \\r
+    \"%3C\"; \"%3D\"; \"%3E\"; \"%3F\";\r\\r
+    \n         \"%40\"; \"%5B\"; \"%5C\"; \"%5D\"; \"%5E\"; \"%60\"; \"%7B\"; \\r
+    \"%7C\"; \"%7D\"; \"%7E\" };\r\\r
+    \n  :for I from=0 to=([ :len \$Input ] - 1) do={\r\\r
+    \n    :local Char [ :pick \$Input \$I ];\r\\r
+    \n    :local Replace [ :find \$Chars \$Char ];\r\\r
+    \n    :if ([ :typeof \$Replace ] = \"num\") do={:set Char (\$Subs->\$Repla\\r
+    ce)}\r\\r
+    \n    :set Return (\$Return . \$Char);\r\\r
+    \n  }\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n:set ValidateSyntax do={\r\\r
+    \n  :local Code [ :tostr \$1 ];\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :onerror Err {\r\\r
+    \n    [ :parse (\":local Validate do={\\n\" . \$Code . \"\\n}\") ];\r\\r
+    \n  } do={\r\\r
+    \n    \$LogPrint debug \$0 (\"Valdation failed: \" . \$Err);\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n:set IsDNSResolving do={\r\\r
+    \n  :do {:resolve \"api.telegram.org\"} on-error={:return false}\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n:set IsFullyConnected do={\r\\r
+    \n  :global IsDNSResolving;\r\\r
+    \n  :global IsTimeSync;\r\\r
+    \n  :if ([ \$IsDNSResolving ] = false) do={:return false};\r\\r
+    \n  :if ([ \$IsTimeSync ] = false) do={:return false};\r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n:set IsTimeSync do={\r\\r
+    \n  :global IsTimeSyncCached;\r\\r
+    \n  :global IsTimeSyncResetNtp;\r\\r
+    \n  :if (\$IsTimeSyncCached = true) do={:return true}\r\\r
+    \n  :if ([ /system/ntp/client/get enabled ] = true) do={\r\\r
+    \n    :if ([ /system/ntp/client/get status ] = \"synchronized\") do={\r\\r
+    \n      :set IsTimeSyncCached true;\r\\r
+    \n      :return true;\r\\r
+    \n    }\r\\r
+    \n    :local Uptime [ /system/resource/get uptime ];\r\\r
+    \n    :if ([ :typeof \$IsTimeSyncResetNtp ] = \"nothing\") do={\r\\r
+    \n      :set IsTimeSyncResetNtp \$Uptime;\r\\r
+    \n    }\r\\r
+    \n    :if (\$Uptime - \$IsTimeSyncResetNtp < 3m) do={:return false}\r\\r
+    \n    :log warning \"\$0 The ntp client is configured, but did not sync.\"\\r
+    ;\r\\r
+    \n    :set IsTimeSyncResetNtp \$Uptime;\r\\r
+    \n    /system/ntp/client/set enabled=no;\r\\r
+    \n    :delay 20ms;\r\\r
+    \n    /system/ntp/client/set enabled=yes;\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :if ([ /system/license/get ]->\"level\" = \"free\" || \\\r\\r
+    \n       [ /system/resource/get ]->\"board-name\" = \"x86\") do={\r\\r
+    \n    :log debug \"\$0 No ntp client configured, relying on RTC for CHR fr\\r
+    ee license and x86.\";\r\\r
+    \n    :return true;\r\\r
+    \n  }\r\\r
+    \n  :if ([ /ip/cloud/get update-time ] = true) do={\r\\r
+    \n    :if ([ :typeof [ /ip/cloud/get public-address ] ] = \"ip\") do={\r\\r
+    \n      :set IsTimeSyncCached true;\r\\r
+    \n      :return true;\r\\r
+    \n    }\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :log debug \"\$0 No time source configured! Returning gracefully...\";\\r
+    \r\\r
+    \n  :return true;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# read parts of a large file\r\\r
+    \n:set FetchLargeFiles do={\r\\r
+    \n  :local ScriptName [:tostr \$1];\r\\r
+    \n  :local fetchUrl [:tostr \$2];\r\\r
+    \n  :local CheckCert [:tostr \$3];\r\\r
+    \n  :local fetchMode [:tostr \$4];\r\\r
+    \n  :local fetchMethod [:tostr \$5];\r\\r
+    \n  :local FetchString \"undefined\";\r\\r
+    \n \r\\r
+    \n  :global CleanName;\r\\r
+    \n  :global FetchUserAgentStr;\r\\r
+    \n  :global GetRandom20CharAlNum;\r\\r
+    \n  :global IfThenElse;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :global MkDir;\r\\r
+    \n  :global RmDir;\r\\r
+    \n  :global RmFile;\r\\r
+    \n  :global WaitForFile;\r\\r
+    \n\r\\r
+    \n  :set CheckCert [ \$IfThenElse (\$CheckCert = \"false\") \"no\" \"yes-w\\r
+    ithout-crl\" ];\r\\r
+    \n  #:set fetchMode [ \$IfThenElse (\$fetchMode != \"false\") [:tostr (\"m\\r
+    ode=\" . \$fetchMode)] ];\r\\r
+    \n  #:set fetchMethod [\$IfThenElse (\$fetchMethod != \"false\") [:tostr (\\r
+    \"http-method=\\\"\" . \$fetchMethod . \"\\\"\") ]];\r\\r
+    \n  \r\\r
+    \n  :local DirName (\"tmpfs/\" . [ \$CleanName \$ScriptName ]);\r\\r
+    \n  :if ([ \$MkDir \$DirName ] = false) do={\r\\r
+    \n    \$LogPrint error \$0 (\"Failed creating directory!\");\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :local FileName (\$DirName . \"/\" . [ \$CleanName \$0 ] . \"-\" . [ \\r
+    \$GetRandom20CharAlNum ]);\r\\r
+    \n  #/tool/fetch check-certificate=\$CheckCert \$Url dst-path=\$FileName h\\r
+    ttp-header-field=({ [ \$FetchUserAgentStr \$ScriptName ] }) as-value;\r\\r
+    \n  #:log warning (\"\\\$fUrl =\" . \$2 . ({[ \$fMode ]}));\r\\r
+    \n    :onerror Err {\r\\r
+    \n      :set FetchString (\"/tool/fetch \" . \\\r\\r
+    \n      [\$IfThenElse ([\$fetchMethod] != \"false\") (\"http-method=\\\"\"\\r
+    \_. \$fetchMethod . \"\\\" \")] . \\\r\\r
+    \n      \"check-certificate=\" . \$CheckCert . \" url=(\\\"\" . \$fetchUrl\\r
+    \_. \"\\\") \" . \\\r\\r
+    \n      [\$IfThenElse ([\$fetchMode] != \"false\") (\"mode=\" . \$fetchMod\\r
+    e . \" \")] . \\\r\\r
+    \n      http-header-field=({ [ \$FetchUserAgentStr \$ScriptName ] }) as-va\\r
+    lue);\r\\r
+    \n      :log warning (\"\\\$FetchSring = \" . \$FetchString);\r\\r
+    \n      :put [\$FetchString];\r\\r
+    \n    #:put [/tool/fetch \$fetchMode check-certificate=\$CheckCert url=(\$\\r
+    fetchUrl) dst-path=(\$FileName) http-header-field=({ [ \$FetchUserAgentStr\\r
+    \_\$ScriptName ] }) as-value];\r\\r
+    \n  } do={\r\\r
+    \n    :if ([ \$WaitForFile \$FileName 500ms ] = true) do={\r\\r
+    \n      \$RmFile \$FileName;\r\\r
+    \n    }\r\\r
+    \n    \$LogPrint debug \$0 (\"Failed downloading from \" . \$fetchUrl . \"\\r
+    \_- \" . \$Err);\r\\r
+    \n    \$RmDir \$DirName;\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :if ([ \$WaitForFile \$FileName 5s ] = false) do={\r\\r
+    \n    \$LogPrint debug \$0 (\"The file downloaded from \" . \$fetchUrl . \\r
+    \" did not show up.\");\r\\r
+    \n    :return false;\r\\r
+    \n  }\r\\r
+    \n  :local FileSize [ /file/get \$FileName size ];\r\\r
+    \n  :local Return \"\";\r\\r
+    \n  :local VarSize 0;\r\\r
+    \n  :while (\$VarSize != \$FileSize) do={\r\\r
+    \n    :set Return (\$Return . ([ /file/read offset=\$VarSize chunk-size=32\\r
+    768 file=\$FileName as-value ]->\"data\"));\r\\r
+    \n    :set FileSize [ /file/get \$FileName size ];\r\\r
+    \n    :set VarSize [ :len \$Return ];\r\\r
+    \n    :if (\$VarSize > \$FileSize) do={\r\\r
+    \n      :delay 100ms;\r\\r
+    \n    }\r\\r
+    \n  }\r\\r
+    \n  \$RmDir \$DirName;\r\\r
+    \n  :return \$Return;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Global Environment clear. Use: \"\$GlobalEnvRemove True;\".\r\\r
+    \n:set GlobalEnvRemove do={\r\\r
+    \n  :local doRmEnv [ :tostr \$1 ];\r\\r
+    \n  :global GlobalScriptsUrl;\r\\r
+    \n  :local ScriptsUrl;\r\\r
+    \n  :global LogPrint;\r\\r
+    \n  :if (\$doRmEnv != \"True\") do={\r\\r
+    \n     \$LogPrint error \"GlobalEnvRemove\" (\"This script is needed \\\"T\\r
+    rue\\\" for confirm to remove global environment variables!\");\r\\r
+    \n     :return [];\r\\r
+    \n     :error true;  \r\\r
+    \n  } else={\r\\r
+    \n     :set ScriptsUrl \$GlobalScriptsUrl;\r\\r
+    \n     :delay 5;\r\\r
+    \n     :foreach var in=[/system/script/environment print as-value] do={/sy\\r
+    stem/script/environment remove (\$var->\".id\")}\r\\r
+    \n     :delay 5;\r\\r
+    \n     :global GlobalScriptsUrl \$ScriptsUrl;\r\\r
+    \n     \$LogPrint warning \"GlobalEnvRemove\" (\"Done!\");\r\\r
+    \n     :return [];\r\\r
+    \n     :error false;\r\\r
+    \n  }\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n# Add and fix global scheduler\r\\r
+    \n:put \"Add or/and fix Global scheduler...\";\r\\r
+    \n:local OnEvent \"/system/script { run AM-GlobalConfig; run AM-GlobalFunc\\r
+    ; }\";\r\\r
+    \n:local Comment \"Setup Global Environment for scripts\";\r\\r
+    \n:if ([ :len [ /system/scheduler/find where name=\"AM-SetGlobalEnv\" ] ] \\r
+    = 0) do={\r\\r
+    \n  /system/scheduler/add name=\"AM-SetGlobalEnv\" comment=\$Comment on-ev\\r
+    ent=\$OnEvent start-time=startup;\r\\r
+    \n}\r\\r
+    \n:if ([ /system/scheduler/get \"AM-SetGlobalEnv\" comment ] != \$Comment)\\r
+    \_do={\r\\r
+    \n  /system/scheduler/set \"AM-SetGlobalEnv\" comment=\$Comment;\r\\r
+    \n}\r\\r
+    \n:if ([ /system/scheduler/get \"AM-SetGlobalEnv\" on-event ] != \$OnEvent\\r
+    ) do={\r\\r
+    \n  /system/scheduler/set \"AM-SetGlobalEnv\" on-event=\$OnEvent;\r\\r
+    \n}\r\\r
+    \n# Add Update Script scheduler\r\\r
+    \n:put \"Add or/and fix Update Script scheduler\";\r\\r
+    \n:set OnEvent \":global ScriptInstallUpdate; \\\$ScriptInstallUpdate;\";\\r
+    \r\\r
+    \n:set Comment \"Every Day Check For Update Scripts\";\r\\r
+    \n:if ([ :len [ /system/scheduler/find where name=\"AM-ScriptInstallUpdate\\r
+    \" ] ] = 0) do={\r\\r
+    \n/system/scheduler/add name=\"AM-ScriptInstallUpdate\" comment=\$Comment \\r
+    start-time=startup interval=1d on-event=\$OnEvent;\r\\r
+    \n}\r\\r
+    \n\r\\r
+    \n#:local Resource [ /system/resource/get ];\r\\r
+    \n#:log info (\$ScriptName . \" Loaded on \" . \$Resource->\"board-name\" \\r
+    . \" with RouterOS \" . \$Resource->\"version\" . \" and Architecture \" .\\r
+    \".\");\r\\r
+    \n\r\\r
+    \n:onerror Err {\r\\r
+    \n  :global GlobalConfReady;\r\\r
+    \n  :retry { :if (\$GlobalConfReady != true) do={ :error (\"Global configs\\r
+    \_not ready.\"); }; } delay=100ms max=5;\r\\r
+    \n\r\\r
+    \n# signal we are ready\r\\r
+    \n:set GlobalFuncReady true;\r\\r
+    \n:set ExitOK true;\r\\r
+    \n:log warning (\"This script \$ScriptName Loaded on \" . \$devBoardName .\\r
+    \_\"\\nRouterOS: \" . \$devCurVersion . \"\\nArchitecture: \" . \$devCurAr\\r
+    ch . \"\\nIdentity: \" . \$Identity);\r\\r
+    \n} do={:global ExitOnError; \$ExitOnError \$0 \$Err;}\r\\r
+    \n\r\\r
+    \n#} do={:global ExitError; \$ExitError \$ExitOK [ :jobname ] \$Err}\r\\r
+    \n# log the successful load of the script, or an error if it failed\r\\r
+    \n#:if ([\$GlobalFuncReady] = true && [\$GlobalConfReady] = true) do={\r\\r
+    \n"\r
+/tool e-mail\r
+set certificate-verification=no from=MikroYellow<vadossio@icloud.com> port=\\r
+    587 server=smtp.mail.me.com tls=starttls user=vadossio@icloud.com\r
diff --git a/MikroYellow/history/20260312/20260312113134-Diff-Config.rsc b/MikroYellow/history/20260312/20260312113134-Diff-Config.rsc
new file mode 100644 (file)
index 0000000..e69de29