aboutsummaryrefslogtreecommitdiff
path: root/bin/pb
blob: cb9ef89117e919eae70db1328f461a35fad856fa (about) (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
#!/bin/sh
set -eu


WEBSITE_DIR=~/dev/libre/website


usage() {
	cat <<-'EOF'
		Usage:
		  pb -t TITLE [-l LANGUAGE] [-s SLUG]
		  pg -h
	EOF
}

help() {
	cat <<-'EOF'

		Options:
		  -t TITLE       the title of the snippet
		  -l LANGUAGE    the programming language of the snippet
		  -s SLUG        the URL slug of the snippet

		Examples:

		  FIXME:

		    $ FIXME
	EOF
}


slugify() {
	iconv -ct ASCII//TRANSLIT |
		tr '[:upper:]' '[:lower:]' |
		sed -e 's/[^a-z0-9]/-/g' \
		    -e 's/--*/-/g'       \
		    -e 's/^-//'         \
		    -e 's/-$//'
}

prompt() {
	printf '%s [Y/n]: ' "$1"
	read -r yesno
	if [ "$yesno" = 'n' ] || [ "$yesno" = 'N' ]; then
		return 1
	else
		return 0
	fi
}

outname() {
	DATE=$1
	SLUG=$2
	N="${3:-0}"
	if [ "$N" = 0 ]; then
		SUFFIX=''
	else
		SUFFIX="-$N"
	fi
	F="_pastebins/$DATE-$SLUG$SUFFIX.md"
	if [ -e "$F" ]; then
		outname "$DATE" "$SLUG" $((N + 1))
	else
		# FIXME
		eval "SLUG=$SLUG$SUFFIX"
		printf '%s' "$F"
	fi
}

url() {
	DATE="$1"
	SLUG="$2"
	printf 'https://%s/pastebin/%s/%s.html' \
		"$(make -s fqdn)" \
		"$(echo "$DATE" | tr '-' '/')" \
		"$SLUG"
}


for flag in "$@"; do
	case "$flag" in
		--)
			break
			;;
		--help)
			usage
			help
			exit
			;;
		*)
			;;
	esac
done

while getopts 't:l:s:h' flag; do
	case "$flag" in
		t)
			TITLE="$OPTARG"
			;;
		l)
			LANGUAGE="$OPTARG"
			;;
		s)
			SLUG="$OPTARG"
			;;
		h)
			usage
			help
			exit
			;;
		*)
			usage >&2
			exit 2
			;;
	esac
done

assert_arg() {
	if [ -z "$1" ]; then
		{
			printf 'Missing %s.\n' "$2"
			printf '\n'
			usage
		} >&2
		exit 2
	fi
}

cd "$WEBSITE_DIR"

assert_arg "${TITLE:-}" '-t TITLE'
LANGUAGE="${LANGUAGE:-}"
DATE="$(date '+%Y-%m-%d')"
SLUG="${SLUG:-$(echo "$TITLE" | slugify)}"
OUT="$(outname "$DATE" "$SLUG")"
URL="$(url "$DATE" "$SLUG")"

trap "rm -f $OUT-tmp" EXIT
cat /dev/stdin <<-EOF | vipe > "$OUT-tmp"
	---

	title: $TITLE

	date: $DATE

	layout: post

	lang: en

	ref: $SLUG

	---

	\`\`\`$LANGUAGE
	$(cat)
	\`\`\`
EOF

exec 0</dev/tty
if ! prompt 'Proceed with publishing the snippet?'; then
	printf 'Aborted.\n' >&2
	exit
fi

mv "$OUT-tmp" "$OUT"
git reset .
git add "$OUT"
git commit -m "pastebin: Auto-add $OUT"
make deploy

open "$URL"
printf '%s' "$URL" | copy
printf 'Opened on the browser and copied URL to clipboard.\n' >&2