aboutsummaryrefslogtreecommitdiffstats
path: root/lease-script.rsc
blob: 582f8ff5896e0b24638bf3c07011b837a3f012ca (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
58
59
60
61
62
63
64
#!rsc by RouterOS
# RouterOS script: lease-script
# Copyright (c) 2013-2024 Christian Hesse <mail@eworm.de>
# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
#
# requires RouterOS, version=7.12
#
# run scripts on DHCP lease
# https://git.eworm.de/cgit/routeros-scripts/about/doc/lease-script.md

:global GlobalFunctionsReady;
:while ($GlobalFunctionsReady != true) do={ :delay 500ms; }

:local Main do={
  :local ScriptName      [ :tostr $1 ];
  :local leaseActIP      [ :tostr $2 ];
  :local leaseActMAC     [ :tostr $2 ];
  :local leaseServerName [ :tostr $2 ];
  :local leaseBound      [ :tostr $2 ];

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

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

  $LogPrintExit2 debug $ScriptName ("DHCP Server " . $leaseServerName . " " . [ $IfThenElse ($leaseBound = 0) \
    "de" "" ] . "assigned lease " . $leaseActIP . " to " . $leaseActMAC) false;

  :if ([ $ScriptLock $ScriptName 10 ] = false) do={
    :return false;
  }

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

  :local RunOrder ({});
  :foreach Script in=[ /system/script/find where source~("\n# provides: lease-script\\b") ] do={
    :local ScriptVal [ /system/script/get $Script ];
    :local Store [ $ParseKeyValueStore [ $Grep ($ScriptVal->"source") ("\23 provides: lease-script, ") ] ];

    :set ($RunOrder->($Store->"order" . "-" . $ScriptVal->"name")) ($ScriptVal->"name");
  }

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

$Main [ :jobname ] $leaseActIP $leaseActMAC $leaseServerName $leaseBound;