#!rsc
# RouterOS script: sms-forward
# Copyright (c) 2013-2019 Christian Hesse <mail@eworm.de>
#
# forward SMS to e-mail

:global Identity;

:global SendNotification;

# check mail server
:if ([ / tool netwatch get [ find where comment=[ / tool e-mail get address ] ] status ] != "up") do={
  :error "Mail server is not up.";
}

:local Allowed [ / tool sms get allowed-number ];
:local Secret [ / tool sms get secret ];

# forward SMS in a loop
:foreach Sms in=[ / tool sms inbox find ] do={
  :local Message   [ / tool sms inbox get $Sms message ];
  :local Phone     [ / tool sms inbox get $Sms phone ];
  :local TimeStamp [ / tool sms inbox get $Sms timestamp ];
  :local Type      [ / tool sms inbox get $Sms type ];

  :if ($Phone = $Allowed && $Message~("^:cmd " . $Secret . " script ")) do={
    :log debug "Ignoring SMS, which starts a script.";
  } else={
    $SendNotification ("SMS Forwarding") \
      ("A message was received by " . $Identity . ":\n\n" . \
        "Phone:     " . $Phone . "\n" . \
        "Timestamp: " . $TimeStamp . "\n" . \
        "Type:      " . $Type . "\n\n" . \
        "Message:\n" .  $Message);
    / tool sms inbox remove $Sms;
  }
}