summaryrefslogtreecommitdiff
path: root/api/backups/backups.go
blob: d389582719db84054884825188747602c7b8b976 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package backups

import (
	"log"
	"net/http"
	"time"

	"git.simponic.xyz/simponic/backup-notify/api/types"
	"git.simponic.xyz/simponic/backup-notify/database"
)

func getHostStatusOverTime(backups []database.Backup) map[string][]bool {
	hostnameBackups := make(map[string][]database.Backup)
	statusOverTime := make(map[string][]bool)

	if len(backups) == 0 {
		return statusOverTime
	}

	firstReceivedBackup := backups[0].ReceivedOn
	for _, backup := range backups {
		if backup.ReceivedOn.Before(firstReceivedBackup) {
			firstReceivedBackup = backup.ReceivedOn
		}

		if _, ok := hostnameBackups[backup.Hostname]; !ok {
			hostnameBackups[backup.Hostname] = []database.Backup{}
		}
		hostnameBackups[backup.Hostname] = append(hostnameBackups[backup.Hostname], backup)
	}

	daysSinceFirstBackup := int(time.Since(firstReceivedBackup).Hours()/24) + 1

	for hostname := range hostnameBackups {
		statusOverTime[hostname] = make([]bool, daysSinceFirstBackup)
		for _, backup := range hostnameBackups[hostname] {
			dayReceivedOn := int(time.Since(backup.ReceivedOn).Hours() / 24)
			statusOverTime[hostname][dayReceivedOn] = true
		}
	}

	return statusOverTime
}

func ListBackupsContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
	return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
		backups, err := database.ListBackups(context.DBConn)
		if err != nil {
			log.Println(err)
			resp.WriteHeader(http.StatusInternalServerError)
			return failure(context, req, resp)
		}

		hostStatusOverTime := getHostStatusOverTime(backups)
		(*context.TemplateData)["HostStatusOverTime"] = hostStatusOverTime
		return success(context, req, resp)
	}
}