aboutsummaryrefslogtreecommitdiffstats
path: root/lease-script
blob: 3134cb615a94fc8c5f0197270c17c8295dac00e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!rsc by RouterOS
# RouterOS script: lease-script
# Copyright (c) 2013-2021 Christian Hesse <mail@eworm.de>
# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
#
# run scripts on DHCP lease
# https://git.eworm.de/cgit/routeros-scripts/about/doc/lease-script.md

:local 0 "lease-script";
:global GlobalFunctionsReady;
:while ($GlobalFunctionsReady != true) do={ :delay 500ms; }

:global IfThenElse;
:global LogPrintExit2;
:global ParseKeyValueStore;
:global ScriptLock;

:if ([ :typeof $leaseActIP ] = "nothing" || \
     [ :typeof $leaseActMAC ] = "nothing" || \
     [ :typeof $leaseServerName ] = "nothing" || \
     [ :typeof $leaseBound ] = "nothing") do={
  $LogPrintExit2 error $0 ("This script is supposed to run from ip dhcp-server.") true;
}

$ScriptLock $0 false 10;

:if ([ :len [ / system script job find where script=$0 ] ] > 1) do={
  $LogPrintExit2 debug $0 ("More invocations are waiting, exiting early.") true;
}

:local State ([ $IfThenElse ($leaseBound = 0) "de" "" ] . "assign");
:local RunOrder [ :toarray "" ];

$LogPrintExit2 debug $0 ("DHCP Server " . $leaseServerName . " " . \
  $State . "ed lease " . $leaseActIP . " to " . $leaseActMAC) false;

:foreach Script in=[ / system script find where source~("\n# provides: lease-script, ") ] do={
  :local Name [ / system script get $Script name ];
  :local Store [ / system script get $Script source ];

  :set Store [ :pick $Store ([ :find $Store "\n# provides: lease-script, " ] + 27) [ :len $Store ] ];
  :set Store [ :pick $Store 0 [ :find $Store "\n" ] ];
  :set Store [ $ParseKeyValueStore $Store ];

  :if (($Store->$State) = true) do={
    :set ($RunOrder->($Store->"order")) $Name;
  }
}

:foreach Order,Script in=$RunOrder do={
  :do {
    $LogPrintExit2 debug $0 ("Running script with order " . $Order . ": " . $Script) false;
    / system script run $Script;
  } on-error={
    $LogPrintExit2 warning $0 ("Running script '" . $Script . "' failed!") false;
  }
}