1--input: keys: [],  values: [ namespace, channel_id ]
2--output: channel_hash {ttl, time_last_seen, subscribers, messages} or nil
3-- delete this channel and all its messages
4local ns = ARGV[1]
5local id = ARGV[2]
6local ch = ('%s{channel:%s}'):format(ns, id)
7local key_msg=    ch..':msg:%s' --not finished yet
8local key_channel=ch
9local messages=   ch..':messages'
10local subscribers=ch..':subscribers'
11local pubsub=     ch..':pubsub'
12
13redis.call('echo', ' ####### DELETE #######')
14local num_messages = 0
15--delete all the messages right now mister!
16local msg
17while true do
18  msg = redis.call('LPOP', messages)
19  if msg then
20    num_messages = num_messages + 1
21    redis.call('DEL', key_msg:format(msg))
22  else
23    break
24  end
25end
26
27local del_msgpack =cmsgpack.pack({"alert", "delete channel", id})
28for k,channel_key in pairs(redis.call('SMEMBERS', subscribers)) do
29  redis.call('PUBLISH', channel_key, del_msgpack)
30end
31
32local tohash=function(arr)
33  if type(arr)~="table" then
34    return nil
35  end
36  local h = {}
37  local k=nil
38  for i, v in ipairs(arr) do
39    if k == nil then
40      k=v
41    else
42      h[k]=v; k=nil
43    end
44  end
45  return h
46end
47
48local channel = nil
49if redis.call('EXISTS', key_channel) ~= 0 then
50  channel = tohash(redis.call('hgetall', key_channel))
51  --leave some crumbs behind showing this channel was just deleted
52  redis.call('setex', ch..":deleted", 5, 1)
53end
54
55redis.call('DEL', key_channel, messages, subscribers)
56redis.call('PUBLISH', pubsub, del_msgpack)
57
58if channel then
59  return {
60    tonumber(channel.ttl) or 0,
61    tonumber(channel.last_seen_fake_subscriber) or 0,
62    tonumber(channel.fake_subscribers or channel.subscribers) or 0,
63    channel.current_message or "",
64    tonumber(num_messages)
65  }
66else
67  return nil
68end
69