summary refs log tree commit diff
path: root/tools/blog_cli/main.go
blob: 76e4bde8efa459708a976f5d785523d4e343bb0e (plain) (blame)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// The tazblog CLI implements updating my blog records in DNS, see the
// README in this folder for details.
//
// The post input format is a file with the title on one line,
// followed by the date on a line, followed by an empty line, followed
// by the post text.
package main

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"time"

	"google.golang.org/api/dns/v1"
)

var (
	project = flag.String("project", "tazjins-infrastructure", "Target GCP project")
	zone    = flag.String("zone", "blog-tazj-in", "Target Cloud DNS zone")
	title   = flag.String("title", "", "Title of the blog post")
	infile  = flag.String("text", "", "Text file containing the blog post")
	id      = flag.String("id", "", "Post ID - will be generated if unset")
)

// Number of runes to include in a single chunk. If any chunks exceed
// the limit of what can be encoded, the chunk size is reduced and we
// try again.
var chunkSize = 200

type metadata struct {
	Chunks int       `json:"c"`
	Title  string    `json:"t"`
	Date   time.Time `json:"d"`
}

type chunk struct {
	Chunk int
	Text  string
}

type post struct {
	ID     string
	Meta   metadata
	Chunks []string
}

func (p *post) writeToDNS() error {
	var additions []*dns.ResourceRecordSet
	additions = append(additions, &dns.ResourceRecordSet{
		Name: fmt.Sprintf("_meta.%s.blog.tazj.in.", p.ID),
		Type: "TXT",
		Ttl:  1200,
		Rrdatas: []string{
			encodeJSON(p.Meta),
		},
	})

	for i, c := range p.Chunks {
		additions = append(additions, &dns.ResourceRecordSet{
			Name:    fmt.Sprintf("_%v.%s.blog.tazj.in.", i, p.ID),
			Type:    "TXT",
			Ttl:     1200,
			Rrdatas: []string{c},
		})
	}

	ctx := context.Background()
	dnsSvc, err := dns.NewService(ctx)
	if err != nil {
		return err
	}

	change := dns.Change{
		Additions: additions,
	}

	_, err = dnsSvc.Changes.Create(*project, *zone, &change).Do()
	if err != nil {
		return err
	}

	return nil
}

// Encode given value as JSON and base64-encode it.
func encodeJSON(v interface{}) string {
	outer, _ := json.Marshal(v)
	return base64.RawStdEncoding.EncodeToString(outer)
}

// Encode a chunk and check whether it is too large
func encodeChunk(c chunk) (string, bool) {
	tooLarge := false
	s := base64.RawStdEncoding.EncodeToString([]byte(c.Text))

	if len(s) >= 255 {
		tooLarge = true
	}

	return s, tooLarge
}

func createPost(id, title, text string, date time.Time) post {
	runes := []rune(text)
	n := 0
	tooLarge := false

	var chunks []string

	for chunkSize < len(runes) {
		c, l := encodeChunk(chunk{
			Chunk: n,
			Text:  string(runes[0:chunkSize:chunkSize]),
		})

		tooLarge = tooLarge || l
		chunks = append(chunks, c)
		runes = runes[chunkSize:]
		n++
	}

	if len(runes) > 0 {
		c, l := encodeChunk(chunk{
			Chunk: n,
			Text:  string(runes),
		})

		tooLarge = tooLarge || l
		chunks = append(chunks, c)
		n++
	}

	if tooLarge {
		log.Println("Too large at chunk size", chunkSize)
		chunkSize -= 5
		return createPost(id, title, text, date)
	}

	return post{
		ID: id,
		Meta: metadata{
			Chunks: n,
			Title:  title,
			Date:   date,
		},
		Chunks: chunks,
	}
}

func main() {
	flag.Parse()

	if *title == "" {
		log.Fatalln("Post title must be set (-title)")
	}

	if *infile == "" {
		log.Fatalln("Post text file must be set (-text)")
	}

	if *id == "" {
		log.Fatalln("Post ID must be set (-id)")
	}

	t, err := ioutil.ReadFile(*infile)
	if err != nil {
		log.Fatalln("Failed to read post:", err)
	}

	post := createPost(*id, *title, string(t), time.Now())

	log.Println("Writing post to DNS ...")
	err = post.writeToDNS()

	if err != nil {
		log.Fatalln("Failed to write post:", err)
	}

	log.Println("Successfully wrote entries")
}