-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremarkable-ssh.sh
More file actions
executable file
·1209 lines (1064 loc) · 33.1 KB
/
remarkable-ssh.sh
File metadata and controls
executable file
·1209 lines (1064 loc) · 33.1 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
##
### Hard-coded globals (for easy access):
##
#
#
## Sync behaviour:
#
declare -a SyncParams=( ## For making either the local cache or (remote) device like the other.
'--info=progress2'
'--archive'
'--checksum'
## Some options (such as filters) are appended conditionally.
## See rsync manual section on "TRANSFER RULES" for filter compatibility.
)
declare -a DiffSyncParams=( ## For checking what rsync would do if run.
'--dry-run'
'--itemize-changes'
)
declare -a SshCmd=(
'ssh'
'-o' 'ConnectTimeout 3'
)
#
## Remarkable implementation:
#
declare XochitlDir='/home/root/.local/share/remarkable/xochitl'
## Rm* associative arrays (-A) are accessed through the get_rm_enum function.
declare -A RmFileExt=( ## File types defined by Xochitl.
[metadata]='metadata' ## Defines object.
[content]='content' ## Defines state of object (e.g. user preferences).
[local]='local' ## Meta-content data? ("contentFormatVersion")
[thumbnails]='thumbnails' ## Thumbnail image(s). Always singular?
[png]='png' ## Used for thumbnails in sub-directories?
[rm]='rm' ## "reMarkable .lines file" ("version=6")
[pagedata]='pagedata'
[epubindex]='epubindex'
)
declare -A RmObjectType=( ## Object types defined by Xochitl.
[folder]='CollectionType'
[document]='DocumentType'
)
declare -a RmSupportedImportFileExt=( ## File types Xochitl can import.
'pdf'
'epub'
)
#
## Help output:
#
declare -a help_sections=(
'main'
)
for s in "${help_sections[@]}"; do
declare -a "${s}_help_text"='()'
done
read -r -d '' main_help_text <<- 'EOF'
It should be safe to run operations with missing parameters.
When one is missing, you will be told what the next parameter field should be.
Many functions define variables of questionable utility as an attempt at documentation.
Only `cache` operations interact with the remote device.
The only operation that attempts to modify the remote device is `cache push`.
No effort is made to avoid incidental modification, like updating file access timestamps.
Running `cache push` will, upon completion, restart the remote device's xochitl service.
Synchronisation (`cache push`/`cache pull`) is performed using rsync.
These operations will delete anything on the receiving side that is not on the sending side!
Sync behaviour can be adjusted by editing the "SyncParams" variable at the top of this script.
Almost all operations require the "cache" parameter to have been set.
`Cache` operations also require the "host" parameter, corresponding to your S.S.H. host.
EOF
#
##
### Initialisation for function definitions:
##
#
{ ## Check for (some) dependencies:
declare -a Dependencies=(
'jq'
'rsync'
'ssh'
'find'
'sed' ## Currently only used in `diff_cache`.
)
declare -i failed=0 ## Print all, if any, missing dependencies.
for dep in "${Dependencies[@]}"; do
if ! command -v "$dep" > /dev/null 2>&1 ; then
echo "Failed to detect necessary program: \"$dep\"" >&2
failed=1
fi
done
if ((failed)); then exit 1; fi
}
## Support termination from sub-shells:
trap "exit 1" TERM
export TOP_PID=$$
function terminate() {
kill -s SIGTERM 0 ## Send to all processes in group (see `man 2 kill`).
## Attempt to prevent async procession.
if command -v sleep > /dev/null 2>&1 || enable -f sleep sleep ; then
sleep 2
else
wait -f ## Not specifying $TOP_PID, for risk of race condition.
fi
}
#
##
### Utility functions:
##
#
#
## Validation utility functions:
#
function validate_cache() {
if [[ -z "$cache" ]]; then
echo 'Specify local directory for cache.' >&2
elif [[ ! -d "$cache" ]]; then
echo "Specified cache directory does not exist: \"$cache\"" >&2
else
return 0
fi
terminate
}
function validate_host() {
## Currently, only a simple string not null check is performed.
if ! get_param 'host' >/dev/null; then
echo 'Specify S.S.H. host for your Remarkable device.' >&2
terminate
fi
}
function validate_string_not_empty() {
if [[ -z "$1" ]]; then
if [[ "$2" ]]; then
echo "$2" >&2
else
echo 'Encountered empty string where value is required.' >&2
fi
terminate
fi
}
function is_function_defined() {
validate_string_not_empty "$1"
if declare -F "$1" >/dev/null 2>&1; then return 0; fi ## True.
return 1 ## False.
}
#
## Accessor utility functions:
#
function get_param() {
## $1: Parameter name.
if [[ ! -v "$1" ]]; then
return 1
fi
echo "$1" ## Empty string may be valid.
return 0
}
function get_necessary_param() {
if ! get_param "$1"; then ## Return param name via stdout on success.
echo "Necessary parameter not defined: \"$1\"" >&2
terminate
fi
}
function get_rm_enum() { ## Accessor for Rm* arrays.
local -n rm_enum="Rm$1"
local rm_name="$2"
local var="${!rm_enum}_${rm_name}"
if [[ -v "$var" ]]; then ## Check for cached global variable.
## Found variable-- use it.
echo "${!var}"
return
fi
## No cached variable. Look for entry in array.
while read -r entry; do
if [[ "$entry" == "$rm_name" ]]; then
## Cache to global variable.
declare -g "${var}"="${rm_enum[$entry]}"
echo "${!var}"
return
fi
done < <(get_preferred_labels "${!rm_enum}")
echo "No entry for \"$rm_name\" in \"${!rm_enum}\" array." >&2
terminate
}
#
## UUID-related utility functions:
#
function is_string_uuid() {
if [[ $1 =~ ^[[:alnum:]]{8}-([[:alnum:]]{4}-){3}[[:alnum:]]{12}$ ]]; then
return 0 ## True.
else
return 1 ## False.
fi
}
function gen_uuid() {
## I am not yet sure how Remarkable's UUID are generated.
## Checking for uniqueness is probably not useful, but I'm doing it anyway to be safe.
local prospective_uuid
if [[ ! -v 'existing_uuids[@]' ]]; then
## Cache to global variable in case of subsequent calls to this function.
declare -a -g existing_uuids=()
readarray -d $'\0' existing_uuids < <(find "$cache" -type f -name "*.$(get_rm_enum 'FileExt' 'metadata')" -print0)
fi
while prospective_uuid="$(uuidgen)" ; do
## assert(is_string_uuid "$prospective_uuid")
## No (non-assert) check for is_string_uuid, since caller logic may require it anyway.
## Check pre-existing UUID array to ensure no conflict with the one we generated.
for uuid in "${existing_uuids[@]}"; do
if [[ "$uuid" == "$prospective_uuid" ]]; then
## Generate new UUID and restart array scan.
continue 2
fi
done
## UUID seems new.
existing_uuids+=("$prospective_uuid")
echo "$prospective_uuid"
return 0
done
echo 'Failed to generate new UUID.' >&2
terminate
}
function parse_uuid_from_file_name() {
local ret
## Remove any preceeding path, up through the right-most forward slash.
ret="${1##*/}"
## Remove any trailing file extension, starting from the left-most period.
ret="${ret%%.*}"
if is_string_uuid "$ret"; then
echo "$ret"
else
terminate
fi
}
function get_uuid_by_name() {
local target_name="$1"
if [[ -z "$target_name" ]]; then return 0; fi ## Print no output (empty string).
for f in "$cache"/*".$(get_rm_enum 'FileExt' 'metadata')" ; do
if [[ "$(jq -r '.visibleName' "$f")" == "$target_name" ]]; then
## Print output.
parse_uuid_from_file_name "$f"
return 0
fi
done
return 1
}
function accept_uuid_or_name() {
if is_string_uuid "$1"; then
uuid="$1"
## Currently assumed to exist and be a directory/folder type object!
else
uuid="$(get_uuid_by_name "$1" "$cache")"
## Empty string is valid-- represents document root ($XochitlDir).
fi
echo "$uuid"
}
#
## Output/formatting utility functions:
#
function get_indent_str() {
local -n ret="$1"
local -i indent_ct="$2"
local indent_char="${3- }" ## Default to tab character.
for (( i=0; i != $indent_ct; i++ )); do
ret+='\t'
done
}
function print_with_indent() {
local -i indent_ct="$1"
shift
## All proceeding arguments are printed as messages with that indent level.
local buff=
get_indent_str 'buff' "$indent_ct"
for msg in "$@"; do
echo -e "$buff$msg"
done
}
function get_preferred_labels() { ## Print keys from an associative or values from an indexed array.
## Indirect access to associative array keys seems impossible as of version 5.3.9.
## `test/[[ -v ...` no longer works on associative arrays since version 5.2 (unless you enable 5.1 compatibility).
case "${!1@a}" in
A)
while read -r key ; do
echo "$key"
done < <(eval printf "\"%s\n\"" "\${!$1[@]}")
;;
a)
local -n arr="$1"
for val in "${arr[@]}" ; do
echo "$val"
done
;;
*)
echo "Invalid data type or empty array: \"$1\"" >&2
terminate
esac
}
#
## Filesystem utility functions:
#
function add_metadata_file() { ## Create metadata file in cache.
## This function assumes caller has validated its arguments.
local fs_dir="$1" ## Support Xochitl sub-directory format.
local metadata_type="$(get_rm_enum 'ObjectType' "$2")"
local visible_name="$3"
local parent_uuid="$4"
local uuid="$5" ## Unless "$metadata_type" == "${RmObjectType[folder]}".
if [[ "$metadata_type" == "$(get_rm_enum 'ObjectType' 'folder')" ]]; then
## assert(!uuid)
uuid="$(gen_uuid)"
fi
if ! is_string_uuid "$uuid"; then
echo "Invalid UUID: \"$uuid\""
terminate
fi
local new_file_name="$uuid.$(get_rm_enum 'FileExt' 'metadata')"
local ts="$(date '+%s')000" ## Append empty milisecond precision to epoch.
## I am not sure whether these are all necessary.
## The order probably does not matter and will likely be changed by Xochitl anyway.
cat <<- EOF >> "$fs_dir/$new_file_name"
{
"visibleName": "$visible_name",
"parent": "$parent_uuid",
"lastModified": "$ts",
"createdTime": "$ts",
"new": false,
"source": "",
"modified": false,
"metadatamodified": false,
"deleted": false,
"pinned": false,
"version": 0,
"type": "$metadata_type"
}
EOF
}
#
##
### Sub-operation handler functions:
##
#
function pull_cache() { ## Pull remote device to local cache.
if (($#)); then
local -i print_help=0
local -i err=0
case $1 in
diff)
echo -e 'Format is described in the rsync manual. See "--itemize-changes".\n'
SyncParams+=("${DiffSyncParams[@]}")
;;
help) print_help=1 ;;
*)
echo "Invalid sub-operation: \"$1\"" >&2
print_help=1
err=1
;;
esac
if ((print_help)); then
local -A Operations=(
'diff'
)
print_help 'Adjust cache directory to match tablet.' '' 'Operations'
if ((err)); then terminate; fi
return
fi
fi
## Copy contents of remote directory, not the directory including its contents.
rsync "${SyncParams[@]}" "$host:$XochitlDir/" "$cache"
}
function push_cache() { ## Push local cache to remote device.
if (($#)); then
local -i err=0
case $1 in
diff)
echo -e 'Format is described in the rsync manual. See "--itemize-changes".\n'
rsync "${SyncParams[@]}" "${DiffSyncParams[@]}" "$cache/" "$host:$XochitlDir"
return
;;
help) ;;
*)
echo "Invalid sub-operation: \"$1\"" >&2
err=1
;;
esac
local -A Operations=(
'diff'
)
print_help 'Adjust tablet to match cache directory.' '' 'Operations'
if ((err)); then terminate
else return
fi
else
"${SshCmd[@]}" "$host" systemctl stop xochitl || {
echo 'Failed to stop remote device service: xochitl' >&2
terminate
}
rsync "${SyncParams[@]}" "$cache/" "$host:$XochitlDir" || return 1
"${SshCmd[@]}" "$host" systemctl start xochitl || {
echo 'Failed to start remote device service: xochitl' >&2
terminate
}
fi
}
function diff_cache() { ## Compare local cache to remote device.
if [[ -v '1' ]]; then
local -i err=0
if [[ "$1" != 'help' ]]; then
echo "Invalid sub-operation: \"$1\"" >&2
err=1
fi
print_help 'Output table of differences between tablet and cache directory.' '' ''
if ((err)); then terminate; fi
return 0
fi
## Strip at most one trailing forward slash from the paths, if present.
## This is necessary because we append a slash during the path truncation.
local cache="${cache/%\/}"
local xochitl_dir="${XochitlDir/%\/}"
## Sanitise strings for bash (@E) and left side of sed substitution expression.
## https://unix.stackexchange.com/questions/129059/how-to-ensure-that-string-interpolated-into-sed-substitution-escapes-all-metac/129063#129063
local sanitised_cache=$(sed 's:[][\\/.^$*]:\\&:g' <<< "${cache@E}")
local sanitised_xochitl_dir=$(sed 's:[][\\/.^$*]:\\&:g' <<< "${xochitl_dir@E}")
## The strings above are used to trim file paths to target directories.
## If "cache" has a parent directory with the same name, truncation may end there.
## Cache remote list as array so we can act upon SSH failure.
local -a remote_lines
readarray -t remote_lines < <("${SshCmd[@]}" "$host" "find \"$xochitl_dir\" -type f -exec md5sum {} + | sort -k 2 | sed 's/ .*${sanitised_xochitl_dir}\// /'")
wait "$!" || {
echo 'SSH connection failed.'
terminate
}
## Sed is also used to suppress lines for unchanged items and to cut out checksum strings.
diff --width="$(tput cols)" --suppress-common-lines \
--old-line-format=' %l <++--> .
' --new-line-format=' . <--++> %l
' --unchanged-line-format=' . . .
' \
<(find "$cache" -type f -exec md5sum {} + | sort -k 2 | sed "s/ .*${sanitised_cache}\// /") \
<(printf '%s\n' "${remote_lines[@]}") \
| sed -E '/^[[:space:].]*$/d; s/((^|>)\s*)[[[:lower:][:digit:]]+ +/\1/' \
| column -t --output-separator=' ' \
-C name="Local cache",right \
-C name="Difference" \
-C name="Remarkable device",right
}
#
##
### Primary operation handler functions:
##
#
function run_cache() { ## Operations relating the local cache and remote device.
validate_cache "$cache"
validate_host
local -A Operations=(
[push]='push_cache'
[pull]='pull_cache'
[diff]='diff_cache'
)
local -i err
if [[ -v '1' ]]; then
local silly_buff="${1,,}" ## Namerefs do not support positional arguments.
local -n run_op='silly_buff'
if get_op 'run_op' 'Operations'; then
err=0
## Handle default false parameters that disable default behaviour.
if ! get_param 'only_add' || get_param 'no_delete'; then
## Enable deletion of extraneous receiver-side things.
## This does not include unsupported files (see below).
SyncParams+=('--delete')
fi >/dev/null
if ! get_param 'unsupported_files' >/dev/null; then
## Direct rsync to...
## Ignore unsupported file types.
for ext in "${RmFileExt[@]}" "${RmSupportedImportFileExt[@]}"; do
SyncParams+=("-f+ *.$ext")
done
SyncParams+=('-fH,! */')
## Delete empty directories.
## These likely only contained unsupported file types.
SyncParams+=('--prune-empty-dirs')
fi
shift
"$run_op" "$@"
return "$?"
fi
## Else:
if [[ "$1" == 'help' ]]; then err=0
else
err=1
echo "Invalid cache operation: \"$1\""
fi
else err=1 ## [[ ! -v '1' ]]
fi
if [[ -v '2' && -v "Operations["$2"]" ]]; then
"${Operations["$2"]}" 'help'
else
print_help 'Cache scope operations affect or relate to the entire cache directory.' '' 'Operations'
fi
if ((err)); then terminate
else return 0
fi
}
function run_list_directory() { ## Enumerate contents of a Remarkable folder object (in the cache).
if [[ -v '1' && "$1" == 'help' ]]; then
print_valid_args \
'Target folder (default: document root)' \
'Recursive depth limit (default: unlimited)'
fi
local parent="${1:-/}"
## Initially name; uuid for recursive calls.
## Default to document root ("/" --> "").
local -i recursive_depth_remaining="${2:--1}"
## Default to -1.
## Negative values for infinite recursion (unless decrement overflows).
## This may or may not have fork bomb potential.
local -i initial_recursion_depth_limit="${3:-$recursive_depth_remaining}"
validate_string_not_empty "$parent"
validate_cache "$cache"
local parent_name
local parent_uuid
local parent_metadata_file
if (( recursive_depth_remaining == initial_recursion_depth_limit )); then
## This is not a recursive iteration.
parent_name="$parent"
if [[ "$parent_name" == '/' ]]; then
parent_name=''
parent_uuid=
else
parent_uuid="$(get_uuid_by_name "$parent_name" "$cache")"
validate_string_not_empty "$parent_uuid" "Failed to locate UUID for object named \"$parent_name\"."
fi
else
## This is a recursive iteration.
parent_uuid="$(parse_uuid_from_file_name "$parent")"
parent_name=
fi
local current_recursion_depth=$((initial_recursion_depth_limit - recursive_depth_remaining))
local indent_str= ## Indent with tabs for each level of recursion.
get_indent_str 'indent_str' "$current_recursion_depth"
for f in "$cache"/*".$(get_rm_enum 'FileExt' 'metadata')" ; do
if [[ "$(jq -r '.parent' "$f")" == "$parent_uuid" ]]; then
## Print name registered in metadata (not the UUID file name).
case $(jq -r '.type' "$f") in
$(get_rm_enum 'ObjectType' 'folder'))
echo -e "$indent_str$(jq -j '.visibleName' "$f")/" ## Append '/' after folder names.
## Handle recursion if enabled.
if (( $recursive_depth_remaining != 0 )); then
run_list_directory "$f" $((recursive_depth_remaining - 1)) "$initial_recursion_depth_limit"
fi
;;
$(get_rm_enum 'ObjectType' 'document'))
echo -e "$indent_str$(jq -j '.visibleName' "$f")"
local document_uuid="$(parse_uuid_from_file_name "$f")"
## Indent information about and files subsidiary to this object.
local sub_document_depth=$((current_recursion_depth + 1))
## Print UUID associated with this object.
print_with_indent "$sub_document_depth" "UUID: $document_uuid"
## Print type of all files associated with this object.
for ff in "$cache/$document_uuid."* ; do
print_with_indent "$sub_document_depth" ".${ff##*.}"
done
if [[ -d "$cache/$document_uuid" ]]; then
print_with_indent "$sub_document_depth" "/"
for ff in $cache/$document_uuid/* ; do
print_with_indent $((sub_document_depth + 1)) "${ff##*/}"
done
fi
;;
## Others are ignored.
esac
fi
done
}
function run_delete() { ## Delete a Remarkable object's file(s) (from the cache).
if [[
! -v '1' \
|| "$1" == 'help'
]]; then
print_valid_args 'Target object'
return
fi
local target="$1"
validate_string_not_empty "$target" "Missing parameter expected: target object"
validate_cache "$cache"
if ! is_string_uuid "$target"; then
local target_name="$target"
## `... || true` is hack around `set -o errexit`.
target="$(get_uuid_by_name "$target" "$cache" || true)"
validate_string_not_empty "$target" \
"Failed to find UUID associated with target name: \"$target_name\""
fi
if ! rm -rv "$cache/$target"* ; then terminate; fi
}
function run_mkdir() { ## Make a Remarkable folder object (not filesystem directory) (in the cache).
if [[
! -v '1' \
|| "$1" == 'help'
]]; then
print_valid_args \
'Name of new folder' \
'Parent directory (default: document root)'
return
fi
local dir_name="$1"
local parent_uuid="$(accept_uuid_or_name "$cache" "${2:-/}")" ## Default to document root.
validate_string_not_empty "$dir_name"
validate_cache "$cache"
add_metadata_file "$cache" 'folder' "$dir_name" "$parent_uuid"
}
function run_add_file() { ## Copy a supported file type (from anywhere) as/into a new Remarkable object (in the cache).
if [[
! -v '1' \
|| "$1" == 'help'
]]; then
print_valid_args 'Path to file'
return
fi
local file_src="$1"
local parent_uuid="$(accept_uuid_or_name "$cache" "${2:-/}")" ## Default to document root.
if [[ ! -f "$file_src" ]]; then
echo "Source file does not exist: \"$file_src\"" >&2
terminate
fi
validate_cache "$cache"
local uuid="$(gen_uuid)"
local file_ext="${file_src##*.}"
local uuid_file_name=
for ext in ${RmSupportedImportFileExt[@]}; do
if [[ "$file_ext" == "$ext" ]]; then
uuid_file_name="$uuid.$file_ext"
break
fi
done
if [[ -z "$uuid_file_name" ]]; then
echo "File extension is not supported: \"$file_ext\"" >&2
echo "Supported extensions:"
for ext in ${RmSupportedImportFileExt[@]}; do
echo -e "\t$ext"
done
terminate
fi
local visible_name="${file_src##*/}"
visible_name="${visible_name%%.*}"
validate_string_not_empty "$visible_name"
## Add the file.
cp --update=none-fail "$file_src" "$cache/$uuid_file_name" || terminate
## Add a corresponding metadata file.
add_metadata_file "$cache" 'document' "$visible_name" "$parent_uuid" "$uuid"
## Add .content file. I have no idea why this is necessary, but it is.
if [[ -e "$cache/$uuid.$(get_rm_enum 'FileExt' 'content')" ]]; then
echo 'Detected pre-existing .content file while adding new document. It will not be over-written.' >&2
else
echo '{}' > "$cache/$uuid.$(get_rm_enum 'FileExt' 'content')"
fi
}
function run_rename() { ## Change the visible name associated with a Remarkable object (in the cache).
if [[
! -v '2' \
|| "$1" == 'help'
]]; then
print_valid_args \
'Object to rename' \
'New name for object'
return
fi
local target="$(accept_uuid_or_name "$cache" "$1")"
local new_name="$2"
validate_string_not_empty "$target"
validate_cache "$cache"
local target_file="$cache/$target.$(get_rm_enum 'FileExt' 'metadata')"
## Only over-write on successful jq return status.
jq ".visibleName = \"$new_name\"" "$target_file" > "$target_file.tmp" && mv "$target_file.tmp" "$target_file"
}
function run_move() { ## Change the parent directory associated with a Remarkable object (in the cache).
if [[
! -v '2' \
|| "$1" == 'help'
]]; then
print_valid_args \
'Object to move' \
'New parent folder'
return
fi
local target="$(accept_uuid_or_name "$cache" "$1")"
local new_parent="$(accept_uuid_or_name "$cache" "$2")"
validate_string_not_empty "$target"
validate_cache "$cache"
local target_file="$cache/$target.$(get_rm_enum 'FileExt' 'metadata')"
## Only over-write on successful jq return status.
jq ".parent = \"$new_parent\"" "$target_file" > "$target_file.tmp" && mv "$target_file.tmp" "$target_file"
}
function run_print_help() {
if ((${#@} == 0)); then
print_help
return
fi
## Traverse potential chain of operations.
local help_section=
local next_op=
local -i shift_by
while
parse_positional_args 'next_op' 'shift_by' "$@" \
&& test -v 'next_op'
do
help_section="$next_op" ## Cache in case previous was last.
shift "$shift_by" || break ## Break if past last.
done
if [[ -n "$help_section" ]]; then
"$help_section" "$@" 'help'
else
echo -e '\nNo help is available for that query. The target probably does not exist.\n' >&2
terminate
fi
}
#
## Meta-operations:
#
function print_options() {
local -n valid="$1"
local subject="${2,,}"
echo "${subject@u}:"
while read -r item; do
echo -e "\t$item"
done < <(get_preferred_labels "${!valid}")
}
function print_valid_args() {
local -a valid_args=()
local -i i=1
for a in "$@"; do
valid_args+=("$i: $a")
i+=1
done
if ((${#valid_args[@]} == 0)); then terminate; fi
print_options 'valid_args' 'Arguments expected/accepted'
}
function print_help() {
## Variables allow for flexible argument order, accommodating default values.
local -r help_text="${1-${main_help_text[@]}}"
local -r valid_params="${2-${!valid_params}}" ## Nameref.
local -r valid_ops="${3-${!valid_ops}}" ## Nameref.
if ((! ${#@})); then ## No arguments to this function call-- assume main help section.
echo -ne "\nSYNTAX: \`${0##*/} [Flag]... <Operation>\`\n" \
" Operation: \`<name> [(scoped) Flag]... [(sub-)Operation]\`\n" \
" Flag: \`-[-]<parameter>[=<value>]\`\n\n"
fi
if [[ -n "$help_text" ]]; then
echo -ne "\n$help_text\n\n\n"
else echo
fi
if [[ -n "$valid_params" ]]; then
print_options "$valid_params" 'Parameters available at this scope'
echo
fi
if [[ -n "$valid_ops" ]]; then
print_options "$valid_ops" 'Operations available at this scope'
echo
fi
return 0
}
#
##
### Initialisation functions:
##
#
function load_param_set() {
declare -g -n valid_params="$1"
for f in "${valid_params[@]}"; do
## "-v" condition supports shell with `set -u`/`set -o nounset` enabled.
if [[ -v "$f" && -n "${!f}" ]]; then
echo "Hard-coded parameter variable already in use: \"$f\"" >&2
terminate
fi
done
}
#function load_op_set() {
# declare -g -n valid_ops="$1"
# for o in "${valid_ops[@]}"; do
# if is_function_defined "$o"; then continue; fi
# echo -ne \
# "Failed to load operation set: \"$1\"\n" \
# "\tUndefined function: \"$o\"\n" \
# >&2
# terminate
# done
#}
function get_op() {
## $1: nameref assigned to variable containing the operation name.
## Variable must not be a positional argument.
## $2: (Optional) array to search through.
local -n op="${1,,}"
local -n ops_arr="${2-valid_ops}"
if [[ -v "ops_arr["$op"]" ]]; then
op="${ops_arr["$op"]}"
if is_function_defined "$op"; then return 0; fi
echo "No function defined for valid operation: \"${!op}\"" >&2
terminate
fi
return 1
}
#
## Parsing helper functions:
#
function parse_param() {
local key="$1"
local val="$2"
## Validate that specified key is known/handled (was set/assigned/initialised).
local -n param
for p in "${!valid_params[@]}"; do
if [[ "$p" == "$key" ]]; then
param="valid_params[$key]"
break
fi
done
if [[ ! -R 'param' ]]; then
echo "Invalid parameter: \"$key\"" >&2
terminate
fi
## Check whether a handler function matching the parameter name exists.
if is_function_defined "handle_param_$param"; then
## Run it immediately with the supplied value as its first argument.
## Terminate on non-zero return status from that function.
"handle_param_$param" "$val" || terminate
## No additional actions are taken for these parameters.
return
fi
## The remaining parameter types are boolean and string.
## Both are assigned to global variables.
## Protect against namespace conflicts with caller's environment.
if [[ -v "$param" ]]; then
echo "Value already assigned to parameter variable: \"$param\"." >&2
echo 'This could be a result of duplicate specification or namespace conflict.'
terminate
fi
## Accept flags without a specified val(ue) as boolean toggle switches.
if [[ -z "$val" ]]; then
declare -g -i "$param"=1 ## 1 == true. Not declared as integer type.
## If there a handler function is defined for this flag, run it now.
if is_function_defined "handle_bool_param_$param"; then
"handle_bool_param_$param"
fi
return
fi
declare -g "$param"="$val" || {
echo "Failed to assign value to parameter: \"$param\"" >&2
echo -e "\tValue was: \"$val\""
terminate
}
}
function count_flag_prefix_length() {
## $1: Target string, which may or may not start with a flag prefix.
## $2: Nameref to caller variable for counting.
local -n i="$2" ; i=0
while [[ "${1:$i:1}" == "$FlagPrefixSymbol" ]]; do
i+=1
if (( $i > 2 )); then
echo "Invalid prefix ($i+) for supposed flag: \"$1\"" >&2
terminate
fi
done
}
function parse_flag() {
## $1: Flag string, including prefix, delimiter, and value if applicable.
local -i prefix_offset ## Assigned zero later.
count_flag_prefix_length "$1" 'prefix_offset'
if ((prefix_offset == 0)); then return 1; fi
local key
local val=
local FlagKeyValDelim='='
IFS="$FlagKeyValDelim" read -r key val <<< "${1:$prefix_offset}" || {
echo "Failed to parse flag parameter: \"$1\"" >&2
terminate
}
parse_param "$key" "$val" ## Terminates on failure.
}
function parse_config_file() {
## Multiple delim characters should be interpreted independently.
local ConfigKeyValDelim='='
local LineCommentDelim='#'
while read -r line; do
## Whitespace leading or trailing line has been stripped.
## Skip empty lines and comment lines.
case ${line:0:1} in