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

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

while getopts 'hV' flag; do
	case "$flag" in
		h)
			usage
			help
			exit
			;;
		*)
			usage >&2
			exit 2
			;;
	esac
done

NAME='pb'

usage() {
  cat <<EOF
Missing argument <$1>.

Usage:
    $NAME <FULL_TITLE> [-|FILE [LANG]]

    Reads contents from [FILE], from stdin if '-' is given, and opens the
    editor on the content.

    Arguments:
      FULL_TITLE       Full title of the pastebin

Examples:
    $NAME 'My example pastebin title'
    $NAME 'My example pastebin title' file
    $NAME 'My example pastebin title' - < file
    cat file | $NAME 'My example pastebin title' -
    $NAME 'Title' file lang
    $NAME 'Title' - lang < file
    cat file | $NAME 'Title' - lang
EOF
}

FULL_TITLE="${1:-}"
[ -z "$FULL_TITLE" ] && {
  usage 'FULL_TITLE'
  exit 2
}

# Derived from:
# https://stackoverflow.com/questions/4009281/how-can-i-generate-url-slugs-in-perl/4009519#4009519
slugify() {
  echo "$1"                     | \
    tr '[:upper:]' '[:lower:]'  | \
    perl -ne 'tr/\000-\177//cd;
              s/[^\w\s-]//g;
              s/^\s+|\s+$//g;
              s/[-\s]+/-/g;
              print;'
}

SLUG_TITLE="$(slugify "$FULL_TITLE")"
PASTE_DATE="$(date -I)"
OUT="_pastebins/$PASTE_DATE-$SLUG_TITLE.md"
INPUT="${2:-}"
PL="${3:-FIXME}"
if [ -n "$INPUT" ]; then
  CONTENT=$(cat "$INPUT")
else
  CONTENT='FIXME'
fi


cd ~/dev/libre/website > /dev/null

[ -f "$OUT" ] && {
  echo "Pastebin named $OUT already exists."
  exit 1
}

FILE="$(mktemp)"
cat <<EOF > "$FILE"
---

title: ${FULL_TITLE}

date: ${PASTE_DATE}

layout: post

lang: en

ref: $SLUG_TITLE

---

\`\`\`$PL
$CONTENT
\`\`\`
EOF

if [ "$PL" = FIXME ]; then
	vipe < "$FILE" > "$OUT"
else
	cp "$FILE" "$OUT"
fi

git reset .
git add "$OUT"
git commit -m "pastebin: Auto-add $OUT"
make clean publish
URL="https://euandre.org/pastebin/$(echo "$PASTE_DATE" | tr '-' '/')/$SLUG_TITLE.html"
open "$URL"
printf "$URL" | xsel -ib
echo 'Opened on the browser and copied URL to clipboard.' >&2
cd - > /dev/null