aboutsummaryrefslogtreecommitdiffstats
path: root/src/vpp-api/lua/examples/lute/lute.lua
blob: 89b9924b9016a4c2c33922fe352c97aa7913e699 (plain) .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
# -*- coding: utf8 -*-
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.

import sys
import time

import zmq
from zmq import ZMQError, strerror, Again, ContextTerminated
from zmq.tests import BaseZMQTestCase

if sys.version_info[0] >= 3:
    long = int

class TestZMQError(BaseZMQTestCase):
    
    def test_strerror(self):
        """test that strerror gets the right type."""
        for i in range(10):
            e = strerror(i)
            self.assertTrue(isinstance(e, str))
    
    def test_zmqerror(self):
        for errno in range(10):
            e = ZMQError(errno)
            self.assertEqual(e.errno, errno)
            self.assertEqual(str(e), strerror(errno))
    
    def test_again(self):
        s = self.context.socket(zmq.REP)
        self.assertRaises(Again, s.recv, zmq.NOBLOCK)
        self.assertRaisesErrno(zmq.EAGAIN, s.recv, zmq.NOBLOCK)
        s.close()
    
    def atest_ctxterm(self):
        s = self.context.socket(zmq.REP)
        t = Thread(target=self.context.term)
        t.start()
        self.assertRaises(ContextTerminated, s.recv, zmq.NOBLOCK)
        self.assertRaisesErrno(zmq.TERM, s.recv, zmq.NOBLOCK)
        s.close()
        t.join()
'#n372'>372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
--[[
version = 1
/*
 * Copyright (c) 2016 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
]]

-- LUTE: Lua Unit Test Environment
-- AKA what happens when screen tries to marry with lua and expect,
-- but escapes mid-ceremony.
--
-- comments: @ayourtch

ffi = require("ffi")

vpp = {}
function vpp.dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. vpp.dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end


ffi.cdef([[

int posix_openpt(int flags);
int grantpt(int fd);
int unlockpt(int fd);
char *ptsname(int fd);

typedef long pid_t;
typedef long ssize_t;
typedef long size_t;
typedef int nfds_t;
typedef long time_t;
typedef long suseconds_t;

pid_t fork(void);
pid_t setsid(void);

int close(int fd);
int open(char *pathname, int flags);

int dup2(int oldfd, int newfd);

ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);

struct pollfd {
               int   fd;         /* file descriptor */
               short events;     /* requested events */
               short revents;    /* returned events */
           };

int poll(struct pollfd *fds, nfds_t nfds, int timeout);

struct timeval {
               time_t      tv_sec;     /* seconds */
               suseconds_t tv_usec;    /* microseconds */
           };

int gettimeofday(struct timeval *tv, struct timezone *tz);

int inet_pton(int af, const char *src, void *dst);

]])

ffi.cdef([[
void *memset(void *s, int c, size_t n);
void *memcpy(void *dest, void *src, size_t n);
void *memmove(void *dest, const void *src, size_t n);
void *memmem(const void *haystack, size_t haystacklen,
        const void *needle, size_t needlelen);
]])



local O_RDWR = 2


function os_time()
  local tv = ffi.new("struct timeval[1]")
  local ret = ffi.C.gettimeofday(tv, nil)
  return tonumber(tv[0].tv_sec) + (tonumber(tv[0].tv_usec)/1000000.0)
end

function sleep(n)
  local when_wakeup = os_time() + n
  while os_time() <= when_wakeup do
    ffi.C.poll(nil, 0, 10)
  end
end


function c_str(text_in)
  local text = text_in 
  local c_str = ffi.new("char[?]", #text+1)
  ffi.copy(c_str, text)
  return c_str
end

function ip46(addr_text)
  local out = ffi.new("char [200]")
  local AF_INET6 = 10
  local AF_INET = 2
  local is_ip6 = ffi.C.inet_pton(AF_INET6, c_str(addr_text), out)
  if is_ip6 == 1 then
    return ffi.string(out, 16), true
  end
  local is_ip4 = ffi.C.inet_pton(AF_INET, c_str(addr_text), out)
  if is_ip4 then
    return (string.rep("4", 12).. ffi.string(out, 4)), false
  end
end

function pty_master_open()
  local fd = ffi.C.posix_openpt(O_RDWR)
  ffi.C.grantpt(fd)
  ffi.C.unlockpt(fd)
  local p = ffi.C.ptsname(fd)
  print("PTS:" .. ffi.string(p))
  return fd, ffi.string(p)
end

function pty_run(cmd)
  local master_fd, pts_name = pty_master_open()
  local child_pid = ffi.C.fork()
  if (child_pid == -1) then
    print("Error fork()ing")
    return -1
  end 
 
  if child_pid ~= 0 then
    -- print("Parent")
    return master_fd, child_pid
  end

  -- print("Child")
  if (ffi.C.setsid() == -1) then
    print("Child error setsid")
    os.exit(-1)
  end

  ffi.C.close(master_fd)

  local slave_fd = ffi.C.open(c_str(pts_name), O_RDWR)
  if slave_fd == -1 then
    print("Child can not open slave fd")
    os.exit(-2)
  end

  ffi.C.dup2(slave_fd, 0)
  ffi.C.dup2(slave_fd, 1)
  ffi.C.dup2(slave_fd, 2)
  os.execute(cmd)
end

function readch()
  local buf = ffi.new("char[1]")
  local nread= ffi.C.read(0, buf, 1)
  -- print("\nREADCH : " .. string.char(buf[0]))
  return string.char(buf[0])
end

function stdout_write(str)
  ffi.C.write(1, c_str(str), #str)
end


readln = {
split = function(str, pat)
  local t = {}  -- NOTE: use {n = 0} in Lua-5.0
  local fpat = "(.-)" .. pat
  local last_end = 1
  if str then
    local s, e, cap = str:find(fpat, 1)
    while s do
      if s ~= 1 or cap ~= "" then
        table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
    end
    if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(t, cap)
    end
  end
  return t
end,

reader = function()
  local rl = {}

  rl.init = function()
    os.execute("stty -icanon min 1 -echo")
    rl.rawmode = true
  end

  rl.done = function()
    os.execute("stty icanon echo")
    rl.rawmode = false
  end

  rl.prompt = ">"
  rl.history = { "" }
  rl.history_index = 1
  rl.history_length = 1

  rl.hide_cmd = function()
    local bs = string.char(8) .. " " .. string.char(8)
    for i = 1, #rl.command do
      stdout_write(bs)
    end
  end

  rl.show_cmd = function()
    if rl.command then
      stdout_write(rl.command)
    end
  end

  rl.store_history = function(cmd)
    if cmd == "" then
      return
    end
    rl.history[rl.history_length] = cmd
    rl.history_length = rl.history_length + 1
    rl.history_index = rl.history_length
    rl.history[rl.history_length] = ""
  end

  rl.readln = function(stdin_select_fn, batch_cmd, batch_when, batch_expect)
    local done = false
    local need_prompt = true
    rl.command = ""

    if not rl.rawmode then
      rl.init()
    end

    while not done do
      local indent_value = #rl.prompt + #rl.command
      if need_prompt then
        stdout_write(rl.prompt)
        stdout_write(rl.command)
        need_prompt = false
      end
      if type(stdin_select_fn) == "function" then
        while not stdin_select_fn(indent_value, batch_cmd, batch_when, batch_expect) do
          stdout_write(rl.prompt)
          stdout_write(rl.command)
          indent_value = #rl.prompt + #rl.command
        end
        if batch_cmd and ((os_time() > batch_when) or (batch_expect and expect_success(batch_expect, buf, 0))) then
          stdout_write("\n" .. rl.prompt .. batch_cmd .. "\n")
          if batch_expect then
            expect_done(batch_expect)
          end
          return batch_cmd, batch_expect
        end
      end
      local ch = readch()
      if ch:byte(1) == 27 then
        -- CONTROL
        local ch2 = readch()
        -- arrows
        if ch2:byte(1) == 91 then
          local ch3 = readch()
          local b = ch3:byte(1)
          if b == 65 then
            ch = "UP"
          elseif b == 66 then
            ch = "DOWN"
          elseif b == 67 then
            ch = "RIGHT"
          elseif b == 68 then
            ch = "LEFT"
          end
          -- print("Byte: " .. ch3:byte(1))
          -- if ch3:byte(1)
        end
      end

      if ch == "?" then
        stdout_write(ch)
        stdout_write("\n")
        if rl.help then
          rl.help(rl)
        end
        need_prompt = true
      elseif ch == "\t" then
        if rl.tab_complete then
          rl.tab_complete(rl)
        end
        stdout_write("\n")
        need_prompt = true
      elseif ch == "\n" then
        stdout_write(ch)
        done = true
      elseif ch == "\004" then
        stdout_write("\n")
        rl.command = nil
        done = true
      elseif ch == string.char(127) then
        if rl.command ~= "" then
          stdout_write(string.char(8) .. " " .. string.char(8))
          rl.command = string.sub(rl.command, 1, -2)
        end
      elseif #ch > 1 then
        -- control char
        if ch == "UP" then
          rl.hide_cmd()
          if rl.history_index == #rl.history then
            rl.history[rl.history_index] = rl.command
          end
          if rl.history_index > 1 then
            rl.history_index = rl.history_index - 1
            rl.command = rl.history[rl.history_index]
          end
          rl.show_cmd()
        elseif ch == "DOWN" then
          rl.hide_cmd()
          if rl.history_index < rl.history_length then
            rl.history_index = rl.history_index + 1
            rl.command = rl.history[rl.history_index]
          end
          rl.show_cmd()
        end
      else
        stdout_write(ch)
        rl.command = rl.command .. ch
      end
    end
    if rl.command then
      rl.store_history(rl.command)
    end
    return rl.command
  end
  return rl
end

}

local select_fds = {}
local sessions = {}

local line_erased = false

function erase_line(indent)
  if not line_erased then
    line_erased = true
    stdout_write(string.rep(string.char(8), indent)..string.rep(" ", indent)..string.rep(string.char(8), indent))
  end
end

function do_select_stdin(indent, batch_cmd, batch_when, batch_expect)
  while true do
    local nfds = 1+#select_fds
    local pfds = ffi.new("struct pollfd[?]", nfds)
    pfds[0].fd = 0;
    pfds[0].events = 1;
    pfds[0].revents = 0;
    for i = 1,#select_fds do
      pfds[i].fd = select_fds[i].fd
      pfds[i].events = 1
      pfds[i].revents = 0
    end
    if batch_cmd and ((os_time() > batch_when) or (batch_expect and expect_success(batch_expect, buf, 0))) then
      return true
    end
    while ffi.C.poll(pfds, nfds, 10) == 0 do
      if batch_cmd and ((os_time() > batch_when) or (batch_expect and expect_success(batch_expect, buf, 0))) then
        return true
      end
      if line_erased then
        line_erased = false
        return false
      end
    end
    if pfds[0].revents == 1 then
      return true
    end
    for i = 1,#select_fds do
      if(pfds[i].revents > 0) then
        if pfds[i].fd ~= select_fds[i].fd then
          print("File descriptors unequal", pfds[i].fd, select_fds[i].fd)
        end
        select_fds[i].cb(select_fds[i], pfds[i].revents, indent)
      end
    end
  end
end

local buf = ffi.new("char [32768]")

function session_stdout_write(prefix, data)
  data = prefix .. data:gsub("\n", "\n"..prefix):gsub("\n"..prefix.."$", "\n")
  
  stdout_write(data)
end

function expect_success(sok, buf, nread)
  local expect_buf_sz = ffi.sizeof(sok.expect_buf) - 128
  local expect_buf_avail = expect_buf_sz - sok.expect_buf_idx
  -- print("EXPECT_SUCCESS: nread ".. tostring(nread).. " expect_buf_idx: " .. tostring(sok.expect_buf_idx) .. " expect_buf_avail: " .. tostring(expect_buf_avail) )
  if expect_buf_avail < 0 then
    print "EXPECT BUFFER OVERRUN ALREADY"
    os.exit(1)
  end
  if expect_buf_avail < nread then
    if (nread >= ffi.sizeof(sok.expect_buf)) then
      print("Read too large of a chunk to fit into expect buffer")
      return nil
    end
    local delta = nread - expect_buf_avail

    ffi.C.memmove(sok.expect_buf, sok.expect_buf + delta, expect_buf_sz - delta)
    sok.expect_buf_idx = sok.expect_buf_idx - delta
    expect_buf_avail = nread 
  end
  if sok.expect_buf_idx + nread > expect_buf_sz then
    print("ERROR, I have just overrun the buffer !")
    os.exit(1)
  end
  ffi.C.memcpy(sok.expect_buf + sok.expect_buf_idx, buf, nread)
  sok.expect_buf_idx = sok.expect_buf_idx + nread
  if sok.expect_str == nil then
    return true
  end
  local match_p = ffi.C.memmem(sok.expect_buf, sok.expect_buf_idx, sok.expect_str, sok.expect_str_len)
  if match_p ~= nil then
    return true
  end
  return false
end

function expect_done(sok)
  local expect_buf_sz = ffi.sizeof(sok.expect_buf) - 128
  if not sok.expect_str then 
    return false
  end
  local match_p = ffi.C.memmem(sok.expect_buf, sok.expect_buf_idx, sok.expect_str, sok.expect_str_len)
  if match_p ~= nil then
    if sok.expect_cb then
      sok.expect_cb(sok)
    end
    local match_idx = ffi.cast("char *", match_p) - ffi.cast("char *", sok.expect_buf)
    ffi.C.memmove(sok.expect_buf, ffi.cast("char *", match_p) + sok.expect_str_len, expect_buf_sz - match_idx - sok.expect_str_len)
    sok.expect_buf_idx = match_idx + sok.expect_str_len
    sok.expect_success = true

    sok.expect_str = nil
    sok.expect_str_len = 0
    return true
  end
end

function slave_events(sok, revents, indent)
  local fd = sok.fd
  local nread = ffi.C.read(fd, buf, ffi.sizeof(buf)-128)
  local idx = nread - 1
  while idx >= 0 and buf[idx] ~= 10 do
    idx = idx - 1
  end
  if idx >= 0 then
    erase_line(indent)
    session_stdout_write(sok.prefix, sok.buf .. ffi.string(buf, idx+1))
    sok.buf = ""
  end
  sok.buf = sok.buf .. ffi.string(buf+idx+1, nread-idx-1)
  -- print("\nRead: " .. tostring(nread))
  -- stdout_write(ffi.string(buf, nread))
  if expect_success(sok, buf, nread) then
    return true
  end
  return false
end


function start_session(name)
  local mfd, cpid = pty_run("/bin/bash")
  local sok =  { ["fd"] = mfd, ["cb"] = slave_events, ["buf"] = "", ["prefix"] = name .. ":", ["expect_buf"] = ffi.new("char [165536]"), ["expect_buf_idx"] = 0, ["expect_str"] = nil }
  table.insert(select_fds, sok)
  sessions[name] = sok
end

function command_transform(exe)
  if exe == "break" then
    exe = string.char(3)
  end
  return exe
end

function session_write(a_session, a_str)
  if has_session(a_session) then
    return tonumber(ffi.C.write(sessions[a_session].fd, c_str(a_str), #a_str))
  else
    return 0
  end
end

function session_exec(a_session, a_cmd)
  local exe = command_transform(a_cmd) .. "\n"
  session_write(a_session, exe)
end

function session_cmd(ui, a_session, a_cmd)
  if not has_session(a_session) then
    stdout_write("ERR: No such session '" .. tostring(a_session) .. "'\n")
    return nil
  end
  if a_session == "lua" then
    local func, msg = loadstring(ui.lua_acc .. a_cmd)
    -- stdout_write("LOADSTR: " .. vpp.dump({ ret, msg }) .. "\n")
    if not func and string.match(msg, "<eof>") then
      if a_session ~= ui.in_session then
         stdout_write("ERR LOADSTR: " .. tostring(msg) .. "\n")
         return nil
      end
      ui.lua_acc = ui.lua_acc .. a_cmd  .. "\n"
      return true
    end
    ui.lua_acc = ""
    local ret, msg = pcall(func)
    if ret then
      return true
    else
      stdout_write("ERR: " .. msg .. "\n") 
      return nil
    end
  else
    session_exec(a_session, a_cmd)
    if ui.session_cmd_delay then
      return { "delay", ui.session_cmd_delay }
    end
    return true
  end
end

function has_session(a_session)
  if a_session == "lua" then
    return true
  end
  return (sessions[a_session] ~= nil)
end

function command_match(list, input, output)
  for i, v in ipairs(list) do
    local m = {}
    m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] = string.match(input, v[1])
    -- print("MATCH: ", vpp.dump(m))
    if m[1] then
       output["result"] = m
       output["result_index"] = i
       return m
    end 
  end
  return nil
end

function cmd_spawn_shell(ui, a_arg)
  start_session(a_arg[1])
  return true
end

function cmd_run_cmd(ui, a_arg)
  local a_sess = a_arg[1]
  local a_cmd = a_arg[2]
  return session_cmd(ui, a_sess, a_cmd)
end

function cmd_cd(ui, a_arg)
  local a_sess = a_arg[1]
  if has_session(a_sess) then
    ui.in_session = a_sess
    return true
  else
    stdout_write("ERR: Unknown session '".. tostring(a_sess) .. "'\n")
    return nil
  end
end

function cmd_sleep(ui, a_arg)
  return { "delay", tonumber(a_arg[1]) }
end

function cmd_expect(ui, a_arg)
  local a_sess = a_arg[1]
  local a_expect = a_arg[2]
  local sok = sessions[a_sess]
  if not sok then
    stdout_write("ERR: unknown session '" .. tostring(a_sess) .. "'\n")
    return nil
  end
  sok.expect_str = c_str(a_expect)
  sok.expect_str_len = #a_expect
  return { "expect", a_sess }
end

function cmd_info(ui, a_arg)
  local a_sess = a_arg[1]
  local sok = sessions[a_sess]
  if not sok then
    stdout_write("ERR: unknown session '" .. tostring(a_sess) .. "'\n")
    return nil
  end
  print("Info for session " .. tostring(a_sess) .. "\n")
  print("Expect buffer index: " .. tostring(sok.expect_buf_idx))
  print("Expect buffer: '" .. tostring(ffi.string(sok.expect_buf, sok.expect_buf_idx)) .. "'\n")
  if sok.expect_str then
    print("Expect string: '" .. tostring(ffi.string(sok.expect_str, sok.expect_str_len)) .. "'\n")
  else
    print("Expect string not set\n")
  end
end

function cmd_echo(ui, a_arg)
  local a_data = a_arg[1]
  print("ECHO: " .. tostring(a_data))
end

main_command_table = {
  { "^shell ([a-zA-Z0-9_]+)$", cmd_spawn_shell },
  { "^run ([a-zA-Z0-9_]+) (.+)$", cmd_run_cmd },
  { "^cd ([a-zA-Z0-9_]+)$", cmd_cd  },
  { "^sleep ([0-9]+)$", cmd_sleep },
  { "^expect ([a-zA-Z0-9_]+) (.-)$", cmd_expect },
  { "^info ([a-zA-Z0-9_]+)$", cmd_info },
  { "^echo (.-)$", cmd_echo }
}



function ui_set_prompt(ui)
  if ui.in_session then 
    if ui.in_session == "lua" then
      if #ui.lua_acc > 0 then
        ui.r.prompt = ui.in_session .. ">>"
      else
        ui.r.prompt = ui.in_session .. ">"
      end 
    else
      ui.r.prompt = ui.in_session .. "> "
    end
  else
    ui.r.prompt = "> "
  end
  return ui.r.prompt
end

function ui_run_command(ui, cmd)
  -- stdout_write("Command: " .. tostring(cmd) .. "\n")
  local ret = false
  if ui.in_session then
    if cmd then
      if cmd == "^D^D^D" then
        ui.in_session = nil
        ret = true
      else
        ret = session_cmd(ui, ui.in_session, cmd)
      end
    else
      ui.in_session = nil
      ret = true
    end
  else  
    if cmd then
      local out = {}
      if cmd == "" then
        ret = true
      end
      if command_match(main_command_table, cmd, out) then
        local i = out.result_index
        local m = out.result
        if main_command_table[i][2] then
          ret = main_command_table[i][2](ui, m)
        end
      end
    end
    if not cmd or cmd == "quit" then
      return "quit"
    end
  end
  return ret
end

local ui = {}
ui.in_session = nil
ui.r = readln.reader() 
ui.lua_acc = ""
ui.session_cmd_delay = 0.3

local lines = ""

local done = false
-- a helper function which always returns nil
local no_next_line = function() return nil end

-- a function which returns the next batch line
local next_line = no_next_line

local batchfile = arg[1]

if batchfile then
  local f = io.lines(batchfile)
  next_line = function() 
    local line = f()
    if line then 
      return line
    else 
      next_line = no_next_line
      session_stdout_write(batchfile .. ":", "End of batch\n")
      return nil
    end
  end
end


local batch_when = 0
local batch_expect = nil
while not done do
  local prompt = ui_set_prompt(ui)
  local batch_cmd = next_line() 
  local cmd, expect_sok = ui.r.readln(do_select_stdin, batch_cmd, batch_when, batch_expect)
  if expect_sok and not expect_success(expect_sok, buf, 0) then
    if not cmd_ret and next_line ~= no_next_line then
      print("ERR: expect timeout\n")
      next_line = no_next_line
    end
  else 
    local cmd_ret = ui_run_command(ui, cmd)
    if not cmd_ret and next_line ~= no_next_line then
      print("ERR: Error during batch execution\n")
      next_line = no_next_line
    end

    if cmd_ret  == "quit" then
      done = true
    end
    batch_expect = nil
    batch_when = 0
    if type(cmd_ret) == "table" then
      if cmd_ret[1] == "delay" then
	batch_when = os_time() + tonumber(cmd_ret[2])
      end
      if cmd_ret[1] == "expect" then
	batch_expect = sessions[cmd_ret[2]]
	batch_when = os_time() + 15
      end
    end
  end
end
ui.r.done()

os.exit(1)