main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // This file is subject to a 1-clause BSD license.
  2. // Its contents can be found in the enclosed LICENSE file.
  3. package main
  4. import (
  5. "flag"
  6. "fmt"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "github.com/monkeybird/autimaat/app"
  11. "github.com/monkeybird/autimaat/irc"
  12. )
  13. func main() {
  14. // Parse command line arguments and load the bot profile.
  15. profile := parseArgs()
  16. // Write PID file. It may be needed by a process supervisor.
  17. writePid()
  18. // Create and run the bot.
  19. err := Run(profile)
  20. if err != nil {
  21. log.Fatal("[bot]", err)
  22. }
  23. }
  24. // writePid writes a file with process' pid. This is used by supervisors.
  25. // like systemd to track the process state.
  26. func writePid() {
  27. fd, err := os.Create("app.pid")
  28. if err != nil {
  29. log.Println("[bot] Create PID file:", err)
  30. return
  31. }
  32. fmt.Fprintf(fd, "%d", os.Getpid())
  33. fd.Close()
  34. }
  35. // parseArgs parses and validates command line arguments.
  36. func parseArgs() irc.Profile {
  37. flag.Usage = func() {
  38. fmt.Println("usage:", os.Args[0], "[options] <profile directory>")
  39. flag.PrintDefaults()
  40. }
  41. newconf := flag.Bool("new", false, "Create a new, default configuration file and exit.")
  42. version := flag.Bool("version", false, "Display version information.")
  43. flag.Parse()
  44. if *version {
  45. fmt.Println(app.Version())
  46. os.Exit(0)
  47. }
  48. if flag.NArg() == 0 {
  49. flag.Usage()
  50. os.Exit(1)
  51. }
  52. // Read and validate the profile root directory.
  53. root, err := filepath.Abs(flag.Arg(0))
  54. if err != nil {
  55. fmt.Fprintln(os.Stderr, err)
  56. os.Exit(1)
  57. }
  58. // Set root as current working directory.
  59. err = os.Chdir(root)
  60. if err != nil {
  61. fmt.Fprintln(os.Stderr, err)
  62. os.Exit(1)
  63. }
  64. // Create a new bot profile instance.
  65. profile := irc.NewProfile(root)
  66. // If applicable, save a new, default profile and exit.
  67. if *newconf {
  68. err := profile.Save()
  69. if err != nil {
  70. fmt.Fprintln(os.Stderr, err)
  71. os.Exit(1)
  72. }
  73. fmt.Println("New configuration saved.")
  74. fmt.Println("Please edit it and relaunch the program.")
  75. os.Exit(0)
  76. }
  77. // Load an existing profile.
  78. err = profile.Load()
  79. if err != nil {
  80. fmt.Fprintln(os.Stderr, err)
  81. os.Exit(1)
  82. }
  83. return profile
  84. }