]> git.lizzy.rs Git - hydra-dragonfire.git/blob - hydra.go
Event system
[hydra-dragonfire.git] / hydra.go
1 package main
2
3 import (
4         _ "embed"
5         "github.com/yuin/gopher-lua"
6         "os"
7         "os/signal"
8         "syscall"
9         "time"
10 )
11
12 var lastTime = time.Now()
13 var signalChannel chan os.Signal
14
15 var serializeVer uint8 = 28
16 var protoVer uint16 = 39
17
18 //go:embed builtin/luax/init.lua
19 var builtinLuaX string
20
21 //go:embed builtin/vector.lua
22 var builtinVector string
23
24 //go:embed builtin/escapes.lua
25 var builtinEscapes string
26
27 //go:embed builtin/client.lua
28 var builtinClient string
29
30 //go:embed builtin/base64.lua
31 var builtinBase64 string
32
33 var builtinFiles = []string{
34         builtinLuaX,
35         builtinVector,
36         builtinEscapes,
37         builtinClient,
38         builtinBase64,
39 }
40
41 var hydraFuncs = map[string]lua.LGFunction{
42         "client": l_client,
43         "dtime":  l_dtime,
44         "poll":   l_poll,
45         "close":  l_close,
46 }
47
48 func l_dtime(l *lua.LState) int {
49         l.Push(lua.LNumber(time.Since(lastTime).Seconds()))
50         lastTime = time.Now()
51         return 1
52 }
53
54 func l_poll(l *lua.LState) int {
55         return doPoll(l, getClients(l))
56 }
57
58 func l_close(l *lua.LState) int {
59         for _, client := range getClients(l) {
60                 client.closeConn()
61         }
62
63         return 0
64 }
65
66 func main() {
67         if len(os.Args) < 2 {
68                 panic("missing filename")
69         }
70
71         signalChannel = make(chan os.Signal, 1)
72         signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
73
74         l := lua.NewState()
75         defer l.Close()
76
77         arg := l.NewTable()
78         for i, a := range os.Args {
79                 l.RawSetInt(arg, i-1, lua.LString(a))
80         }
81         l.SetGlobal("arg", arg)
82
83         hydra := l.SetFuncs(l.NewTable(), hydraFuncs)
84         l.SetField(hydra, "BS", lua.LNumber(10.0))
85         l.SetField(hydra, "serialize_ver", lua.LNumber(serializeVer))
86         l.SetField(hydra, "proto_ver", lua.LNumber(protoVer))
87         l.SetGlobal("hydra", hydra)
88
89         l.SetField(l.NewTypeMetatable("hydra.auth"), "__index", l.SetFuncs(l.NewTable(), authFuncs))
90         l.SetField(l.NewTypeMetatable("hydra.client"), "__index", l.NewFunction(l_client_index))
91         l.SetField(l.NewTypeMetatable("hydra.map"), "__index", l.SetFuncs(l.NewTable(), mapFuncs))
92         l.SetField(l.NewTypeMetatable("hydra.pkts"), "__index", l.SetFuncs(l.NewTable(), pktsFuncs))
93
94         for _, str := range builtinFiles {
95                 if err := l.DoString(str); err != nil {
96                         panic(err)
97                 }
98         }
99
100         if err := l.DoFile(os.Args[1]); err != nil {
101                 panic(err)
102         }
103 }