added show option to display a note using a PAGER instead of an EDITOR.
[bash-notes.git] / notes.sh
1 #! /bin/bash
2
3 # bash-notes © 2023 by danix is licensed under CC BY-NC 4.0.
4 # To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/
5
6 # to debug the script run it like:
7 # DEBUG=true notes.sh ...
8 # and check /tmp/debug_bash-notes.log
9 if [[ $DEBUG == true ]]; then
10 exec 5> /tmp/debug_bash-notes.log
11 BASH_XTRACEFD="5"
12 PS4='$LINENO: '
13 set -x
14 fi
15
16 PID=$$
17 BASENAME=$( basename "$0" )
18 NOW=$(date +%s)
19
20 VERSION="0.3"
21 DBVERSION=${VERSION}_${NOW}
22
23 set_defaults() {
24 # Binaries to use
25 JQ=${JQ:-/usr/bin/jq}
26 EDITOR=${EDITOR:-/usr/bin/vim}
27 TERMINAL=${TERMINAL:-/usr/bin/alacritty}
28 # add options for your terminal. Remember to add the last option to execute
29 # your editor program, otherwise the script will fail.
30 # see example in the addnote function
31 TERM_OPTS="--class notes --title notes -e "
32 # Setting PAGER here overrides whatever is set in your default shell
33 # comment this option to use your default pager if set in your shell.
34 PAGER=${PAGER:-/usr/bin/more}
35
36 # set this to true to have output in plain text
37 # or use the -p option on the command line before every other option
38 PLAIN=false
39 # base directory for program files
40 BASEDIR=${BASEDIR:-~/.local/share/bash-notes}
41 # notes database in json format
42 DB=${BASEDIR}/db.json
43 # directory containing the actual notes
44 NOTESDIR=${BASEDIR}/notes
45
46 } # end set_defaults, do not change this line.
47
48 set_defaults
49
50 # Do not edit below this point
51 RCFILE=${RCFILE:-~/.config/bash-notes.rc}
52 TMPDB=/tmp/db.json
53
54 if [ ! -x "$JQ" ]; then
55 echo "jq not found in your PATH"
56 echo "install jq to continue"
57 exit 1
58 fi
59
60 # IMPORT USER DEFINED OPTIONS IF ANY
61 if [[ -f $RCFILE ]]; then
62 # shellcheck disable=SC1090
63 source "$RCFILE"
64 fi
65
66 # We prevent the program from running more than one instance:
67 PIDFILE=/var/tmp/$(basename "$0" .sh).pid
68
69 # Make sure the PID file is removed when we kill the process
70 trap 'rm -f $PIDFILE; exit 1' TERM INT
71
72 if [[ -r $PIDFILE ]]; then
73 # PIDFILE exists, so I guess there's already an instance running
74 # let's kill it and run again
75 # shellcheck disable=SC2046,SC2086
76 kill -s 15 $(cat $PIDFILE) > /dev/null 2>&1
77 # should already be deleted by trap, but just to be sure
78 rm "$PIDFILE"
79 fi
80
81 # create PIDFILE
82 echo $PID > "$PIDFILE"
83
84 # check if input is a number, returns false or the number itself
85 function check_noteID() {
86 IN=$1
87 case $IN in
88 ''|*[!0-9]*)
89 return 1
90 ;;
91 *)
92 echo "$IN"
93 ;;
94 esac
95 }
96
97 function helptext() {
98 echo "Usage:"
99 echo " $0 [PARAMS] ..."
100 echo ""
101 cat << __NOWCONF__
102 ${BASENAME} configuration is:
103
104 base directory: ${BASEDIR}/
105 notes archive: ${NOTESDIR}/
106 notes database: ${DB}
107 rc file: $RCFILE
108 debug file: /tmp/debug_bash-note.log
109
110 text editor: ${EDITOR}
111 terminal: ${TERMINAL}
112 jq executable: ${JQ}
113 __NOWCONF__
114
115 echo ""
116 echo "${BASENAME} parameters are:"
117 echo " -h | --help : This help text"
118 echo " -p | --plain : Output is in plain text"
119 echo " (without this option the output is formatted)"
120 echo " (this option must precede all others)"
121 echo " -l | --list : List existing notes"
122 echo " -a | --add [\"<title>\"] : Add new note"
123 echo " -e | --edit [<note>] : Edit note"
124 echo " -d | --delete [<note> | all] : Delete single note or all notes at once"
125 echo " -s | --show [<note>] : Display note using your favourite PAGER"
126 echo " -v | --version : Print version"
127 echo " --userconf : Export User config file"
128 echo ""
129 }
130
131 function addnote() {
132 # remove eventually existing temp DB file
133 if [[ -f $TMPDB ]]; then
134 rm $TMPDB
135 fi
136
137 NOTETITLE="$1"
138 echo "adding new note - \"$NOTETITLE\""
139 # shellcheck disable=SC2086
140 LASTID=$($JQ '.notes[-1].id // 0 | tonumber' $DB)
141 # [ "" == $LASTID ] && LASTID=0
142 NOTEID=$(( LASTID + 1 ))
143 # shellcheck disable=SC2086
144 touch ${NOTESDIR}/${NOW}
145 # shellcheck disable=SC2016
146 $JQ --arg i "$NOTEID" --arg t "$NOTETITLE" --arg f "$NOW" '.notes += [{"id": $i, "title": $t, "file": $f}]' "$DB" > $TMPDB
147 # shellcheck disable=SC2086
148 mv $TMPDB $DB
149 # example for alacritty:
150 # alacritty --class notes --title notes -e /usr/bin/vim ...
151 # shellcheck disable=SC2086,SC2091
152 $(${TERMINAL} ${TERM_OPTS} ${EDITOR} ${NOTESDIR}/${NOW})
153 }
154
155 function listnotes() {
156 # [ $PLAIN == true ] && echo "output is plain text" || echo "output is colored"
157 if [[ $(ls -A "$NOTESDIR") ]]; then
158 if [ $PLAIN == false ]; then
159 echo "listing all notes"
160 echo ""
161 fi
162 [ $PLAIN == false ] && echo "[ID] [TITLE] [CREATED]"
163 for i in "${NOTESDIR}"/*; do
164 # shellcheck disable=SC2155
165 local fname=$(basename $i)
166 DATE=$(date -d @${fname} +"%d/%m/%Y %R %z%Z")
167 # shellcheck disable=SC2016,SC2086
168 TITLE=$($JQ -r --arg z $(basename $i) '.notes[] | select(.file == $z) | .title' $DB)
169 # shellcheck disable=SC2016,SC2086
170 ID=$($JQ -r --arg z $(basename $i) '.notes[] | select(.file == $z) | .id' $DB)
171 [ $PLAIN == false ] && echo "[${ID}] ${TITLE} ${DATE}" || echo "${ID} - ${TITLE} - ${DATE}"
172 done
173 else
174 echo "no notes yet. You can add your first one with: ${BASENAME} -a \"your note title\""
175 fi
176 }
177
178 function editnote() {
179 NOTE=$1
180 # shellcheck disable=SC2155
181 local OK=$(check_noteID "$NOTE")
182 if [ ! "$OK" ]; then
183 echo "invalid note \"$NOTE\""
184 echo "Use the note ID that you can fetch after listing your notes"
185 exit 1
186 fi
187
188 # shellcheck disable=SC2016,SC2086
189 TITLE=$($JQ --arg i $OK '.notes[] | select(.id == $i) | .title' $DB)
190 # shellcheck disable=SC2016,SC2086
191 FILE=$($JQ -r --arg i $OK '.notes[] | select(.id == $i) | .file' $DB)
192 if [ "$TITLE" ]; then
193 echo "editing note $TITLE"
194 # shellcheck disable=SC2086,SC2091
195 $(${TERMINAL} ${TERM_OPTS} ${EDITOR} ${NOTESDIR}/${FILE})
196 else
197 echo "note not found"
198 exit 1
199 fi
200 }
201
202 function rmnote() {
203 # remove eventually existing temp DB file
204 if [[ -f $TMPDB ]]; then
205 rm $TMPDB
206 fi
207
208 NOTE=$1
209 if [ "all" == "$NOTE" ]; then
210 echo "You're going to delete all notes."
211 read -r -p "Do you wish to continue? (y/N) " ANSWER
212 case $ANSWER in
213 y|Y )
214 # shellcheck disable=SC2086
215 $JQ 'del(.notes[])' $DB > $TMPDB
216 # shellcheck disable=SC2086
217 mv $TMPDB $DB
218 # shellcheck disable=SC2086
219 rm $NOTESDIR/*
220 echo "Deleted all notes"
221 ;;
222 * )
223 echo "Aborting, no notes were deleted."
224 exit 1
225 ;;
226 esac
227 else
228 # shellcheck disable=SC2155
229 local OK=$(check_noteID "$NOTE")
230 if [ ! "$OK" ]; then
231 echo "invalid note \"$NOTE\""
232 echo "Use the note ID that you can fetch after listing your notes"
233 exit 1
234 fi
235
236 # shellcheck disable=SC2016,SC2086
237 TITLE=$($JQ --arg i $OK '.notes[] | select(.id == $i) | .title' $DB)
238 # shellcheck disable=SC2016,SC2086
239 FILE=$($JQ -r --arg i $OK '.notes[] | select(.id == $i) | .file' $DB)
240 if [ "$TITLE" ]; then
241 # shellcheck disable=SC2016,SC2086
242 $JQ -r --arg i $OK 'del(.notes[] | select(.id == $i))' $DB > $TMPDB
243 # shellcheck disable=SC2086
244 mv $TMPDB $DB
245 rm $NOTESDIR/$FILE
246 echo "Deleted note $TITLE"
247 else
248 echo "note not found"
249 exit 1
250 fi
251 fi
252 }
253
254 function shownote() {
255 NOTE=$1
256
257 # shellcheck disable=SC2155
258 local OK=$(check_noteID "$NOTE")
259 if [ ! "$OK" ]; then
260 echo "invalid note \"$NOTE\""
261 echo "Use the note ID that you can fetch after listing your notes"
262 exit 1
263 fi
264
265 FILE=$($JQ -r --arg i $OK '.notes[] | select(.id == $i) | .file' $DB)
266
267 if [ "$FILE" ]; then
268 $PAGER ${NOTESDIR}/${FILE}
269 fi
270 }
271
272 function export_config() {
273 if [ -r ${RCFILE} ]; then
274 echo "Backing up current '${RCFILE}'...."
275 mv -f ${RCFILE} ${RCFILE}.$(date +%Y%m%d_%H%M)
276 fi
277 echo "Writing '${RCFILE}'...."
278 sed -n '/^set_defaults() {/,/^} # end set_defaults, do not change this line./p' $0 \
279 | grep -v set_defaults \
280 | sed -e 's/^\([^=]*\)=\${\1:-\([^}]*\)}/\1=\2/' \
281 > ${RCFILE}
282 if [ -r ${RCFILE} ]; then
283 echo "Taking no further action."
284 exit 0
285 else
286 echo "Could not write '${RCFILE}'...!"
287 exit 1
288 fi
289 }
290
291 # we should expand on this function to add a sample note and explain a little bit
292 # how the program works.
293 function firstrun() {
294 [ -f $RCFILE ] && RC=$RCFILE || RC="none"
295
296 clear
297 echo "${BASENAME} configuration:
298
299 base directory: ${BASEDIR}/
300 notes archive: ${NOTESDIR}/
301 notes database: ${DB}
302 rc file: $RC
303 text editor: ${EDITOR}
304 terminal: ${TERMINAL}
305 jq executable: ${JQ}
306 "
307
308 read -r -p "Do you wish to continue? (y/N) " ANSWER
309 case $ANSWER in
310 y|Y )
311 mkdir -p $NOTESDIR
312 cat << __EOL__ > ${DB}
313 {
314 "params": {
315 "version": "${VERSION}",
316 "dbversion": "${DBVERSION}"
317 },
318 "notes": []
319 }
320 __EOL__
321 echo; echo "All done, you can now write your first note."
322 ;;
323 * )
324 echo "No changes made. Exiting"
325 exit
326 ;;
327 esac
328 }
329
330 # check for notes dir existance and create it in case it doesn't exists
331 if [[ ! -d $NOTESDIR ]]; then
332 # we don't have a directory. FIRST RUN?
333 firstrun
334 fi
335
336 # shellcheck disable=SC2006
337 GOPT=$(getopt -o hvpla::e::d::s:: --long help,version,list,plain,userconf,backup::,add::,edit::,delete::,show:: -n 'bash-notes' -- "$@")
338
339 # shellcheck disable=SC2181
340 if [ $? != 0 ] ; then helptext >&2 ; exit 1 ; fi
341
342 # Note the quotes around `$GOPT': they are essential!
343 eval set -- "$GOPT"
344 unset GOPT
345
346 while true; do
347 case "$1" in
348 -h | --help )
349 helptext
350 exit
351 ;;
352 -v | --version )
353 echo $BASENAME v${VERSION}
354 exit
355 ;;
356 -p | --plain )
357 PLAIN=true
358 shift
359 ;;
360 -l | --list )
361 listnotes
362 exit
363 ;;
364 -a | --add )
365 case "$2" in
366 '' )
367 read -r -p "Title: " TITLE
368 ;;
369 * )
370 TITLE=$2
371 ;;
372 esac
373 shift 2
374 addnote "$TITLE"
375 ;;
376 -e | --edit )
377 case "$2" in
378 '' )
379 read -r -p "Note ID: " NOTE
380 ;;
381 * )
382 NOTE=$2
383 ;;
384 esac
385 shift 2
386 editnote "$NOTE"
387 ;;
388 -d | --delete )
389 case "$2" in
390 '' )
391 read -r -p "Note ID: " NOTE
392 ;;
393 * )
394 NOTE=$2
395 ;;
396 esac
397 shift 2
398 rmnote "$NOTE"
399 ;;
400 -s | --show )
401 case "$2" in
402 '' )
403 read -r -p "Note ID: " NOTE
404 ;;
405 * )
406 NOTE=$2
407 ;;
408 esac
409 shift 2
410 shownote "$NOTE"
411 ;;
412 --userconf )
413 export_config
414 # shellcheck disable=SC2317
415 echo "config exported to \"$RCFILE\""
416 # shellcheck disable=SC2317
417 exit
418 ;;
419 -- )
420 shift
421 break
422 ;;
423 * )
424 break
425 ;;
426 esac
427 done
428
429 if [ -z $1 ]; then
430 helptext
431 fi