shithub: chessfs

ref: e82dcee1a3d54f14c93a19f8fe21965ea72c56ce
dir: /chessfs.go/

View raw version
package main

import (
	"flag"
	"log"
	"os"
	"path"
	"fmt"

	"aqwari.net/net/styx"
)

var (
	addr	= flag.String("a", ":5650", "Binding address")
	debug	= flag.Bool("D", false, "trace 9P messages")
	verbose	= flag.Bool("v", false, "verbose")
)

var logrequests styx.HandlerFunc = func(s *styx.Session) {
	for s.Next() {
		log.Printf("%q %T %s", s.User, s.Request(), s.Request().Path())
	}
}

type ChessServer struct {
	uid		string
	gid		string
	board	*Board
}

func (c *ChessServer) Serve9P(s *styx.Session) {
	c.uid = s.User
	c.gid = s.User

	for s.Next() {
		request := s.Request()

		var file os.FileInfo
		var err error
		switch(path.Base(request.Path())) {
		case "/":
			file = NewChessRootDir(c.board, c.uid, c.gid)
		case "ctl":
			file = &ChessControlFile {
				board:	c.board,
				uid:	c.uid,
				gid:	c.gid,
			}
		case "board":
			file = &BoardFile {
				board:	c.board,
				uid:	c.uid,
				gid:	c.gid,
			}
		case "status":
			file = &ChessStatusFile {
				board:	c.board,
				uid:	c.uid,
				gid:	c.gid,
			}
		case "notify":
			file = &ChessNotifyFile {
				board:	c.board,
				uid:	c.uid,
				gid:	c.gid,
			}
		case "history":
			file = &GameHistory {
				board:	c.board,
				uid:	c.uid,
				gid:	c.gid,
			}
		default:
			err = fmt.Errorf("%s does not exist", request.Path())
		}

		switch t := request.(type) {
			case styx.Tstat:
				t.Rstat(file, err)
			case styx.Twalk:
				t.Rwalk(file, err)
			case styx.Topen:
				t.Ropen(file, err)
		}
	}
}

// Entrypoint
func main() {
	flag.Parse()

	log.SetPrefix("")
	log.SetFlags(0)

	if flag.NArg() != 0 {
		flag.Usage()
		os.Exit(2)
	}

	var board Board = NewBoard()
	var srv styx.Server
	var chessServer ChessServer = ChessServer {
		board: &board,
	}

	if *verbose {
		srv.ErrorLog = log.New(os.Stderr, "[DEBUG] ", 0)
	}
	if *debug {
		srv.TraceLog = log.New(os.Stderr, "[TRACE] ", 0)
	}

	srv.Addr = *addr
	srv.Handler = styx.Stack(logrequests, &chessServer)

	log.Fatal(srv.ListenAndServe())
}