summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
authorElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-04-21 18:46:40 -0700
committerElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-04-21 18:46:40 -0700
commitd14605d1388aaa7cc9ef1c230eae5ba14c9cef44 (patch)
tree59fcda0fae7899ca577eed1f72d89bff17d5ad5d /main.go
downloadbackup-notify-d14605d1388aaa7cc9ef1c230eae5ba14c9cef44.tar.gz
backup-notify-d14605d1388aaa7cc9ef1c230eae5ba14c9cef44.zip
initial commit
Diffstat (limited to 'main.go')
-rw-r--r--main.go96
1 files changed, 96 insertions, 0 deletions
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..b66bac6
--- /dev/null
+++ b/main.go
@@ -0,0 +1,96 @@
+package main
+
+import (
+ "encoding/json"
+ "log"
+
+ "git.simponic.xyz/simponic/backup-notify/api"
+ "git.simponic.xyz/simponic/backup-notify/args"
+ "git.simponic.xyz/simponic/backup-notify/database"
+ "git.simponic.xyz/simponic/backup-notify/ntfy"
+ "git.simponic.xyz/simponic/backup-notify/scheduler"
+ "github.com/joho/godotenv"
+)
+
+func main() {
+ log.SetFlags(log.LstdFlags | log.Lshortfile)
+
+ err := godotenv.Load()
+ if err != nil {
+ log.Println("could not load .env file:", err)
+ }
+
+ argv, err := args.GetArgs()
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ dbConn := database.MakeConn(&argv.DatabasePath)
+ defer dbConn.Close()
+
+ if argv.Migrate {
+ _, err = database.Migrate(dbConn)
+ if err != nil {
+ log.Fatal(err)
+ }
+ log.Println("database migrated successfully")
+ }
+
+ if argv.Scheduler {
+ scheduler.StartScheduler(dbConn)
+ }
+
+ if argv.NtfyEndpoint != "" {
+ ntfy := ntfy.MakeNtfyWatcher(argv.NtfyEndpoint, argv.NtfyTopics)
+ notifications := ntfy.Watch()
+
+ go func() {
+ for notification := range notifications {
+ // message type is a struct, so we can marshal it to JSON
+ message := notification.Text
+ messageStruct := struct {
+ Id string `json:"id"`
+ Time int `json:"time"`
+ Message string `json:"message"`
+ Event string `json:"event"`
+ }{}
+
+ err := json.Unmarshal([]byte(message), &messageStruct)
+ if err != nil {
+ log.Println("could not unmarshal message:", err)
+ continue
+ }
+
+ if messageStruct.Event == "keepalive" {
+ log.Println("received keepalive message")
+ continue
+ }
+
+ if messageStruct.Event != "message" {
+ log.Println("received unknown event:", messageStruct.Event)
+ continue
+ }
+
+ log.Println("received backup host:", messageStruct.Message)
+ err = database.ReceivedBackup(dbConn, messageStruct.Message)
+ if err != nil {
+ log.Println("could not record backup:", err)
+ }
+ }
+ }()
+ }
+
+ if argv.Server {
+ server := api.MakeServer(argv, dbConn)
+ log.Println("🚀🚀 API listening on port", argv.Port)
+
+ go func() {
+ err = server.ListenAndServe()
+ if err != nil {
+ log.Fatal(err)
+ }
+ }()
+ }
+
+ select {} // block forever
+}