forked from Jack000/Expose
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpose.sh
More file actions
executable file
·1413 lines (1173 loc) · 45.1 KB
/
Copy pathexpose.sh
File metadata and controls
executable file
·1413 lines (1173 loc) · 45.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
#!/usr/bin/env bash
# Expose Static Site Generator
# Generates responsive photo galleries from folder structures
#
# Usage: ./expose.sh [-s] [-c] [-p <project>]
# Author: Expose Static Site Generator
# Version: 1.0
# Original Expose didn't use strict error handling
SECONDS=0
topdir=$(pwd)
scriptdir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# Load Mustache-Light template engine
source "$scriptdir/lib/template.sh"
skip_images=false
# Check if we're in a project directory or need to detect it
if [ -f "project.config" ] && [ -d "input" ]; then
# We're already in a project directory
proj_dir="$topdir"
project=$(basename "$topdir")
else
# Use the original project detection logic
project=$(find "$topdir/projects" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' 2>/dev/null | head -1)
proj_dir="$topdir/projects/$project"
fi
while getopts ":scp:" opt; do
case "${opt}" in
s)
echo "Skipping image encoding"
skip_images=true
;;
c)
echo "Disabling HTML cache"
no_html_cache=true
;;
p)
if [ -d "$topdir/projects/${OPTARG}" ]; then
echo "using project: ${OPTARG}"
project=${OPTARG}
proj_dir="$topdir/projects/${OPTARG}"
else
echo "project '${OPTARG}' not found"
exit 1
fi
;;
\?)
echo "Invalid option: -$OPTARG" >&2
echo "Usage: $0 [-s] [-c] [-p <project>]" >&2
echo " -s: Skip image encoding (HTML only)"
echo " -c: Disable HTML cache (useful for theme development)"
echo " -p: Specify project folder"
exit 1
;;
esac
done
# configuration
# Source project configuration file
if [ ! -f "$proj_dir/project.config" ]; then
echo "❌ Project configuration not found: $proj_dir/project.config" >&2
echo "" >&2
echo "Create a new project with:" >&2
echo " ./new-project.sh -p $project" >&2
exit 1
fi
. "$proj_dir/project.config"
# Load site config (overrides config defaults for content variables)
site_config=""
if [ -f "$proj_dir/site.config" ]; then
site_config=$(cat "$proj_dir/site.config")
# Parse site config and set variables
while IFS=: read -r key value; do
# Skip empty lines and comments
[[ -z "$key" || "$key" =~ ^[[:space:]]*# ]] && continue
# Trim whitespace
key=$(echo "$key" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
value=$(echo "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
# Set variable dynamically
if [ -n "$key" ] && [ -n "$value" ]; then
eval "$key=\"$value\""
fi
done <<< "$site_config"
fi
# Set defaults for content variables (if not set by site.config)
site_title=${site_title:-"My Awesome Photos"}
site_description=${site_description:-"A photography portfolio"}
site_author=${site_author:-""}
site_keywords=${site_keywords:-"photography, photos, gallery"}
site_copyright=${site_copyright:-"© $(date +%Y)"}
nav_title=${nav_title:-"Pages"}
# Root gallery display name (default: directory name)
root_gallery_name=${root_gallery_name:-""}
# Show root in navigation (default: true)
show_root_in_nav=${show_root_in_nav:-"true"}
theme=${theme:-"default"}
theme_dir=${theme_dir:-"$scriptdir/themes/$theme"}
in_dir=${in_dir:-"$proj_dir/input"}
out_dir=${out_dir:-"$topdir/output/$project"}
# Load theme configuration (defines required image resolutions)
if [ -f "$theme_dir/theme.config" ]; then
. "$theme_dir/theme.config"
fi
# widths to scale images to (heights are calculated from source images)
resolution=${resolution:-(2560 1920 1280 1024 640)}
# jpeg compression quality for static photos
jpeg_quality=${jpeg_quality:-85}
# Apply default sort directions if not set in project.config
folder_sort_direction=${folder_sort_direction:-"asc"}
image_sort_direction=${image_sort_direction:-"asc"}
folder_sort_option="-r"
image_sort_option="-r"
if [ "$folder_sort_direction" = "asc" ]; then
folder_sort_option=""
fi
if [ "$image_sort_direction" = "asc" ]; then
image_sort_option=""
fi
# script starts here
# Check for required dependencies
missing_deps=()
required_tools=("exiftool" "vips" "rsync" "jq" "perl" "bc")
for tool in "${required_tools[@]}"; do
if ! command -v "$tool" >/dev/null 2>&1; then
missing_deps+=("$tool")
fi
done
if [ ${#missing_deps[@]} -gt 0 ]; then
echo "❌ Missing required dependencies: ${missing_deps[*]}" >&2
echo "" >&2
echo "Please run the setup script to install all dependencies:" >&2
echo " ./setup.sh" >&2
echo "" >&2
exit 1
fi
# Set VIPS concurrency to 1 for maximum stability (prevents threading-related segfaults)
# Benchmarked: VIPS_CONCURRENCY=2 is 1.5% faster but we prioritize stability
export VIPS_CONCURRENCY=1
# Determine optimal parallelization for image processing
# Benchmarked optimal values for different CPU counts
nproc_count=$(nproc 2>/dev/null || echo "4")
if [ "$nproc_count" -le 4 ]; then
MAX_PARALLEL_IMAGES=4
elif [ "$nproc_count" -le 8 ]; then
MAX_PARALLEL_IMAGES=8
elif [ "$nproc_count" -le 16 ]; then
MAX_PARALLEL_IMAGES=12
elif [ "$nproc_count" -le 24 ]; then
MAX_PARALLEL_IMAGES=16
else
MAX_PARALLEL_IMAGES=24 # Optimal for 32-core: 4.5s vs 5.7s with 12
fi
# directory structure will form nav structure
paths=() # relevant non-empty dirs in $in_dir
nav_name=() # a front-end friendly label for each item in paths[], with numeric prefixes stripped
nav_depth=() # depth of each navigation item
nav_type=() # 0 = structure, 1 = leaf. Where a leaf directory is a gallery of images
nav_url=() # a browser-friendly url for each path, relative to output
nav_image_url=() # url for images (root gallery gets subfolder)
nav_count=() # the number of images in each gallery, or -1 if not a leaf
metadata_file="metadata.txt" # search for this file in each gallery directory for gallery-wide metadata
gallery_files=() # a flat list of all gallery images
gallery_nav=() # index of nav item the gallery image belongs to
gallery_url=() # url-friendly name of each image
gallery_md5=() # md5 hash of original image
gallery_maxwidth=() # maximum image size available
gallery_maxheight=() # maximum height
# scan working directory to populate $nav variables
root_depth=$(echo "$in_dir" | awk -F"/" "{ print NF }")
# $1: template, $2: {{ variable name }}, $3: replacement string
template () {
key=$(echo "$2" | tr -d '[:space:]')
value=$(echo $3 | sed -e 's/\\/\\\\/g' -e 's/\//\\\//g' -e 's/&/\\\&/g') # escape sed input
echo "$1" | sed "s/{{$key}}/$value/g; s/{{$key:[^}]*}}/$value/g"
}
# Batch template processing - much faster than multiple individual calls
# Usage: template_batch "template_string" "key1:value1" "key2:value2" ...
template_batch() {
local result="$1"
shift
# Process each key-value pair by calling template() function
# This is slower than a single sed call, but handles multi-line values correctly
for assignment in "$@"; do
if [[ "$assignment" == *":"* ]]; then
local key="${assignment%%:*}"
local value="${assignment#*:}"
result=$(template "$result" "$key" "$value")
fi
done
echo "$result"
}
# Extract EXIF data for a specific file from individual JSON cache
# $1: filename (basename), $2: EXIF field name
get_exif_value() {
local filename="$1"
local field="$2"
# Find the cache file for this image
local cache_file=""
for k in "${!gallery_files[@]}"; do
if [ "$(basename "${gallery_files[k]}")" = "$filename" ]; then
local file_cache_key="${gallery_md5[k]}"
cache_file="$exif_cache_dir/$file_cache_key.json"
break
fi
done
# Check if cache file exists
if [ ! -f "$cache_file" ]; then
return
fi
# Parse JSON using jq for reliable extraction
jq -r --arg field "$field" '.[$field] // empty' "$cache_file" 2>/dev/null
}
# Check if /tmpfs exists, otherwise use the system default temp folder
if [ -d "/tmpfs" ]; then
tmpdir=$(mktemp -d -p /tmpfs -t expose.XXXXXXXX)
else
tmpdir=$(mktemp -d -t expose.XXXXXXXX)
fi
if [ -z "$tmpdir" ]
then
echo "Could not create scratch directory" >&2; exit 1;
fi
chmod -R 740 "$tmpdir"
printf "temp directory: $tmpdir\n"
cleanup() {
echo "Cleaning up"
if [ -d "$tmpdir" ]
then
rm -r "$tmpdir"
fi
echo " ✅"
echo "Elapsed time: $SECONDS seconds" # Prints the time elapsed since SECONDS was initialized
exit
}
trap cleanup INT TERM
printf "\nScanning directories\n "
# Process subdirectories (Original behavior - root is handled automatically)
while read node
do
echo -n " 📂"
node_depth=$(echo "$node" | awk -F"/" "{ print NF-$root_depth }")
# ignore empty directories
if find "$node" -maxdepth 0 -empty | read _
then
continue
fi
node_name=$(basename "$node" | sed -e 's/^[0-9][0-9]* *//;s/^[[:space:]]*//;s/[[:space:]]*$//')
if [ -z "$node_name" ]
then
node_name=$(basename "$node")
fi
# Special handling for root directory name
if [ "$node" = "$in_dir" ] && [ -n "$root_gallery_name" ]
then
node_name="$root_gallery_name"
fi
dircount=$(find "$node" -maxdepth 1 -type d ! -path "$node" ! -path "$node*/_*" | wc -l)
imagecount=$(find "$node" -maxdepth 1 -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif" -o -iname "*.bmp" -o -iname "*.webp" \) | wc -l)
# Determine node type:
# Type 2 = Column (depth 0 or 1, only subdirs, no images)
# Type 1 = Leaf gallery (has images, no subdirs or subdirs at depth 0/1)
# Type 0 = Structure/Branch (depth 2+, has subdirs, regardless of images)
if ( [ "$node_depth" -eq 0 ] || [ "$node_depth" -eq 1 ] ) && [ "$dircount" -gt 0 ] && [ "$imagecount" -eq 0 ]
then
node_type=2 # column header (depth 0 or 1, only subdirs, no images)
elif [ "$node_depth" -ge 2 ] && [ "$dircount" -gt 0 ]
then
node_type=0 # structure/branch at depth 2+: has subdirs (even if it also has images)
elif [ "$dircount" -gt 0 ]
then
node_type=0 # structure: dir contains other dirs at depth 0/1, it is not a pure leaf
else
node_type=1 # leaf: does not contain other dirs, it is a pure leaf gallery
fi
paths+=("$node")
nav_name+=("$node_name")
nav_depth+=("$node_depth")
nav_type+=("$node_type")
nav_has_images+=("$imagecount")
done < <(find "$in_dir" -type d ! -path "$in_dir*/_*" | sort -V $folder_sort_option) # Version sort for numeric prefixes
# re-create directory structure
mkdir -p "$out_dir"
dir_stack=()
url_rel=""
printf "\nPopulating nav\n "
for i in "${!paths[@]}"
do
echo -n " 📄"
# Build dir_stack based on actual parent path, not array order
# Always rebuild dir_stack from path (not from previous array position)
current_path="${paths[i]}"
current_depth="${nav_depth[i]}"
# Rebuild dir_stack from scratch based on current path
dir_stack=()
# Split current path and build stack up to parent level
if [ "$current_depth" -gt 0 ]; then
# Get all parent directories from the path
temp_path="$current_path"
temp_stack=()
# Walk up the path to root
for (( d=0; d<current_depth; d++ )); do
temp_path=$(dirname "$temp_path")
# Find this path in our nav arrays to get the name
for k in "${!paths[@]}"; do
if [ "${paths[k]}" = "$temp_path" ]; then
# Skip root (depth 0) from URL path
if [ "${nav_depth[k]}" -gt 0 ]; then
parent_url=$(echo "${nav_name[k]}" | sed 's/[^ a-zA-Z0-9]//g;s/ /-/g' | tr '[:upper:]' '[:lower:]')
temp_stack=("$parent_url" "${temp_stack[@]}")
fi
break
fi
done
done
dir_stack=("${temp_stack[@]}")
fi
url_rel=$(echo "${nav_name[$i]}" | sed 's/[^ a-zA-Z0-9]//g;s/ /-/g' | tr '[:upper:]' '[:lower:]')
url=""
for u in "${dir_stack[@]}"
do
url+="$u/"
done
# Columns (type 2) don't get their own URL - they only exist in navigation
if [ "${nav_type[i]}" -ne 2 ]; then
url+="$url_rel"
fi
# Special handling for root directory
if [ "${paths[$i]}" = "$in_dir" ]
then
nav_url+=("") # index.html goes to root
nav_image_url+=("$url_rel") # but images go to subfolder
mkdir -p "$out_dir"
mkdir -p "$out_dir/$url_rel"
elif [ "${nav_type[i]}" -eq 2 ]
then
# Columns don't get output directories or URLs
nav_url+=("")
nav_image_url+=("")
else
nav_url+=("$url/")
nav_image_url+=("$url")
mkdir -p "$out_dir/$url"
fi
done
printf "\nReading files"
# read in each file to populate $gallery variables
for i in "${!paths[@]}"
do
nav_count[i]=-1 # All directories start with -1, including non-galleries
dir="${paths[i]}"
url="${nav_url[i]}"
# Check if directory has images - if not, skip processing but keep in nav structure
image_count=$(find "$dir" -maxdepth 1 ! -path "$dir" ! -path "$dir*/_*" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.gif" -o -iname "*.png" -o -iname "*.bmp" -o -iname "*.webp" \) | wc -l)
if [ "$image_count" -eq 0 ]; then
nav_count[i]=0
continue
fi
mkdir -p "$out_dir"/"$url"
printf "\n 📂 $url"
index=0
# loop over found files
while read file
do
filename=$(basename "$file")
printf "\n %s" "$filename" # Show filename for better progress feedback
# printf "." # Alternative: fast progress dots
# URL-safe conversion - use stable hash-based ID to avoid reordering issues
image_id=$(echo "${file##*/}_$(stat -c '%Y_%s' "$file" 2>/dev/null || stat -f '%m_%z' "$file" 2>/dev/null)" | md5sum | cut -c1-12)
image_url="$image_id" # Use stable hash-based ID
# Extract and normalize extension (already filtered by find)
extension="${filename##*.}"
extension=$(echo "$extension" | tr '[:upper:]' '[:lower:]')
image="$file"
# Get the width and height of the image using VIPS
width=$(vipsheader -f width "$image" 2>/dev/null)
height=$(vipsheader -f height "$image" 2>/dev/null)
maxwidth=0
maxheight=0
count=0
for res in "${resolution[@]}"
do
((count++))
# store max values for later use
if [ "$width" -ge "$res" ] && [ "$res" -gt "$maxwidth" ]
then
maxwidth="$res"
maxheight=$((res*height/width))
elif [ "$maxwidth" -eq 0 ] && [ "$count" = "${#resolution[@]}" ]
then
maxwidth="$res"
maxheight=$((res*height/width))
fi
done
((index++))
# store file and type for later use
# Use file modification time + size for fast, reliable cache key
mdx="${file##*/}_$(stat -c '%Y_%s' "$file" 2>/dev/null || stat -f '%m_%z' "$file" 2>/dev/null)"
gallery_files+=("$file")
gallery_nav+=("$i")
gallery_url+=("$image_url")
gallery_md5+=("$mdx")
gallery_maxwidth+=("$maxwidth")
gallery_maxheight+=("$maxheight")
done < <(find "$dir" -maxdepth 1 -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif" -o -iname "*.bmp" -o -iname "*.webp" \) ! -path "$dir*/_*" | sort $image_sort_option)
nav_count[i]="$index"
done
# build html file for each gallery
template=$(cat "$theme_dir/template.html" | tr -d '\n' | sed 's/>[[:space:]]*</></g')
post_template=$(cat "$theme_dir/post-template.html" | tr -d '\n' | sed 's/>[[:space:]]*</></g')
# Minify navigation templates to single line for sed compatibility
# This allows the template files to be nicely formatted while avoiding sed multi-line issues
nav_branch_template=$(cat "$theme_dir/nav-branch-template.html" | tr -d '\n' | sed 's/>[[:space:]]*</></g')
nav_branch_empty_template=$(cat "$theme_dir/nav-branch-empty-template.html" | tr -d '\n' | sed 's/>[[:space:]]*</></g')
nav_leaf_template=$(cat "$theme_dir/nav-leaf-template.html" | tr -d '\n' | sed 's/>[[:space:]]*</></g')
nav_column_template=$(cat "$theme_dir/nav-column-template.html" | tr -d '\n' | sed 's/>[[:space:]]*</></g')
# Extract EXIF placeholders from post template once (optimization)
exif_placeholders_global=$(echo "$post_template" | grep -o '{{exif_[^}]*}}' | sed 's/{{exif_\([^:}]*\)[^}]*}}/\1/' | sort -u)
gallery_index=0
# Build main navigation ONCE (not for every gallery)
printf "\nBuilding Navigation"
# Build hierarchical navigation using depth-first search (adapted from Jack's algorithm)
navigation=""
# Find root column parent once (if exists) and process it immediately
root_column_parent=-1
for k in "${!paths[@]}"; do
if [ "${nav_depth[k]}" = 0 ] && [ "${nav_type[k]}" = 2 ]; then
root_column_parent="$k"
# Skip root if show_root_in_nav is false
if [ "$show_root_in_nav" != "false" ]; then
# Render root column immediately
nav_item="$nav_column_template"
nav_item=$(template "$nav_item" text "${nav_name[k]}")
nav_item=$(template "$nav_item" children "{{marker$k}}")
navigation+="$nav_item"
fi
break
fi
done
# Create markers for template replacement in hierarchical structure
depth=1 # Start at 1, root (depth 0) was handled above
prevdepth=0
remaining="${#paths[@]}"
parent=-1
while [ "$remaining" -gt 0 ]; do
items_processed_this_depth=0
for j in "${!paths[@]}"; do
if [ "${nav_depth[j]}" = "$depth" ]; then
# Skip root gallery if show_root_in_nav is false
if [ "${paths[j]}" = "$in_dir" ] && [ "$show_root_in_nav" = "false" ]; then
((remaining--))
continue
fi
items_processed_this_depth=1
if [ "$root_column_parent" -ge 0 ] && [ "${nav_depth[j]}" = 1 ]; then
# Depth 1 items with root column parent - nest them inside the column
nav_item="$nav_leaf_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" uri "{{basepath}}${nav_url[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
substring="$nav_item{{marker$root_column_parent}}"
navigation=$(template "$navigation" "marker$root_column_parent" "$substring")
((remaining--))
elif [ "$parent" -lt 0 ] && [ "${nav_depth[j]}" = 1 ]; then
# Top level items (depth 1)
if [ "${nav_type[j]}" = 2 ]; then
# Column header (type 2)
nav_item="$nav_column_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
navigation+="$nav_item"
elif [ "${nav_type[j]}" = 0 ]; then
# Structure node (branch with or without own gallery)
if [ "${nav_has_images[j]}" -gt 0 ]; then
# Branch with own gallery - use link
nav_item="$nav_branch_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" uri "{{basepath}}${nav_url[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
else
# Branch without own gallery - use span only
nav_item="$nav_branch_empty_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
fi
navigation+="$nav_item"
else
# Gallery node (has own page)
nav_item="$nav_leaf_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" uri "{{basepath}}${nav_url[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
navigation+="$nav_item"
fi
((remaining--))
elif [ "${nav_depth[j]}" = "$depth" ]; then
# Nested items - find correct parent by path
parent=-1
current_path="${paths[j]}"
parent_path=$(dirname "$current_path")
# Find parent index by matching path
for k in "${!paths[@]}"; do
if [ "${paths[k]}" = "$parent_path" ]; then
parent="$k"
break
fi
done
if [ "$parent" -lt 0 ]; then
# Parent not found, skip this item
((remaining--))
continue
fi
# Replace parent marker with this item
if [ "${nav_type[j]}" = 2 ]; then
# Column (shouldn't happen at nested level, but handle it)
nav_item="$nav_column_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
substring="$nav_item{{marker$parent}}"
elif [ "${nav_type[j]}" = 0 ]; then
# Structure node (branch with or without own gallery)
if [ "${nav_has_images[j]}" -gt 0 ]; then
# Branch with own gallery - use link
nav_item="$nav_branch_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" uri "{{basepath}}${nav_url[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
else
# Branch without own gallery - use span only
nav_item="$nav_branch_empty_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
fi
substring="$nav_item{{marker$parent}}"
else
# Gallery node
nav_item="$nav_leaf_template"
nav_item=$(template "$nav_item" text "${nav_name[j]}")
nav_item=$(template "$nav_item" uri "{{basepath}}${nav_url[j]}")
nav_item=$(template "$nav_item" children "{{marker$j}}")
substring="$nav_item{{marker$parent}}"
fi
navigation=$(template "$navigation" "marker$parent" "$substring")
((remaining--))
fi
fi
done
# If no items were processed at this depth, break the loop
if [ "$items_processed_this_depth" = 0 ]; then
break
fi
((prevdepth++))
((depth++))
done
# Clean up remaining placeholders (markers for children, active class)
# Note: {{basepath}} is kept for later replacement by template_render()
navigation=$(echo "$navigation" | sed 's/{{marker[^}]*}}//g; s/{{active}}//g')
# Pre-extract all EXIF data in batch for massive performance boost
printf "\nExtracting EXIF data in batch..."
# Create persistent cache directories
cache_dir="$topdir/.cache/$project"
exif_cache_dir="$cache_dir/exif"
html_cache_dir="$cache_dir/html"
mkdir -p "$exif_cache_dir" "$html_cache_dir"
# Check which images need EXIF extraction
images_to_process=()
for i in "${!gallery_files[@]}"; do
file_path="${gallery_files[i]}"
file_cache_key="${gallery_md5[i]}" # Already contains timestamp+size
exif_cache_path="$exif_cache_dir/$file_cache_key.json"
# Check if EXIF cache exists and is current
if [ ! -f "$exif_cache_path" ]; then
images_to_process+=("$file_path")
fi
done
# Extract EXIF data only for changed/new images
if [ ${#images_to_process[@]} -gt 0 ]; then
printf " (%d new/changed)" "${#images_to_process[@]}"
# Process in chunks to avoid memory issues with large datasets
chunk_size=100
for ((i=0; i<${#images_to_process[@]}; i+=chunk_size)); do
chunk_files=()
# Prepare chunk
for ((j=i; j<i+chunk_size && j<${#images_to_process[@]}; j++)); do
chunk_files+=("${images_to_process[j]}")
done
# Extract EXIF for chunk
if [ ${#chunk_files[@]} -gt 0 ]; then
# Extract to temporary file
temp_json="$tmpdir/exif_chunk_$i.json"
exiftool -j -s2 "${chunk_files[@]}" > "$temp_json" 2>/dev/null
# Split JSON by image and cache individually using bash/grep/sed
for file_path in "${chunk_files[@]}"; do
filename=$(basename "$file_path")
# Find cache path for this file
for k in "${!gallery_files[@]}"; do
if [ "${gallery_files[k]}" = "$file_path" ]; then
file_cache_key="${gallery_md5[k]}"
exif_cache_path="$exif_cache_dir/$file_cache_key.json"
break
fi
done
# Extract this image's EXIF from chunk JSON using jq
# Find the JSON object for this filename and save directly as object
jq --arg filename "$filename" '.[] | select(.FileName == $filename)' "$temp_json" > "$exif_cache_path"
done
rm -f "$temp_json"
fi
done
else
printf " (all cached)"
fi
# Combine all cached EXIF data into working file
exif_cache_file="$tmpdir/exif_data.json"
echo "[" > "$exif_cache_file"
first=true
for i in "${!gallery_files[@]}"; do
file_cache_key="${gallery_md5[i]}"
exif_cache_path="$exif_cache_dir/$file_cache_key.json"
if [ -f "$exif_cache_path" ]; then
if [ "$first" = true ]; then
first=false
else
echo "," >> "$exif_cache_file"
fi
# Extract the image object (remove outer array brackets)
sed '1d;$d' "$exif_cache_path" >> "$exif_cache_file"
fi
done
echo "]" >> "$exif_cache_file"
printf " ✅"
printf "\nBuilding HTML"
# Count galleries to build (skip structure directories and columns)
total_galleries=0
for i in "${!paths[@]}"
do
# Skip columns (type 2) and structures without images
if [ "${nav_type[i]}" = 2 ]; then
continue
fi
if [ "${nav_type[i]}" -ge 1 ] || [ "${nav_count[i]}" -gt 0 ]
then
((total_galleries++))
fi
done
current_gallery=0
for i in "${!paths[@]}"
do
# Skip columns (type 2) and structure directories without images
if [ "${nav_type[i]}" = 2 ]; then
continue
fi
if [ "${nav_type[i]}" -lt 1 ] && [ "${nav_count[i]}" -le 0 ]
then
continue
fi
((current_gallery++))
# Display gallery name with progress counter
if [ -z "${nav_url[i]}" ]; then
printf "\n [$current_gallery/$total_galleries] ${nav_name[i]} (${nav_count[i]} files)"
else
printf "\n [$current_gallery/$total_galleries] ${nav_name[i]} (${nav_count[i]} files)"
fi
if [ "${nav_count[i]}" -lt 0 ] || [ "${nav_count[i]}" -gt 1000 ]; then
echo "ERROR: Invalid nav_count[${i}] = ${nav_count[i]}"
continue
fi
html="$template"
gallery_metadata=""
if [ -e "${paths[i]}/$metadata_file" ]
then
gallery_metadata=$(cat "${paths[i]}/$metadata_file")
fi
# Process gallery content.md if it exists
gallery_content_body=""
gallery_content_file="${paths[i]}/content.md"
if [ -f "$gallery_content_file" ] && [ -s "$gallery_content_file" ]
then
# Read content.md
gallery_content_text=$(cat "$gallery_content_file" | tr -d $'\r')
gallery_content_text=${gallery_content_text%$'\n'}
# Check for YAML metadata block (between --- lines)
metaline=$(echo "$gallery_content_text" | grep -n -m 2 -- "^---$" | tail -1 | cut -d ':' -f1)
if [ "$metaline" ]
then
# YAML block exists - extract content (skip metadata block)
sumlines=$(echo "$gallery_content_text" | wc -l)
taillines=$((sumlines-metaline))
gallery_content_body=$(echo "$gallery_content_text" | tail -n "$taillines")
else
# No YAML block - everything is content
gallery_content_body="$gallery_content_text"
fi
# Parse Markdown to HTML (same way Jack does it for posts)
if command -v perl >/dev/null 2>&1
then
gallery_content_body=$(perl "$scriptdir/markdown/markdown.pl" --html4tags <(echo "$gallery_content_body"))
fi
fi
# Set gallerybody variable for Mustache section
# Will be truthy only if content.md exists and has content
if [ -n "$gallery_content_body" ]; then
# Collapse multi-line HTML to single line (like expose.sh does for all templates)
template_set "gallerybody" "$(printf '%s' "$gallery_content_body" | tr -d '\n')"
else
template_set "gallerybody" ""
fi
# Set images variable for Mustache section - only render gallery if images exist
if [ "${nav_count[i]}" -gt 0 ]; then
template_set "images" "yes"
else
template_set "images" ""
fi
j=0
while [ "$j" -lt "${nav_count[i]}" ]
do
k=$((j+1))
file_path="${gallery_files[gallery_index]}"
# try to find a text file with the same name
filename=$(basename "$file_path")
printf "\n $filename"
filename="${filename%.*}"
# Cache directories are created earlier in the script
textfile=$(find "$in_dir/$filename".txt "$in_dir/$filename".md ! -path "$file_path" -print -quit 2>/dev/null)
metadata=""
content=""
if [ ! -e "$html_cache_dir/${gallery_md5[gallery_index]}" ] || [ "$no_html_cache" = true ]
then
if LC_ALL=C file "$textfile" | grep -q text
then
# if there are two lines "---", the lines preceding the second "---" are assumed to be metadata
text=$(cat "$textfile" | tr -d $'\r')
text=${text%$'\n'}
metaline=$(echo "$text" | grep -n -m 2 -- "^---$" | tail -1 | cut -d ':' -f1)
if [ "$metaline" ]
then
sumlines=$(echo "$text" | wc -l)
taillines=$((sumlines-metaline))
metadata=$(head -n "$metaline" "$textfile")
content=$(tail -n "$taillines" "$textfile")
else
metadata=""
content=$(echo "$text")
fi
fi
exif_metadata=""
# Extract only EXIF data that's actually used in templates
filename=$(basename "$file_path")
# Use pre-extracted EXIF placeholders (optimization)
if [ -n "$exif_placeholders_global" ]; then
# Find cache file for this image
cache_file=""
for k in "${!gallery_files[@]}"; do
if [ "$(basename "${gallery_files[k]}")" = "$filename" ]; then
file_cache_key="${gallery_md5[k]}"
cache_file="$exif_cache_dir/$file_cache_key.json"
break
fi
done
if [ -f "$cache_file" ]; then
# Extract all needed fields in one jq call
fields_query=""
old_IFS="$IFS"
IFS=$'\n'
for field in $exif_placeholders_global; do
if [ -n "$fields_query" ]; then
fields_query="$fields_query, "
fi
fields_query="$fields_query\"$field\": (.${field} // empty)"
done
IFS="$old_IFS"
# Get all values in one jq call
exif_data=$(jq -r "{$fields_query}" "$cache_file" 2>/dev/null)
# Parse the result and build metadata
old_IFS="$IFS"
IFS=$'\n'
for field in $exif_placeholders_global; do
value=$(echo "$exif_data" | jq -r --arg field "$field" '.[$field] // empty' 2>/dev/null)
if [ -n "$value" ] && [ "$value" != "null" ]; then
exif_metadata+="exif_$field:$value"$'\n'
fi
done
IFS="$old_IFS"
fi
fi
metadata+=$'\n'
metadata+="$gallery_metadata"
metadata+=$'\n'
metadata+="$exif_metadata"
metadata+=$'\n'
# if perl available, pass content through markdown parser
if command -v perl >/dev/null 2>&1
then
content=$(perl "$scriptdir/markdown/markdown.pl" --html4tags <(echo "$content"))
fi
# write to post template and collect all variables for batch processing
post="$post_template"
# Collect all template variables
template_vars=()
template_vars+=("index:$k")
template_vars+=("post:$content")
# Process metadata and collect variables
while read line
do
key=$(echo "$line" | cut -d ':' -f1 | tr -d $'\r\n' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
value=$(echo "$line" | cut -d ':' -f2- | tr -d $'\r\n' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
colon=$(echo "$line" | grep ':')
if [ "$key" ] && [ "$value" ] && [ "$colon" ]
then
if [ "$key" = "exif_LensModel" ]; then
value=$(echo $value | sed 's/ (.*)//')
elif [ "$key" = "exif_Model" ]; then
value=$(echo $value| sed -e 's/ILCE-7M4/α 7 IV/' -e 's/ILCE-7M3/α 7 III/' -e 's/ILCE-7M2/α 7 II/' -e 's/ILCE-7/α 7/' -e 's/ILCE-7RM5/α 7R V/' -e 's/ILCE-7RM4/α 7R IV/' -e 's/ILCE-7RM3/α 7R III/' -e 's/ILCE-7RM2/α 7R II/' -e 's/ILCE-7R/α 7R/' -e 's/ILCE-7SM3/α 7S III/' -e 's/ILCE-7SM2/α 7S II/' -e 's/ILCE-7S/α 7S/')
fi
template_vars+=("$key:$value")
fi
done < <(echo "$metadata")
# Add image parameters - use URL hash for consistent ID
template_vars+=("imagemd5:${gallery_url[gallery_index]}")
template_vars+=("imageurl:${gallery_url[gallery_index]}")
template_vars+=("imagewidth:${gallery_maxwidth[gallery_index]}")
template_vars+=("imageheight:${gallery_maxheight[gallery_index]}")
# Add gallery-level variables that are needed in post templates
if [ "${nav_depth[i]}" = 0 ]; then
basepath="./"
else
basepath=$(yes "../" 2>/dev/null | head -n ${nav_depth[i]} | tr -d '\n')
fi
if [ "${paths[i]}" = "$in_dir" ]; then
resourcepath="home/"
else
resourcepath=""
fi
template_vars+=("basepath:$basepath")