summaryrefslogtreecommitdiff
path: root/main.go
blob: 04bc307d04a2b69f2cadcf434d519ccca7f8a414 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
package main

import (
	"bufio"
	"bytes"
	"context"
	"crypto/sha1"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"html/template"
	"image"
	"image/color"
	"io"
	"io/fs"
	"log"
	"math"
	"math/bits"
	"net"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"regexp"
	"runtime"
	"slices"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/mattn/go-sqlite3"
	"golang.org/x/image/draw"
	"golang.org/x/image/webp"
)

var (
	db               *sql.DB // sqlite database
	galleryDirectory string  // gallery directory

	// taskSemaphore limits parallel computations.
	taskSemaphore semaphore
)

const (
	nameOfDB        = "gallery.db"
	nameOfImageRoot = "images"
	nameOfThumbRoot = "thumbs"
)

func hammingDistance(a, b int64) int {
	return bits.OnesCount64(uint64(a) ^ uint64(b))
}

func init() {
	sql.Register("sqlite3_custom", &sqlite3.SQLiteDriver{
		ConnectHook: func(conn *sqlite3.SQLiteConn) error {
			return conn.RegisterFunc("hamming", hammingDistance, true /*pure*/)
		},
	})
}

func openDB(directory string) error {
	var err error
	db, err = sql.Open("sqlite3_custom", "file:"+filepath.Join(directory,
		nameOfDB+"?_foreign_keys=1&_busy_timeout=1000"))
	galleryDirectory = directory
	return err
}

func imagePath(sha1 string) string {
	return filepath.Join(galleryDirectory,
		nameOfImageRoot, sha1[:2], sha1)
}

func thumbPath(sha1 string) string {
	return filepath.Join(galleryDirectory,
		nameOfThumbRoot, sha1[:2], sha1+".webp")
}

func dbCollectStrings(query string, a ...any) ([]string, error) {
	rows, err := db.Query(query, a...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	result := []string{}
	for rows.Next() {
		var s string
		if err := rows.Scan(&s); err != nil {
			return nil, err
		}
		result = append(result, s)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return result, nil
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

func idForDirectoryPath(tx *sql.Tx, path []string, create bool) (int64, error) {
	var parent sql.NullInt64
	for _, name := range path {
		if err := tx.QueryRow(`SELECT id FROM node
			WHERE parent IS ? AND name = ? AND sha1 IS NULL`,
			parent, name).Scan(&parent); err == nil {
			continue
		} else if !errors.Is(err, sql.ErrNoRows) {
			return 0, err
		} else if !create {
			return 0, err
		}

		// This fails when trying to override a leaf node.
		// That needs special handling.
		if result, err := tx.Exec(
			`INSERT INTO node(parent, name) VALUES (?, ?)`,
			parent, name); err != nil {
			return 0, err
		} else if id, err := result.LastInsertId(); err != nil {
			return 0, err
		} else {
			parent = sql.NullInt64{Int64: id, Valid: true}
		}
	}
	return parent.Int64, nil
}

func decodeWebPath(path string) []string {
	// Relative paths could be handled differently,
	// but right now, they're assumed to start at the root.
	result := []string{}
	for _, crumb := range strings.Split(path, "/") {
		if crumb != "" {
			result = append(result, crumb)
		}
	}
	return result
}

// --- Semaphore ---------------------------------------------------------------

type semaphore chan struct{}

func newSemaphore(size int) semaphore { return make(chan struct{}, size) }
func (s semaphore) release()          { <-s }

func (s semaphore) acquire(ctx context.Context) error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	case s <- struct{}{}:
	}

	// Give priority to context cancellation.
	select {
	case <-ctx.Done():
		s.release()
		return ctx.Err()
	default:
	}
	return nil
}

// --- Progress bar ------------------------------------------------------------

type progressBar struct {
	sync.Mutex
	current int
	target  int
}

func newProgressBar(target int) *progressBar {
	pb := &progressBar{current: 0, target: target}
	pb.Update()
	return pb
}

func (pb *progressBar) Stop() {
	// The minimum thing that works: just print a newline.
	os.Stdout.WriteString("\n")
}

func (pb *progressBar) Update() {
	if pb.target < 0 {
		fmt.Printf("\r%d/?", pb.current)
		return
	}

	var fraction int
	if pb.target != 0 {
		fraction = int(float32(pb.current) / float32(pb.target) * 100)
	}

	target := fmt.Sprintf("%d", pb.target)
	fmt.Printf("\r%*d/%s (%2d%%)", len(target), pb.current, target, fraction)
}

func (pb *progressBar) Step() {
	pb.Lock()
	defer pb.Unlock()

	pb.current++
	pb.Update()
}

func (pb *progressBar) Interrupt(callback func()) {
	pb.Lock()
	defer pb.Unlock()
	pb.Stop()
	defer pb.Update()

	callback()
}

// --- Parallelization ---------------------------------------------------------

type parallelFunc func(item string) (message string, err error)

// parallelize runs the callback in parallel on a list of strings,
// reporting progress and any non-fatal messages.
func parallelize(strings []string, callback parallelFunc) error {
	pb := newProgressBar(len(strings))
	defer pb.Stop()

	ctx, cancel := context.WithCancelCause(context.Background())
	wg := sync.WaitGroup{}
	for _, item := range strings {
		if taskSemaphore.acquire(ctx) != nil {
			break
		}

		wg.Add(1)
		go func(item string) {
			defer taskSemaphore.release()
			defer wg.Done()
			if message, err := callback(item); err != nil {
				cancel(err)
			} else if message != "" {
				pb.Interrupt(func() { log.Printf("%s: %s\n", item, message) })
			}
			pb.Step()
		}(item)
	}
	wg.Wait()
	if ctx.Err() != nil {
		return context.Cause(ctx)
	}
	return nil
}

// --- Initialization ----------------------------------------------------------

// cmdInit initializes a "gallery directory" that contains gallery.sqlite,
// images, thumbs.
func cmdInit(args []string) error {
	if len(args) != 1 {
		return errors.New("usage: GD")
	}

	if err := openDB(args[0]); err != nil {
		return err
	}
	if _, err := db.Exec(initializeSQL); err != nil {
		return err
	}

	// XXX: There's technically no reason to keep images as symlinks,
	// we might just keep absolute paths in the database as well.
	if err := os.MkdirAll(
		filepath.Join(galleryDirectory, nameOfImageRoot), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(
		filepath.Join(galleryDirectory, nameOfThumbRoot), 0755); err != nil {
		return err
	}
	return nil
}

// --- Web ---------------------------------------------------------------------

var hashRE = regexp.MustCompile(`^/.*?/([0-9a-f]{40})$`)
var staticHandler http.Handler

var page = template.Must(template.New("/").Parse(`<!DOCTYPE html><html><head>
	<title>Gallery</title>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel=stylesheet href=style.css>
</head><body>
	<noscript>This is a web application, and requires Javascript.</noscript>
	<script src=mithril.js></script>
	<script src=gallery.js></script>
</body></html>`))

func handleRequest(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		staticHandler.ServeHTTP(w, r)
		return
	}
	if err := page.Execute(w, nil); err != nil {
		log.Println(err)
	}
}

func handleImages(w http.ResponseWriter, r *http.Request) {
	if m := hashRE.FindStringSubmatch(r.URL.Path); m == nil {
		http.NotFound(w, r)
	} else {
		http.ServeFile(w, r, imagePath(m[1]))
	}
}

func handleThumbs(w http.ResponseWriter, r *http.Request) {
	if m := hashRE.FindStringSubmatch(r.URL.Path); m == nil {
		http.NotFound(w, r)
	} else {
		http.ServeFile(w, r, thumbPath(m[1]))
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

func getSubdirectories(tx *sql.Tx, parent int64) (names []string, err error) {
	return dbCollectStrings(`SELECT name FROM node
		WHERE IFNULL(parent, 0) = ? AND sha1 IS NULL`, parent)
}

type webEntry struct {
	SHA1     string `json:"sha1"`
	Name     string `json:"name"`
	Modified int64  `json:"modified"`
	ThumbW   int64  `json:"thumbW"`
	ThumbH   int64  `json:"thumbH"`
}

func getSubentries(tx *sql.Tx, parent int64) (entries []webEntry, err error) {
	rows, err := tx.Query(`
		SELECT i.sha1, n.name, n.mtime, IFNULL(i.thumbw, 0), IFNULL(i.thumbh, 0)
		FROM node AS n
		JOIN image AS i ON n.sha1 = i.sha1
		WHERE n.parent = ?`, parent)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	entries = []webEntry{}
	for rows.Next() {
		var e webEntry
		if err = rows.Scan(
			&e.SHA1, &e.Name, &e.Modified, &e.ThumbW, &e.ThumbH); err != nil {
			return nil, err
		}
		entries = append(entries, e)
	}
	return entries, rows.Err()
}

func handleAPIBrowse(w http.ResponseWriter, r *http.Request) {
	var params struct {
		Path string
	}
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var result struct {
		Subdirectories []string   `json:"subdirectories"`
		Entries        []webEntry `json:"entries"`
	}

	tx, err := db.Begin()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer tx.Rollback()

	parent, err := idForDirectoryPath(tx, decodeWebPath(params.Path), false)
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}

	result.Subdirectories, err = getSubdirectories(tx, parent)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	result.Entries, err = getSubentries(tx, parent)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Println(err)
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

type webTagNamespace struct {
	Description string           `json:"description"`
	Tags        map[string]int64 `json:"tags"`
}

func getTags(nsID int64) (result map[string]int64, err error) {
	rows, err := db.Query(`
		SELECT t.name, COUNT(ta.tag) AS count
		FROM tag AS t
		LEFT JOIN tag_assignment AS ta ON t.id = ta.tag
		WHERE t.space = ?
		GROUP BY t.id`, nsID)
	if err != nil {
		return
	}
	defer rows.Close()

	result = make(map[string]int64)
	for rows.Next() {
		var (
			name  string
			count int64
		)
		if err = rows.Scan(&name, &count); err != nil {
			return
		}
		result[name] = count
	}
	return result, rows.Err()
}

func getTagNamespaces(match *string) (
	result map[string]webTagNamespace, err error) {
	var rows *sql.Rows
	if match != nil {
		rows, err = db.Query(`SELECT id, name, IFNULL(description, '')
			FROM tag_space WHERE name = ?`, *match)
	} else {
		rows, err = db.Query(`SELECT id, name, IFNULL(description, '')
			FROM tag_space`)
	}
	if err != nil {
		return
	}
	defer rows.Close()

	result = make(map[string]webTagNamespace)
	for rows.Next() {
		var (
			id   int64
			name string
			ns   webTagNamespace
		)
		if err = rows.Scan(&id, &name, &ns.Description); err != nil {
			return
		}
		if ns.Tags, err = getTags(id); err != nil {
			return
		}
		result[name] = ns
	}
	return result, rows.Err()
}

func handleAPITags(w http.ResponseWriter, r *http.Request) {
	var params struct {
		Namespace *string
	}
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	result, err := getTagNamespaces(params.Namespace)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Println(err)
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

type webDuplicateImage struct {
	SHA1       string `json:"sha1"`
	ThumbW     int64  `json:"thumbW"`
	ThumbH     int64  `json:"thumbH"`
	Occurences int64  `json:"occurences"`
}

// A hamming distance of zero (direct dhash match) will be more than sufficient.
const duplicatesCTE = `WITH
	duplicated(dhash, count) AS (
		SELECT dhash, COUNT(*) AS count FROM image
		WHERE dhash IS NOT NULL
		GROUP BY dhash HAVING count > 1
	),
	multipathed(sha1, count) AS (
		SELECT n.sha1, COUNT(*) AS count FROM node AS n
		JOIN image AS i ON i.sha1 = n.sha1
		WHERE i.dhash IS NULL
		OR i.dhash NOT IN (SELECT dhash FROM duplicated)
		GROUP BY n.sha1 HAVING count > 1
	)
`

func getDuplicatesSimilar(stmt *sql.Stmt, dhash int64) (
	result []webDuplicateImage, err error) {
	rows, err := stmt.Query(dhash)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	result = []webDuplicateImage{}
	for rows.Next() {
		var image webDuplicateImage
		if err = rows.Scan(&image.SHA1, &image.ThumbW, &image.ThumbH,
			&image.Occurences); err != nil {
			return nil, err
		}
		result = append(result, image)
	}
	return result, rows.Err()
}

func getDuplicates1(result [][]webDuplicateImage) (
	[][]webDuplicateImage, error) {
	stmt, err := db.Prepare(`
		SELECT i.sha1, IFNULL(i.thumbw, 0), IFNULL(i.thumbh, 0),
			COUNT(*) AS occurences
		FROM image AS i
		JOIN node AS n ON n.sha1 = i.sha1
		WHERE i.dhash = ?
		GROUP BY n.sha1`)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := db.Query(duplicatesCTE + `SELECT dhash FROM duplicated`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var (
			group []webDuplicateImage
			dhash int64
		)
		if err = rows.Scan(&dhash); err != nil {
			return nil, err
		}
		if group, err = getDuplicatesSimilar(stmt, dhash); err != nil {
			return nil, err
		}
		result = append(result, group)
	}
	return result, rows.Err()
}

func getDuplicates2(result [][]webDuplicateImage) (
	[][]webDuplicateImage, error) {
	stmt, err := db.Prepare(`
		SELECT i.sha1, IFNULL(i.thumbw, 0), IFNULL(i.thumbh, 0),
			COUNT(*) AS occurences
		FROM image AS i
		JOIN node AS n ON n.sha1 = i.sha1
		WHERE i.sha1 = ?
		GROUP BY n.sha1`)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := db.Query(duplicatesCTE + `SELECT sha1 FROM multipathed`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var (
			image webDuplicateImage
			sha1  string
		)
		if err = rows.Scan(&sha1); err != nil {
			return nil, err
		}
		if err := stmt.QueryRow(sha1).Scan(&image.SHA1,
			&image.ThumbW, &image.ThumbH, &image.Occurences); err != nil {
			return nil, err
		}
		result = append(result, []webDuplicateImage{image})
	}
	return result, rows.Err()
}

func handleAPIDuplicates(w http.ResponseWriter, r *http.Request) {
	var params struct{}
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var (
		result = [][]webDuplicateImage{}
		err    error
	)
	if result, err = getDuplicates1(result); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if result, err = getDuplicates2(result); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Println(err)
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

type webOrphanImage struct {
	SHA1   string `json:"sha1"`
	ThumbW int64  `json:"thumbW"`
	ThumbH int64  `json:"thumbH"`
	Tags   int64  `json:"tags"`
}

type webOrphan struct {
	webOrphanImage
	LastPath    string          `json:"lastPath"`
	Replacement *webOrphanImage `json:"replacement"`
}

func getOrphanReplacement(webPath string) (*webOrphanImage, error) {
	tx, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()

	path := decodeWebPath(webPath)
	if len(path) == 0 {
		return nil, nil
	}

	parent, err := idForDirectoryPath(tx, path[:len(path)-1], false)
	if err != nil {
		return nil, err
	}

	var image webOrphanImage
	err = db.QueryRow(`SELECT i.sha1,
		IFNULL(i.thumbw, 0), IFNULL(i.thumbh, 0), COUNT(ta.sha1) AS tags
		FROM node AS n
		JOIN image AS i ON n.sha1 = i.sha1
		LEFT JOIN tag_assignment AS ta ON n.sha1 = ta.sha1
		WHERE n.parent = ? AND n.name = ?
		GROUP BY n.sha1`, parent, path[len(path)-1]).Scan(
		&image.SHA1, &image.ThumbW, &image.ThumbH, &image.Tags)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &image, nil
}

func getOrphans() (result []webOrphan, err error) {
	rows, err := db.Query(`SELECT o.sha1, o.path,
		IFNULL(i.thumbw, 0), IFNULL(i.thumbh, 0), COUNT(ta.sha1) AS tags
		FROM orphan AS o
		JOIN image AS i ON o.sha1 = i.sha1
		LEFT JOIN tag_assignment AS ta ON o.sha1 = ta.sha1
		GROUP BY o.sha1`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	result = []webOrphan{}
	for rows.Next() {
		var orphan webOrphan
		if err = rows.Scan(&orphan.SHA1, &orphan.LastPath,
			&orphan.ThumbW, &orphan.ThumbH, &orphan.Tags); err != nil {
			return nil, err
		}

		orphan.Replacement, err = getOrphanReplacement(orphan.LastPath)
		if err != nil {
			return nil, err
		}

		result = append(result, orphan)
	}
	return result, rows.Err()
}

func handleAPIOrphans(w http.ResponseWriter, r *http.Request) {
	var params struct{}
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	result, err := getOrphans()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Println(err)
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

func getImageDimensions(sha1 string) (w int64, h int64, err error) {
	err = db.QueryRow(`SELECT width, height FROM image WHERE sha1 = ?`,
		sha1).Scan(&w, &h)
	return
}

func getImagePaths(sha1 string) (paths []string, err error) {
	rows, err := db.Query(`WITH RECURSIVE paths(parent, path) AS (
		SELECT parent, name AS path FROM node WHERE sha1 = ?
		UNION ALL
		SELECT n.parent, n.name || '/' || p.path
		FROM node AS n JOIN paths AS p ON n.id = p.parent
	) SELECT path FROM paths WHERE parent IS NULL`, sha1)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	paths = []string{}
	for rows.Next() {
		var path string
		if err := rows.Scan(&path); err != nil {
			return nil, err
		}
		paths = append(paths, path)
	}
	return paths, rows.Err()
}

func getImageTags(sha1 string) (map[string]map[string]float32, error) {
	rows, err := db.Query(`
		SELECT ts.name, t.name, ta.weight FROM tag_assignment AS ta
		JOIN tag AS t ON t.id = ta.tag
		JOIN tag_space AS ts ON ts.id = t.space
		WHERE ta.sha1 = ?`, sha1)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	result := make(map[string]map[string]float32)
	for rows.Next() {
		var (
			space, tag string
			weight     float32
		)
		if err := rows.Scan(&space, &tag, &weight); err != nil {
			return nil, err
		}

		tags := result[space]
		if tags == nil {
			tags = make(map[string]float32)
			result[space] = tags
		}
		tags[tag] = weight
	}
	return result, rows.Err()
}

func handleAPIInfo(w http.ResponseWriter, r *http.Request) {
	var params struct {
		SHA1 string
	}
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var result struct {
		Width  int64                         `json:"width"`
		Height int64                         `json:"height"`
		Paths  []string                      `json:"paths"`
		Tags   map[string]map[string]float32 `json:"tags"`
	}

	var err error
	result.Width, result.Height, err = getImageDimensions(params.SHA1)
	if errors.Is(err, sql.ErrNoRows) {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	} else if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	result.Paths, err = getImagePaths(params.SHA1)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	result.Tags, err = getImageTags(params.SHA1)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Println(err)
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

type webSimilarImage struct {
	SHA1        string   `json:"sha1"`
	PixelsRatio float32  `json:"pixelsRatio"`
	ThumbW      int64    `json:"thumbW"`
	ThumbH      int64    `json:"thumbH"`
	Paths       []string `json:"paths"`
}

func getSimilar(sha1 string, dhash int64, pixels int64, distance int) (
	result []webSimilarImage, err error) {
	// For distance ∈ {0, 1}, this query is quite inefficient.
	// In exchange, it's generic.
	//
	// If there's a dhash, there should also be thumbnail dimensions,
	// so not bothering with IFNULL on them.
	rows, err := db.Query(`
		SELECT sha1, width * height, IFNULL(thumbw, 0), IFNULL(thumbh, 0)
		FROM image WHERE sha1 <> ? AND dhash IS NOT NULL
		AND hamming(dhash, ?) = ?`, sha1, dhash, distance)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	result = []webSimilarImage{}
	for rows.Next() {
		var (
			match       webSimilarImage
			matchPixels int64
		)
		if err = rows.Scan(&match.SHA1,
			&matchPixels, &match.ThumbW, &match.ThumbH); err != nil {
			return nil, err
		}
		if match.Paths, err = getImagePaths(match.SHA1); err != nil {
			return nil, err
		}
		match.PixelsRatio = float32(matchPixels) / float32(pixels)
		result = append(result, match)
	}
	return result, rows.Err()
}

func getSimilarGroups(sha1 string, dhash int64, pixels int64,
	output map[string][]webSimilarImage) error {
	var err error
	for distance := 0; distance <= 1; distance++ {
		output[fmt.Sprintf("Perceptual distance %d", distance)], err =
			getSimilar(sha1, dhash, pixels, distance)
		if err != nil {
			return err
		}
	}
	return nil
}

func handleAPISimilar(w http.ResponseWriter, r *http.Request) {
	var params struct {
		SHA1 string
	}
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var result struct {
		Info   webSimilarImage              `json:"info"`
		Groups map[string][]webSimilarImage `json:"groups"`
	}

	result.Info = webSimilarImage{SHA1: params.SHA1, PixelsRatio: 1}
	if paths, err := getImagePaths(params.SHA1); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	} else {
		result.Info.Paths = paths
	}

	var (
		width, height int64
		dhash         sql.NullInt64
	)
	err := db.QueryRow(`
		SELECT width, height, dhash, IFNULL(thumbw, 0), IFNULL(thumbh, 0)
		FROM image WHERE sha1 = ?`, params.SHA1).Scan(&width, &height, &dhash,
		&result.Info.ThumbW, &result.Info.ThumbH)
	if errors.Is(err, sql.ErrNoRows) {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	} else if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	result.Groups = make(map[string][]webSimilarImage)
	if dhash.Valid {
		if err := getSimilarGroups(
			params.SHA1, dhash.Int64, width*height, result.Groups); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Println(err)
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// NOTE: AND will mean MULTIPLY(IFNULL(ta.weight, 0)) per SHA1.
const searchCTE = `WITH
	matches(sha1, thumbw, thumbh, score) AS (
		SELECT i.sha1, i.thumbw, i.thumbh, ta.weight AS score
		FROM tag_assignment AS ta
		JOIN image AS i ON i.sha1 = ta.sha1
		WHERE ta.tag = ?
	),
	supertags(tag) AS (
		SELECT DISTINCT ta.tag
		FROM tag_assignment AS ta
		JOIN matches AS m ON m.sha1 = ta.sha1
	),
	scoredtags(tag, score) AS (
		SELECT st.tag, AVG(IFNULL(ta.weight, 0)) AS score
		FROM supertags AS st, matches AS m
		LEFT JOIN tag_assignment AS ta
		ON ta.sha1 = m.sha1 AND ta.tag = st.tag
		GROUP BY st.tag
	)
`

type webTagMatch struct {
	SHA1   string  `json:"sha1"`
	ThumbW int64   `json:"thumbW"`
	ThumbH int64   `json:"thumbH"`
	Score  float32 `json:"score"`
}

func getTagMatches(tag int64) (matches []webTagMatch, err error) {
	rows, err := db.Query(searchCTE+`
		SELECT sha1, IFNULL(thumbw, 0), IFNULL(thumbh, 0), score
		FROM matches`, tag)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	matches = []webTagMatch{}
	for rows.Next() {
		var match webTagMatch
		if err = rows.Scan(&match.SHA1,
			&match.ThumbW, &match.ThumbH, &match.Score); err != nil {
			return nil, err
		}
		matches = append(matches, match)
	}
	return matches, rows.Err()
}

type webTagRelated struct {
	Tag   string  `json:"tag"`
	Score float32 `json:"score"`
}

func getTagRelated(tag int64) (result map[string][]webTagRelated, err error) {
	rows, err := db.Query(searchCTE+`
		SELECT ts.name, t.name, st.score FROM scoredtags AS st
		JOIN tag AS t ON st.tag = t.id
		JOIN tag_space AS ts ON ts.id = t.space
		ORDER BY st.score DESC`, tag)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	result = make(map[string][]webTagRelated)
	for rows.Next() {
		var (
			space string
			r     webTagRelated
		)
		if err = rows.Scan(&space, &r.Tag, &r.Score); err != nil {
			return nil, err
		}
		result[space] = append(result[space], r)
	}
	return result, rows.Err()
}

func handleAPISearch(w http.ResponseWriter, r *http.Request) {
	var params struct {
		Query string
	}
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var result struct {
		Matches []webTagMatch              `json:"matches"`
		Related map[string][]webTagRelated `json:"related"`
	}

	space, tag, _ := strings.Cut(params.Query, ":")

	var tagID int64
	err := db.QueryRow(`
		SELECT t.id FROM tag AS t
		JOIN tag_space AS ts ON t.space = ts.id
		WHERE ts.name = ? AND t.name = ?`, space, tag).Scan(&tagID)
	if errors.Is(err, sql.ErrNoRows) {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	} else if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if result.Matches, err = getTagMatches(tagID); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if result.Related, err = getTagRelated(tagID); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Println(err)
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// cmdWeb runs a web UI against GD on ADDRESS.
func cmdWeb(args []string) error {
	if len(args) != 2 {
		return errors.New("usage: GD ADDRESS")
	}
	if err := openDB(args[0]); err != nil {
		return err
	}

	address := args[1]

	// This separation is not strictly necessary,
	// but having an elementary level of security doesn't hurt either.
	staticHandler = http.FileServer(http.Dir("public"))

	http.HandleFunc("/", handleRequest)
	http.HandleFunc("/image/", handleImages)
	http.HandleFunc("/thumb/", handleThumbs)
	http.HandleFunc("/api/browse", handleAPIBrowse)
	http.HandleFunc("/api/tags", handleAPITags)
	http.HandleFunc("/api/duplicates", handleAPIDuplicates)
	http.HandleFunc("/api/orphans", handleAPIOrphans)
	http.HandleFunc("/api/info", handleAPIInfo)
	http.HandleFunc("/api/similar", handleAPISimilar)
	http.HandleFunc("/api/search", handleAPISearch)

	host, port, err := net.SplitHostPort(address)
	if err != nil {
		log.Println(err)
	} else if host == "" {
		log.Println("http://" + net.JoinHostPort("localhost", port))
	} else {
		log.Println("http://" + address)
	}

	s := &http.Server{
		Addr:           address,
		ReadTimeout:    60 * time.Second,
		WriteTimeout:   60 * time.Second,
		MaxHeaderBytes: 32 << 10,
	}
	return s.ListenAndServe()
}

// --- Sync --------------------------------------------------------------------

type syncFileInfo struct {
	dbID     int64  // DB node ID, or zero if there was none
	dbParent int64  // where the file was to be stored
	dbName   string // the name under which it was to be stored
	fsPath   string // symlink target
	fsMtime  int64  // last modified Unix timestamp, used a bit like an ID

	err    error  // any processing error
	sha1   string // raw content hash, empty to skip file
	width  int    // image width in pixels
	height int    // image height in pixels
}

type syncContext struct {
	ctx  context.Context
	tx   *sql.Tx
	info chan syncFileInfo
	pb   *progressBar

	stmtOrphan     *sql.Stmt
	stmtDisposeSub *sql.Stmt
	stmtDisposeAll *sql.Stmt
}

func syncPrintf(c *syncContext, format string, v ...any) {
	c.pb.Interrupt(func() { log.Printf(format+"\n", v...) })
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

type syncNode struct {
	dbID    int64
	dbName  string
	dbMtime int64
	dbSHA1  string
}

func (n *syncNode) dbIsDir() bool { return n.dbSHA1 == "" }

type syncFile struct {
	fsName  string
	fsMtime int64
	fsIsDir bool
}

type syncPair struct {
	db *syncNode
	fs *syncFile
}

// syncGetNodes returns direct children of a DB node, ordered by name.
// SQLite, like Go, compares strings byte-wise by default.
func syncGetNodes(tx *sql.Tx, dbParent int64) (nodes []syncNode, err error) {
	// This works even for the root, which doesn't exist as a DB node.
	rows, err := tx.Query(`SELECT id, name, IFNULL(mtime, 0), IFNULL(sha1, '')
		FROM node WHERE IFNULL(parent, 0) = ? ORDER BY name`, dbParent)
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var node syncNode
		if err = rows.Scan(&node.dbID,
			&node.dbName, &node.dbMtime, &node.dbSHA1); err != nil {
			return
		}
		nodes = append(nodes, node)
	}
	return nodes, rows.Err()
}

// syncGetFiles returns direct children of a FS directory, ordered by name.
func syncGetFiles(fsPath string) (files []syncFile, err error) {
	dir, err := os.Open(fsPath)
	if err != nil {
		return
	}
	defer dir.Close()

	entries, err := dir.ReadDir(0)
	if err != nil {
		return
	}

	for _, entry := range entries {
		info, err := entry.Info()
		if err != nil {
			return files, err
		}

		files = append(files, syncFile{
			fsName:  entry.Name(),
			fsMtime: info.ModTime().Unix(),
			fsIsDir: entry.IsDir(),
		})
	}
	sort.Slice(files,
		func(a, b int) bool { return files[a].fsName < files[b].fsName })
	return
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

func syncIsImage(path string) (bool, error) {
	out, err := exec.Command("xdg-mime", "query", "filetype", path).Output()
	if err != nil {
		return false, err
	}

	return bytes.HasPrefix(out, []byte("image/")), nil
}

func syncPingImage(path string) (int, int, error) {
	out, err := exec.Command("identify", "-limit", "thread", "1", "-ping",
		"-format", "%w %h", path+"[0]").Output()
	if err != nil {
		return 0, 0, err
	}

	var w, h int
	_, err = fmt.Fscanf(bytes.NewReader(out), "%d %d", &w, &h)
	return w, h, err
}

func syncProcess(c *syncContext, info *syncFileInfo) error {
	// Skip videos, which ImageMagick can process, but we don't want it to,
	// so that they're not converted 1:1 to WebP.
	pathIsImage, err := syncIsImage(info.fsPath)
	if err != nil {
		return err
	}
	if !pathIsImage {
		return nil
	}

	info.width, info.height, err = syncPingImage(info.fsPath)
	if err != nil {
		return err
	}

	f, err := os.Open(info.fsPath)
	if err != nil {
		return err
	}
	defer f.Close()

	// We could make this at least somewhat interruptible by c.ctx,
	// though it would still work poorly.
	hash := sha1.New()
	_, err = io.CopyBuffer(hash, f, make([]byte, 65536))
	if err != nil {
		return err
	}

	info.sha1 = hex.EncodeToString(hash.Sum(nil))
	return nil
}

// syncEnqueue runs file scanning, which can be CPU and I/O expensive,
// in parallel. The goroutine only touches the filesystem, read-only.
func syncEnqueue(c *syncContext, info syncFileInfo) error {
	if err := taskSemaphore.acquire(c.ctx); err != nil {
		return err
	}

	go func(info syncFileInfo) {
		defer taskSemaphore.release()
		info.err = syncProcess(c, &info)
		c.info <- info
	}(info)
	return nil
}

// syncDequeue flushes the result queue of finished asynchronous tasks.
func syncDequeue(c *syncContext) error {
	for {
		select {
		case <-c.ctx.Done():
			return c.ctx.Err()
		case info := <-c.info:
			if err := syncPostProcess(c, info); err != nil {
				return err
			}
		default:
			return nil
		}
	}
}

// syncDispose creates orphan records for the entire subtree given by nodeID
// as appropriate, then deletes all nodes within the subtree. The subtree root
// node is not deleted if "keepNode" is true.
//
// Orphans keep their thumbnail files, as evidence.
func syncDispose(c *syncContext, nodeID int64, keepNode bool) error {
	if _, err := c.stmtOrphan.Exec(nodeID); err != nil {
		return err
	}

	if keepNode {
		if _, err := c.stmtDisposeSub.Exec(nodeID); err != nil {
			return err
		}
	} else {
		if _, err := c.stmtDisposeAll.Exec(nodeID); err != nil {
			return err
		}
	}
	return nil
}

func syncImage(c *syncContext, info syncFileInfo) error {
	if _, err := c.tx.Exec(`INSERT INTO image(sha1, width, height)
		VALUES (?, ?, ?) ON CONFLICT(sha1) DO NOTHING`,
		info.sha1, info.width, info.height); err != nil {
		return err
	}

	// Fast path: it may already there, and not be a dead symlink.
	path := imagePath(info.sha1)
	if _, err := os.Stat(path); err == nil {
		return nil
	}

	dirname, _ := filepath.Split(path)
	if err := os.MkdirAll(dirname, 0755); err != nil {
		return err
	}

	for {
		// TODO: Make it possible to copy or reflink (ioctl FICLONE).
		err := os.Symlink(info.fsPath, path)
		if !errors.Is(err, fs.ErrExist) {
			return err
		}

		// Try to remove anything standing in the way, and try again.
		if err = os.Remove(path); err != nil {
			return err
		}
	}
}

func syncPostProcess(c *syncContext, info syncFileInfo) error {
	defer c.pb.Step()

	// TODO: When replacing an image node (whether it has or doesn't have
	// other links to keep it alive), we could offer copying all tags,
	// though this needs another table to track it.
	// (If it's equivalent enough, the dhash will stay the same,
	// so user can resolve this through the duplicates feature.)
	switch {
	case info.err != nil:
		// * → error
		if ee, ok := info.err.(*exec.ExitError); ok {
			syncPrintf(c, "%s: %s", info.fsPath, ee.Stderr)
		} else {
			return info.err
		}
		fallthrough

	case info.sha1 == "":
		// 0 → 0
		if info.dbID == 0 {
			return nil
		}

		// D → 0, F → 0
		// TODO: Make it possible to disable removal (for copying only?)
		return syncDispose(c, info.dbID, false /*keepNode*/)

	case info.dbID == 0:
		// 0 → F
		if err := syncImage(c, info); err != nil {
			return err
		}
		if _, err := c.tx.Exec(`INSERT INTO node(parent, name, mtime, sha1)
			VALUES (?, ?, ?, ?)`,
			info.dbParent, info.dbName, info.fsMtime, info.sha1); err != nil {
			return err
		}
		return nil

	default:
		// D → F, F → F (this statement is a no-op with the latter)
		if err := syncDispose(c, info.dbID, true /*keepNode*/); err != nil {
			return err
		}

		// Even if the hash didn't change, we may fix any broken symlinks.
		if err := syncImage(c, info); err != nil {
			return err
		}
		if _, err := c.tx.Exec(`UPDATE node SET mtime = ?, sha1 = ?
			WHERE id = ?`, info.fsMtime, info.sha1, info.dbID); err != nil {
			return err
		}
		return nil
	}
}

func syncDirectoryPair(c *syncContext, dbParent int64, fsPath string,
	pair syncPair) error {
	db, fs, fsInfo := pair.db, pair.fs, syncFileInfo{dbParent: dbParent}
	if db != nil {
		fsInfo.dbID = db.dbID
	}
	if fs != nil {
		fsInfo.dbName = fs.fsName
		fsInfo.fsPath = filepath.Join(fsPath, fs.fsName)
		fsInfo.fsMtime = fs.fsMtime
	}

	switch {
	case db == nil && fs == nil:
		// 0 → 0, unreachable.

	case db == nil && fs.fsIsDir:
		// 0 → D
		var id int64
		if result, err := c.tx.Exec(`INSERT INTO node(parent, name)
			VALUES (?, ?)`, dbParent, fs.fsName); err != nil {
			return err
		} else if id, err = result.LastInsertId(); err != nil {
			return err
		}
		return syncDirectory(c, id, filepath.Join(fsPath, fs.fsName))

	case db == nil:
		// 0 → F (or 0 → 0)
		return syncEnqueue(c, fsInfo)

	case fs == nil:
		// D → 0, F → 0
		// TODO: Make it possible to disable removal (for copying only?)
		return syncDispose(c, db.dbID, false /*keepNode*/)

	case db.dbIsDir() && fs.fsIsDir:
		// D → D
		return syncDirectory(c, db.dbID, filepath.Join(fsPath, fs.fsName))

	case db.dbIsDir():
		// D → F (or D → 0)
		return syncEnqueue(c, fsInfo)

	case fs.fsIsDir:
		// F → D
		if err := syncDispose(c, db.dbID, true /*keepNode*/); err != nil {
			return err
		}
		if _, err := c.tx.Exec(`UPDATE node
			SET mtime = NULL, sha1 = NULL WHERE id = ?`, db.dbID); err != nil {
			return err
		}
		return syncDirectory(c, db.dbID, filepath.Join(fsPath, fs.fsName))

	case db.dbMtime != fs.fsMtime:
		// F → F (or F → 0)
		// Assuming that any content modifications change the timestamp.
		return syncEnqueue(c, fsInfo)
	}
	return nil
}

func syncDirectory(c *syncContext, dbParent int64, fsPath string) error {
	db, err := syncGetNodes(c.tx, dbParent)
	if err != nil {
		return err
	}

	fs, err := syncGetFiles(fsPath)
	if err != nil {
		return err
	}

	// This would not be fatal, but it has annoying consequences.
	if _, ok := slices.BinarySearchFunc(fs, syncFile{fsName: nameOfDB},
		func(a, b syncFile) int {
			return strings.Compare(a.fsName, b.fsName)
		}); ok {
		syncPrintf(c, "%s may be a gallery directory, treating as empty",
			fsPath)
		fs = nil
	}

	// Convert differences to a form more convenient for processing.
	iDB, iFS, pairs := 0, 0, []syncPair{}
	for iDB < len(db) && iFS < len(fs) {
		if db[iDB].dbName == fs[iFS].fsName {
			pairs = append(pairs, syncPair{&db[iDB], &fs[iFS]})
			iDB++
			iFS++
		} else if db[iDB].dbName < fs[iFS].fsName {
			pairs = append(pairs, syncPair{&db[iDB], nil})
			iDB++
		} else {
			pairs = append(pairs, syncPair{nil, &fs[iFS]})
			iFS++
		}
	}
	for i := range db[iDB:] {
		pairs = append(pairs, syncPair{&db[iDB+i], nil})
	}
	for i := range fs[iFS:] {
		pairs = append(pairs, syncPair{nil, &fs[iFS+i]})
	}

	for _, pair := range pairs {
		if err := syncDequeue(c); err != nil {
			return err
		}
		if err := syncDirectoryPair(c, dbParent, fsPath, pair); err != nil {
			return err
		}
	}
	return nil
}

func syncRoot(c *syncContext, fsPath string) error {
	// TODO: Support synchronizing individual files.
	// This can only be treated as 0 → F, F → F, or D → F, that is,
	// a variation on current syncEnqueue(), but dbParent must be nullable.

	// Figure out a database root (not trying to convert F → D on conflict,
	// also because we don't know yet if the argument is a directory).
	//
	// Synchronizing F → D or * → F are special cases not worth implementing.
	crumbs := decodeWebPath(filepath.ToSlash(fsPath))
	dbParent, err := idForDirectoryPath(c.tx, crumbs, true)
	if err != nil {
		return err
	}
	if err := syncDirectory(c, dbParent, fsPath); err != nil {
		return err
	}

	// Wait for all tasks to finish, and process the results of their work.
	for i := 0; i < cap(taskSemaphore); i++ {
		if err := taskSemaphore.acquire(c.ctx); err != nil {
			return err
		}
	}
	if err := syncDequeue(c); err != nil {
		return err
	}

	// This is not our semaphore, so prepare it for the next user.
	for i := 0; i < cap(taskSemaphore); i++ {
		taskSemaphore.release()
	}

	// Delete empty directories, from the bottom of the tree up to,
	// but not including, the inserted root.
	//
	// We need to do this at the end due to our recursive handling,
	// as well as because of asynchronous file filtering.
	stmt, err := c.tx.Prepare(`
		WITH RECURSIVE subtree(id, parent, sha1, level) AS (
			SELECT id, parent, sha1, 1 FROM node WHERE id = ?
			UNION ALL
			SELECT n.id, n.parent, n.sha1, s.level + 1
			FROM node AS n JOIN subtree AS s ON n.parent = s.id
		) DELETE FROM node WHERE id IN (
			SELECT id FROM subtree WHERE level <> 1 AND sha1 IS NULL
			-- No idea why one can't put the "node" table in the subselect.
			-- The whole query then matches nothing.
			AND id NOT IN (SELECT parent FROM subtree)
		)`)
	if err != nil {
		return err
	}

	for {
		if result, err := stmt.Exec(dbParent); err != nil {
			return err
		} else if n, err := result.RowsAffected(); err != nil {
			return err
		} else if n == 0 {
			return nil
		}
	}
}

const disposeCTE = `WITH RECURSIVE
	root(id, sha1, parent, path) AS (
		SELECT id, sha1, parent, name FROM node WHERE id = ?
		UNION ALL
		SELECT r.id, r.sha1, n.parent, n.name || '/' || r.path
		FROM node AS n JOIN root AS r ON n.id = r.parent
	),
	children(id, sha1, path, level) AS (
		SELECT id, sha1, path, 1 FROM root WHERE parent IS NULL
		UNION ALL
		SELECT n.id, n.sha1, c.path || '/' || n.name, c.level + 1
		FROM node AS n JOIN children AS c ON n.parent = c.id
	),
	removed(sha1, count, path) AS (
		SELECT sha1, COUNT(*) AS count, MIN(path) AS path
		FROM children
		GROUP BY sha1
	),
	orphaned(sha1, path, count, total) AS (
		SELECT r.sha1, r.path, r.count, COUNT(*) AS total
		FROM removed AS r
		JOIN node ON node.sha1 = r.sha1
		GROUP BY node.sha1
		HAVING count = total
	)`

func syncRun(ctx context.Context, tx *sql.Tx, roots []string) error {
	c := syncContext{ctx: ctx, tx: tx, pb: newProgressBar(-1)}
	defer c.pb.Stop()

	var err error
	if c.stmtOrphan, err = c.tx.Prepare(disposeCTE + `
		INSERT OR IGNORE INTO orphan(sha1, path)
		SELECT sha1, path FROM orphaned`); err != nil {
		return err
	}
	if c.stmtDisposeSub, err = c.tx.Prepare(disposeCTE + `
		DELETE FROM node WHERE id
		IN (SELECT DISTINCT id FROM children WHERE level <> 1)`); err != nil {
		return err
	}
	if c.stmtDisposeAll, err = c.tx.Prepare(disposeCTE + `
		DELETE FROM node WHERE id
		IN (SELECT DISTINCT id FROM children)`); err != nil {
		return err
	}

	// Info tasks take a position in the task semaphore channel.
	// then fill the info channel.
	//
	// Immediately after syncDequeue(), the info channel is empty,
	// but the semaphore might be full.
	//
	// By having at least one position in the info channel,
	// we allow at least one info task to run to semaphore release,
	// so that syncEnqueue() doesn't deadlock.
	//
	// By making it the same size as the semaphore,
	// the end of this function doesn't need to dequeue while waiting.
	// It also prevents goroutine leaks despite leaving them running--
	// once they finish their job, they're gone,
	// and eventually the info channel would get garbage collected.
	//
	// The additional slot is there to handle the one result
	// that may be placed while syncEnqueue() waits for the semaphore,
	// i.e., it is for the result of the task that syncEnqueue() spawns.
	c.info = make(chan syncFileInfo, cap(taskSemaphore)+1)

	for _, path := range roots {
		if err := syncRoot(&c, path); err != nil {
			return err
		}
	}
	return nil
}

// cmdSync ensures the given (sub)roots are accurately reflected
// in the database.
func cmdSync(args []string) error {
	if len(args) < 2 {
		return errors.New("usage: GD ROOT...")
	}
	if err := openDB(args[0]); err != nil {
		return err
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	// In case of a failure during processing, the only retained side effects
	// on the filesystem tree are:
	//  - Fixing dead symlinks to images.
	//  - Creating symlinks to images that aren't used by anything.
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// Mild hack: upgrade the transaction to a write one straight away,
	// in order to rule out deadlocks (preventable failure).
	if _, err := tx.Exec(`END TRANSACTION;
		BEGIN IMMEDIATE TRANSACTION`); err != nil {
		return err
	}

	// Normalize arguments.
	// At least for now, turn all roots into absolute paths.
	roots := args[1:]
	for i := range roots {
		roots[i], err = filepath.Abs(filepath.Clean(roots[i]))
		if err != nil {
			return err
		}
	}

	// Filter out duplicates.
	sort.Strings(roots)
	roots = slices.CompactFunc(roots, func(a, b string) bool {
		if a != b && !strings.HasPrefix(b, a+"/") {
			return false
		}
		log.Printf("asking to sync path twice: %s\n", b)
		return true
	})

	if err := syncRun(ctx, tx, roots); err != nil {
		return err
	}
	return tx.Commit()
}

// --- Removal -----------------------------------------------------------------

// cmdRemove is for manual removal of subtrees from the database.
// Beware that inputs are database, not filesystem paths.
func cmdRemove(args []string) error {
	if len(args) < 2 {
		return errors.New("usage: GD PATH...")
	}
	if err := openDB(args[0]); err != nil {
		return err
	}

	tx, err := db.BeginTx(context.Background(), nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	for _, path := range args[1:] {
		var id sql.NullInt64
		for _, name := range decodeWebPath(path) {
			if err := tx.QueryRow(`SELECT id FROM node
				WHERE parent IS ? AND name = ?`,
				id, name).Scan(&id); err != nil {
				return err
			}
		}
		if id.Int64 == 0 {
			return errors.New("can't remove root")
		}

		if _, err = tx.Exec(disposeCTE+`
			INSERT OR IGNORE INTO orphan(sha1, path)
			SELECT sha1, path FROM orphaned`, id); err != nil {
			return err
		}
		if _, err = tx.Exec(disposeCTE+`
			DELETE FROM node WHERE id
			IN (SELECT DISTINCT id FROM children)`, id); err != nil {
			return err
		}
	}
	return tx.Commit()
}

// --- Tagging -----------------------------------------------------------------

// cmdTag mass imports tags from data passed on stdin as a TSV
// of SHA1 TAG WEIGHT entries.
func cmdTag(args []string) error {
	if len(args) < 2 || len(args) > 3 {
		return errors.New("usage: GD SPACE [DESCRIPTION]")
	}
	if err := openDB(args[0]); err != nil {
		return err
	}

	space := args[1]

	var description sql.NullString
	if len(args) >= 3 {
		description = sql.NullString{String: args[2], Valid: true}
	}

	// Note that starting as a write transaction prevents deadlocks.
	// Imports are rare, and just bulk load data, so this scope is fine.
	tx, err := db.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()

	if _, err := tx.Exec(`INSERT OR IGNORE INTO tag_space(name, description)
		VALUES (?, ?)`, space, description); err != nil {
		return err
	}

	var spaceID int64
	if err := tx.QueryRow(`SELECT id FROM tag_space WHERE name = ?`,
		space).Scan(&spaceID); err != nil {
		return err
	}

	// XXX: It might make sense to pre-erase all tag assignments within
	// the given space for that image, the first time we see it:
	//
	//   DELETE FROM tag_assignment
	//   WHERE sha1 = ? AND tag IN (SELECT id FROM tag WHERE space = ?)
	//
	// or even just clear the tag space completely:
	//
	//   DELETE FROM tag_assignment
	//   WHERE tag IN (SELECT id FROM tag WHERE space = ?);
	//   DELETE FROM tag WHERE space = ?;
	stmt, err := tx.Prepare(`INSERT INTO tag_assignment(sha1, tag, weight)
		VALUES (?, (SELECT id FROM tag WHERE space = ? AND name = ?), ?)
		ON CONFLICT DO UPDATE SET weight = ?`)
	if err != nil {
		return err
	}

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fields := strings.Split(scanner.Text(), "\t")
		if len(fields) != 3 {
			return errors.New("invalid input format")
		}

		sha1, tag := fields[0], fields[1]
		weight, err := strconv.ParseFloat(fields[2], 64)
		if err != nil {
			return err
		}

		if _, err := tx.Exec(
			`INSERT OR IGNORE INTO tag(space, name) VALUES (?, ?);`,
			spaceID, tag); err != nil {
			return nil
		}
		if _, err := stmt.Exec(sha1, spaceID, tag, weight, weight); err != nil {
			return fmt.Errorf("%s: %s", sha1, err)
		}
	}
	if err := scanner.Err(); err != nil {
		return err
	}

	return tx.Commit()
}

// --- Check -------------------------------------------------------------------

func isValidSHA1(hash string) bool {
	if len(hash) != sha1.Size*2 || strings.ToLower(hash) != hash {
		return false
	}
	if _, err := hex.DecodeString(hash); err != nil {
		return false
	}
	return true
}

func hashesToFileListing(root, suffix string, hashes []string) []string {
	// Note that we're semi-duplicating {image,thumb}Path().
	paths := []string{root}
	for _, hash := range hashes {
		dir := filepath.Join(root, hash[:2])
		paths = append(paths, dir, filepath.Join(dir, hash+suffix))
	}
	slices.Sort(paths)
	return slices.Compact(paths)
}

func collectFileListing(root string) (paths []string, err error) {
	err = filepath.WalkDir(root,
		func(path string, d fs.DirEntry, err error) error {
			paths = append(paths, path)
			return err
		})

	// Even though it should already be sorted somehow.
	slices.Sort(paths)
	return
}

func checkFiles(root, suffix string, hashes []string) (bool, []string, error) {
	db := hashesToFileListing(root, suffix, hashes)
	fs, err := collectFileListing(root)
	if err != nil {
		return false, nil, err
	}

	iDB, iFS, ok, intersection := 0, 0, true, []string{}
	for iDB < len(db) && iFS < len(fs) {
		if db[iDB] == fs[iFS] {
			intersection = append(intersection, db[iDB])
			iDB++
			iFS++
		} else if db[iDB] < fs[iFS] {
			ok = false
			fmt.Printf("only in DB: %s\n", db[iDB])
			iDB++
		} else {
			ok = false
			fmt.Printf("only in FS: %s\n", fs[iFS])
			iFS++
		}
	}
	for _, path := range db[iDB:] {
		ok = false
		fmt.Printf("only in DB: %s\n", path)
	}
	for _, path := range fs[iFS:] {
		ok = false
		fmt.Printf("only in FS: %s\n", path)
	}
	return ok, intersection, nil
}

// cmdCheck carries out various database consistency checks.
func cmdCheck(args []string) error {
	if len(args) != 1 {
		return errors.New("usage: GD")
	}
	if err := openDB(args[0]); err != nil {
		return err
	}

	// Check if hashes are in the right format.
	log.Println("checking image hashes")

	allSHA1, err := dbCollectStrings(`SELECT sha1 FROM image`)
	if err != nil {
		return err
	}

	ok := true
	for _, hash := range allSHA1 {
		if !isValidSHA1(hash) {
			ok = false
			fmt.Printf("invalid image SHA1: %s\n", hash)
		}
	}

	// This is, rather obviously, just a strict subset.
	// Although it doesn't run in the same transaction.
	thumbSHA1, err := dbCollectStrings(`SELECT sha1 FROM image
		WHERE thumbw IS NOT NULL OR thumbh IS NOT NULL`)
	if err != nil {
		return err
	}

	// This somewhat duplicates {image,thumb}Path().
	log.Println("checking SQL against filesystem")
	okImages, intersection, err := checkFiles(
		filepath.Join(galleryDirectory, nameOfImageRoot), "", allSHA1)
	if err != nil {
		return err
	}

	okThumbs, _, err := checkFiles(
		filepath.Join(galleryDirectory, nameOfThumbRoot), ".webp", thumbSHA1)
	if err != nil {
		return err
	}
	if !okImages || !okThumbs {
		ok = false
	}

	// NOTE: We could also compare mtime, and on mismatch the current SHA1,
	// though that's more of a "sync" job.
	log.Println("checking for dead symlinks")
	for _, path := range intersection {
		if _, err := os.Stat(path); err != nil {
			ok = false
			fmt.Printf("%s: %s\n", path, err)
		}
	}
	if !ok {
		return errors.New("detected inconsistencies")
	}
	return nil
}

// --- Thumbnailing ------------------------------------------------------------

func makeThumbnail(pathImage, pathThumb string) (int, int, error) {
	thumbDirname, _ := filepath.Split(pathThumb)
	if err := os.MkdirAll(thumbDirname, 0755); err != nil {
		return 0, 0, err
	}

	// Create a normalized thumbnail. Since we don't particularly need
	// any complex processing, such as surrounding of metadata,
	// simply push it through ImageMagick.
	//
	//  - http://www.ericbrasseur.org/gamma.html
	//  - https://www.imagemagick.org/Usage/thumbnails/
	//  - https://imagemagick.org/script/command-line-options.php#layers
	//
	// "info:" output is written for each frame, which is why we delete
	// all of them but the first one beforehands.
	//
	// TODO: See if we can optimize resulting WebP animations.
	// (Do -layers optimize* apply to this format at all?)
	cmd := exec.Command("convert", "-limit", "thread", "1", pathImage,
		"-coalesce", "-colorspace", "RGB", "-auto-orient", "-strip",
		"-resize", "256x128>", "-colorspace", "sRGB",
		"-format", "%w %h", "+write", pathThumb, "-delete", "1--1", "info:")

	out, err := cmd.Output()
	if err != nil {
		return 0, 0, err
	}

	var w, h int
	_, err = fmt.Fscanf(bytes.NewReader(out), "%d %d", &w, &h)
	return w, h, err
}

func makeThumbnailFor(sha1 string) (message string, err error) {
	pathImage := imagePath(sha1)
	pathThumb := thumbPath(sha1)
	w, h, err := makeThumbnail(pathImage, pathThumb)
	if err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return string(ee.Stderr), nil
		}
		return "", err
	}

	_, err = db.Exec(`UPDATE image SET thumbw = ?, thumbh = ?
		WHERE sha1 = ?`, w, h, sha1)
	return "", err
}

// cmdThumbnail generates missing thumbnails, in parallel.
func cmdThumbnail(args []string) error {
	if len(args) < 1 {
		return errors.New("usage: GD [SHA1...]")
	}
	if err := openDB(args[0]); err != nil {
		return err
	}

	hexSHA1 := args[1:]
	if len(hexSHA1) == 0 {
		// Get all unique images in the database with no thumbnail.
		var err error
		hexSHA1, err = dbCollectStrings(`SELECT sha1 FROM image
			WHERE thumbw IS NULL OR thumbh IS NULL`)
		if err != nil {
			return err
		}
	}
	return parallelize(hexSHA1, makeThumbnailFor)
}

// --- Perceptual hash ---------------------------------------------------------

type linearImage struct {
	img image.Image
}

func newLinearImage(img image.Image) *linearImage {
	return &linearImage{img: img}
}

func (l *linearImage) ColorModel() color.Model { return l.img.ColorModel() }
func (l *linearImage) Bounds() image.Rectangle { return l.img.Bounds() }

func unSRGB(c uint32) uint8 {
	n := float64(c) / 0xffff
	if n <= 0.04045 {
		return uint8(n * (255.0 / 12.92))
	}
	return uint8(math.Pow((n+0.055)/(1.055), 2.4) * 255.0)
}

func (l *linearImage) At(x, y int) color.Color {
	r, g, b, a := l.img.At(x, y).RGBA()
	return color.RGBA{
		R: unSRGB(r), G: unSRGB(g), B: unSRGB(b), A: uint8(a >> 8)}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// isWebPAnimation returns whether the given ReadSeeker starts a WebP animation.
// See https://developers.google.com/speed/webp/docs/riff_container
func isWebPAnimation(rs io.ReadSeeker) (bool, error) {
	b := make([]byte, 17)
	if _, err := rs.Read(b); err != nil {
		return false, err
	}
	if _, err := rs.Seek(0, io.SeekStart); err != nil {
		return false, err
	}

	return bytes.Equal(b[:4], []byte("RIFF")) &&
		bytes.Equal(b[8:16], []byte("WEBPVP8X")) &&
		b[16]&0b00000010 != 0, nil
}

var errIsAnimation = errors.New("cannot perceptually hash animations")

func dhashWebP(rs io.ReadSeeker) (uint64, error) {
	if a, err := isWebPAnimation(rs); err != nil {
		return 0, err
	} else if a {
		return 0, errIsAnimation
	}

	// Doing this entire thing in Go is SLOW, but convenient.
	source, err := webp.Decode(rs)
	if err != nil {
		return 0, err
	}

	var (
		linear  = newLinearImage(source)
		resized = image.NewNRGBA64(image.Rect(0, 0, 9, 8))
	)
	draw.CatmullRom.Scale(resized, resized.Bounds(),
		linear, linear.Bounds(), draw.Src, nil)

	var hash uint64
	for y := 0; y < 8; y++ {
		var grey [9]float32
		for x := 0; x < 9; x++ {
			rgba := resized.NRGBA64At(x, y)
			grey[x] = 0.2126*float32(rgba.R) +
				0.7152*float32(rgba.G) +
				0.0722*float32(rgba.B)
		}

		var row uint64
		if grey[0] < grey[1] {
			row |= 1 << 7
		}
		if grey[1] < grey[2] {
			row |= 1 << 6
		}
		if grey[2] < grey[3] {
			row |= 1 << 5
		}
		if grey[3] < grey[4] {
			row |= 1 << 4
		}
		if grey[4] < grey[5] {
			row |= 1 << 3
		}
		if grey[5] < grey[6] {
			row |= 1 << 2
		}
		if grey[6] < grey[7] {
			row |= 1 << 1
		}
		if grey[7] < grey[8] {
			row |= 1 << 0
		}
		hash = hash<<8 | row
	}
	return hash, nil
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

func makeDhash(sha1 string) (uint64, error) {
	pathThumb := thumbPath(sha1)
	f, err := os.Open(pathThumb)
	if err != nil {
		return 0, err
	}
	defer f.Close()
	return dhashWebP(f)
}

func makeDhashFor(sha1 string) (message string, err error) {
	hash, err := makeDhash(sha1)
	if errors.Is(err, errIsAnimation) {
		// Ignoring this common condition.
		return "", nil
	} else if err != nil {
		return err.Error(), nil
	}

	_, err = db.Exec(
		`UPDATE image SET dhash = ? WHERE sha1 = ?`, int64(hash), sha1)
	return "", err
}

// cmdDhash generates perceptual hash from thumbnails.
func cmdDhash(args []string) error {
	if len(args) < 1 {
		return errors.New("usage: GD [SHA1...]")
	}
	if err := openDB(args[0]); err != nil {
		return err
	}

	hexSHA1 := args[1:]
	if len(hexSHA1) == 0 {
		var err error
		hexSHA1, err = dbCollectStrings(`
			SELECT sha1 FROM image WHERE dhash IS NULL`)
		if err != nil {
			return err
		}
	}
	return parallelize(hexSHA1, makeDhashFor)
}

// --- Main --------------------------------------------------------------------

var commands = map[string]struct {
	handler func(args []string) error
}{
	"init":      {cmdInit},
	"web":       {cmdWeb},
	"tag":       {cmdTag},
	"sync":      {cmdSync},
	"remove":    {cmdRemove},
	"check":     {cmdCheck},
	"thumbnail": {cmdThumbnail},
	"dhash":     {cmdDhash},
}

func main() {
	if len(os.Args) <= 2 {
		log.Fatalln("Missing arguments")
	}

	cmd, ok := commands[os.Args[1]]
	if !ok {
		log.Fatalln("Unknown command: " + os.Args[1])
	}

	taskSemaphore = newSemaphore(runtime.NumCPU())
	err := cmd.handler(os.Args[2:])

	// Note that the database object has a closing finalizer,
	// we just additionally print any errors coming from there.
	if db != nil {
		if err := db.Close(); err != nil {
			log.Println(err)
		}
	}

	if err != nil {
		log.Fatalln(err)
	}
}