sccache 0.14.0

Sccache is a ccache-like tool. It is used as a compiler wrapper and avoids compilation when possible. Sccache has the capability to utilize caching in remote storage environments, including various cloud storage options, or alternatively, in local storage.
Documentation
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
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
// Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::cache::CacheMode;
#[cfg(target_os = "windows")]
use crate::util::normalize_win_path;
use directories::ProjectDirs;
use fs::File;
use fs_err as fs;
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
use serde::ser::Serializer;
use serde::{
    Deserialize, Serialize,
    de::{self, DeserializeOwned, Deserializer},
};
#[cfg(test)]
use serial_test::serial;
use std::env;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::result::Result as StdResult;
use std::str::FromStr;
use std::sync::{LazyLock, Mutex};
use std::{collections::HashMap, fmt};
use typed_path::Utf8TypedPathBuf;

pub use crate::cache::PreprocessorCacheModeConfig;
use crate::errors::*;

static CACHED_CONFIG_PATH: LazyLock<PathBuf> = LazyLock::new(CachedConfig::file_config_path);
static CACHED_CONFIG: Mutex<Option<CachedFileConfig>> = Mutex::new(None);

const ORGANIZATION: &str = "Mozilla";
const APP_NAME: &str = "sccache";
const DIST_APP_NAME: &str = "sccache-dist-client";
const TEN_GIGS: u64 = 10 * 1024 * 1024 * 1024;

pub const INSECURE_DIST_CLIENT_TOKEN: &str = "dangerously_insecure_client";

// Unfortunately this means that nothing else can use the sccache cache dir as
// this top level directory is used directly to store sccache cached objects...
pub fn default_disk_cache_dir() -> PathBuf {
    ProjectDirs::from("", ORGANIZATION, APP_NAME)
        .expect("Unable to retrieve disk cache directory")
        .cache_dir()
        .to_owned()
}
// ...whereas subdirectories are used of this one
pub fn default_dist_cache_dir() -> PathBuf {
    ProjectDirs::from("", ORGANIZATION, DIST_APP_NAME)
        .expect("Unable to retrieve dist cache directory")
        .cache_dir()
        .to_owned()
}

fn default_disk_cache_size() -> u64 {
    TEN_GIGS
}
fn default_toolchain_cache_size() -> u64 {
    TEN_GIGS
}

struct StringOrU64Visitor;

impl de::Visitor<'_> for StringOrU64Visitor {
    type Value = u64;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a string with size suffix (like '20G') or a u64")
    }

    fn visit_str<E>(self, value: &str) -> StdResult<Self::Value, E>
    where
        E: de::Error,
    {
        parse_size(value).ok_or_else(|| E::custom(format!("Invalid size value: {}", value)))
    }

    fn visit_u64<E>(self, value: u64) -> StdResult<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(value)
    }

    fn visit_i64<E>(self, value: i64) -> StdResult<Self::Value, E>
    where
        E: de::Error,
    {
        if value < 0 {
            Err(E::custom("negative values not supported"))
        } else {
            Ok(value as u64)
        }
    }
}

fn deserialize_size_from_str<'de, D>(deserializer: D) -> StdResult<u64, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_any(StringOrU64Visitor)
}

pub fn parse_size(val: &str) -> Option<u64> {
    let multiplier = match val.chars().last().map(|v| v.to_ascii_uppercase()) {
        Some('K') => 1024,
        Some('M') => 1024 * 1024,
        Some('G') => 1024 * 1024 * 1024,
        Some('T') => 1024 * 1024 * 1024 * 1024,
        _ => 1,
    };
    let val = if multiplier > 1 && !val.is_empty() {
        val.split_at(val.len() - 1).0
    } else {
        val
    };
    u64::from_str(val).ok().map(|size| size * multiplier)
}

#[cfg(any(feature = "dist-client", feature = "dist-server"))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HTTPUrl(reqwest::Url);
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
impl Serialize for HTTPUrl {
    fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.0.as_str())
    }
}
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
impl<'a> Deserialize<'a> for HTTPUrl {
    fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
    where
        D: Deserializer<'a>,
    {
        use serde::de::Error;
        let helper: String = Deserialize::deserialize(deserializer)?;
        let url = parse_http_url(&helper).map_err(D::Error::custom)?;
        Ok(HTTPUrl(url))
    }
}
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
fn parse_http_url(url: &str) -> Result<reqwest::Url> {
    use std::net::SocketAddr;
    let url = if let Ok(sa) = url.parse::<SocketAddr>() {
        warn!("Url {} has no scheme, assuming http", url);
        reqwest::Url::parse(&format!("http://{}", sa))
    } else {
        reqwest::Url::parse(url)
    }?;
    if url.scheme() != "http" && url.scheme() != "https" {
        bail!("url not http or https")
    }
    // TODO: relative url handling just hasn't been implemented and tested
    if url.path() != "/" {
        bail!("url has a relative path (currently unsupported)")
    }
    Ok(url)
}
#[cfg(any(feature = "dist-client", feature = "dist-server"))]
impl HTTPUrl {
    pub fn from_url(u: reqwest::Url) -> Self {
        HTTPUrl(u)
    }
    pub fn to_url(&self) -> reqwest::Url {
        self.0.clone()
    }
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AzureCacheConfig {
    pub connection_string: String,
    pub container: String,
    pub key_prefix: String,
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct DiskCacheConfig {
    pub dir: PathBuf,
    #[serde(deserialize_with = "deserialize_size_from_str")]
    pub size: u64,
    pub preprocessor_cache_mode: PreprocessorCacheModeConfig,
    pub rw_mode: CacheModeConfig,
}

impl Default for DiskCacheConfig {
    fn default() -> Self {
        DiskCacheConfig {
            dir: default_disk_cache_dir(),
            size: default_disk_cache_size(),
            preprocessor_cache_mode: PreprocessorCacheModeConfig::activated(),
            rw_mode: CacheModeConfig::ReadWrite,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum CacheModeConfig {
    #[serde(rename = "READ_ONLY")]
    ReadOnly,
    #[serde(rename = "READ_WRITE")]
    ReadWrite,
}

impl From<CacheModeConfig> for CacheMode {
    fn from(value: CacheModeConfig) -> Self {
        match value {
            CacheModeConfig::ReadOnly => CacheMode::ReadOnly,
            CacheModeConfig::ReadWrite => CacheMode::ReadWrite,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GCSCacheConfig {
    pub bucket: String,
    pub key_prefix: String,
    pub cred_path: Option<String>,
    pub service_account: Option<String>,
    pub rw_mode: CacheModeConfig,
    pub credential_url: Option<String>,
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GHACacheConfig {
    pub enabled: bool,
    /// Version for gha cache is a namespace. By setting different versions,
    /// we can avoid mixed caches.
    pub version: String,
}

/// Memcached's default value of expiration is 10800s (3 hours), which is too
/// short for use case of sccache.
///
/// We increase the default expiration to 86400s (1 day) to balance between
/// memory consumpation and cache hit rate.
///
/// Please change this value freely if we have a better choice.
const DEFAULT_MEMCACHED_CACHE_EXPIRATION: u32 = 86400;

fn default_memcached_cache_expiration() -> u32 {
    DEFAULT_MEMCACHED_CACHE_EXPIRATION
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct MemcachedCacheConfig {
    #[serde(alias = "endpoint")]
    pub url: String,

    /// Username to authenticate with.
    pub username: Option<String>,

    /// Password to authenticate with.
    pub password: Option<String>,

    /// the expiration time in seconds.
    ///
    /// Default to 24 hours (86400)
    /// Up to 30 days (2592000)
    #[serde(default = "default_memcached_cache_expiration")]
    pub expiration: u32,

    #[serde(default)]
    pub key_prefix: String,
}

/// redis has no default TTL - all caches live forever
///
/// We keep the TTL as 0 here as redis does
///
/// Please change this value freely if we have a better choice.
const DEFAULT_REDIS_CACHE_TTL: u64 = 0;
pub const DEFAULT_REDIS_DB: u32 = 0;
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct RedisCacheConfig {
    /// The single-node redis endpoint.
    /// Mutually exclusive with `cluster_endpoints`.
    pub endpoint: Option<String>,

    /// The redis cluster endpoints.
    /// Mutually exclusive with `endpoint`.
    pub cluster_endpoints: Option<String>,

    /// Username to authenticate with.
    pub username: Option<String>,

    /// Password to authenticate with.
    pub password: Option<String>,

    /// The redis URL.
    /// Deprecated in favor of `endpoint`.
    pub url: Option<String>,

    /// the db number to use
    ///
    /// Default to 0
    #[serde(default)]
    pub db: u32,

    /// the ttl (expiration) time in seconds.
    ///
    /// Default to infinity (0)
    #[serde(default, alias = "expiration")]
    pub ttl: u64,

    #[serde(default)]
    pub key_prefix: String,
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WebdavCacheConfig {
    pub endpoint: String,
    #[serde(default)]
    pub key_prefix: String,
    pub username: Option<String>,
    pub password: Option<String>,
    pub token: Option<String>,
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct S3CacheConfig {
    pub bucket: String,
    pub region: Option<String>,
    #[serde(default)]
    pub key_prefix: String,
    pub no_credentials: bool,
    pub endpoint: Option<String>,
    pub use_ssl: Option<bool>,
    pub server_side_encryption: Option<bool>,
    pub enable_virtual_host_style: Option<bool>,
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OSSCacheConfig {
    pub bucket: String,
    #[serde(default)]
    pub key_prefix: String,
    pub endpoint: Option<String>,
    pub no_credentials: bool,
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct COSCacheConfig {
    pub bucket: String,
    #[serde(default)]
    pub key_prefix: String,
    pub endpoint: Option<String>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum CacheType {
    Azure(AzureCacheConfig),
    GCS(GCSCacheConfig),
    GHA(GHACacheConfig),
    Memcached(MemcachedCacheConfig),
    Redis(RedisCacheConfig),
    S3(S3CacheConfig),
    Webdav(WebdavCacheConfig),
    OSS(OSSCacheConfig),
    COS(COSCacheConfig),
}

#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct CacheConfigs {
    pub azure: Option<AzureCacheConfig>,
    pub disk: Option<DiskCacheConfig>,
    pub gcs: Option<GCSCacheConfig>,
    pub gha: Option<GHACacheConfig>,
    pub memcached: Option<MemcachedCacheConfig>,
    pub redis: Option<RedisCacheConfig>,
    pub s3: Option<S3CacheConfig>,
    pub webdav: Option<WebdavCacheConfig>,
    pub oss: Option<OSSCacheConfig>,
    pub cos: Option<COSCacheConfig>,
}

impl CacheConfigs {
    /// Return cache type in an arbitrary but
    /// consistent ordering
    fn into_fallback(self) -> (Option<CacheType>, DiskCacheConfig) {
        let CacheConfigs {
            azure,
            disk,
            gcs,
            gha,
            memcached,
            redis,
            s3,
            webdav,
            oss,
            cos,
        } = self;

        let cache_type = s3
            .map(CacheType::S3)
            .or_else(|| redis.map(CacheType::Redis))
            .or_else(|| memcached.map(CacheType::Memcached))
            .or_else(|| gcs.map(CacheType::GCS))
            .or_else(|| gha.map(CacheType::GHA))
            .or_else(|| azure.map(CacheType::Azure))
            .or_else(|| webdav.map(CacheType::Webdav))
            .or_else(|| oss.map(CacheType::OSS))
            .or_else(|| cos.map(CacheType::COS));

        let fallback = disk.unwrap_or_default();

        (cache_type, fallback)
    }

    /// Override self with any existing fields from other
    fn merge(&mut self, other: Self) {
        let CacheConfigs {
            azure,
            disk,
            gcs,
            gha,
            memcached,
            redis,
            s3,
            webdav,
            oss,
            cos,
        } = other;

        if azure.is_some() {
            self.azure = azure;
        }
        if disk.is_some() {
            self.disk = disk;
        }
        if gcs.is_some() {
            self.gcs = gcs;
        }
        if gha.is_some() {
            self.gha = gha;
        }
        if memcached.is_some() {
            self.memcached = memcached;
        }
        if redis.is_some() {
            self.redis = redis;
        }
        if s3.is_some() {
            self.s3 = s3;
        }
        if webdav.is_some() {
            self.webdav = webdav;
        }
        if oss.is_some() {
            self.oss = oss;
        }
        if cos.is_some() {
            self.cos = cos;
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(tag = "type")]
pub enum DistToolchainConfig {
    #[serde(rename = "no_dist")]
    NoDist { compiler_executable: PathBuf },
    #[serde(rename = "path_override")]
    PathOverride {
        compiler_executable: PathBuf,
        archive: PathBuf,
        archive_compiler_executable: String,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type")]
pub enum DistAuth {
    #[serde(rename = "token")]
    Token { token: String },
    #[serde(rename = "oauth2_code_grant_pkce")]
    Oauth2CodeGrantPKCE {
        client_id: String,
        auth_url: String,
        token_url: String,
    },
    #[serde(rename = "oauth2_implicit")]
    Oauth2Implicit { client_id: String, auth_url: String },
}

// Convert a type = "mozilla" immediately into an actual oauth configuration
// https://github.com/serde-rs/serde/issues/595 could help if implemented
impl<'a> Deserialize<'a> for DistAuth {
    fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
    where
        D: Deserializer<'a>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        #[serde(tag = "type")]
        pub enum Helper {
            #[serde(rename = "token")]
            Token { token: String },
            #[serde(rename = "oauth2_code_grant_pkce")]
            Oauth2CodeGrantPKCE {
                client_id: String,
                auth_url: String,
                token_url: String,
            },
            #[serde(rename = "oauth2_implicit")]
            Oauth2Implicit { client_id: String, auth_url: String },
        }

        let helper: Helper = Deserialize::deserialize(deserializer)?;

        Ok(match helper {
            Helper::Token { token } => DistAuth::Token { token },
            Helper::Oauth2CodeGrantPKCE {
                client_id,
                auth_url,
                token_url,
            } => DistAuth::Oauth2CodeGrantPKCE {
                client_id,
                auth_url,
                token_url,
            },
            Helper::Oauth2Implicit {
                client_id,
                auth_url,
            } => DistAuth::Oauth2Implicit {
                client_id,
                auth_url,
            },
        })
    }
}

impl Default for DistAuth {
    fn default() -> Self {
        DistAuth::Token {
            token: INSECURE_DIST_CLIENT_TOKEN.to_owned(),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct DistConfig {
    pub auth: DistAuth,
    #[cfg(any(feature = "dist-client", feature = "dist-server"))]
    pub scheduler_url: Option<HTTPUrl>,
    #[cfg(not(any(feature = "dist-client", feature = "dist-server")))]
    pub scheduler_url: Option<String>,
    pub cache_dir: PathBuf,
    pub toolchains: Vec<DistToolchainConfig>,
    #[serde(deserialize_with = "deserialize_size_from_str")]
    pub toolchain_cache_size: u64,
    pub rewrite_includes_only: bool,
}

impl Default for DistConfig {
    fn default() -> Self {
        Self {
            auth: Default::default(),
            scheduler_url: Default::default(),
            cache_dir: default_dist_cache_dir(),
            toolchains: Default::default(),
            toolchain_cache_size: default_toolchain_cache_size(),
            rewrite_includes_only: false,
        }
    }
}

// TODO: fields only pub for tests
#[derive(Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct FileConfig {
    pub cache: CacheConfigs,
    pub dist: DistConfig,
    pub server_startup_timeout_ms: Option<u64>,
    /// Base directories to strip from paths for cache key computation.
    pub basedirs: Vec<String>,
}

// If the file doesn't exist or we can't read it, log the issue and proceed. If the
// config exists but doesn't parse then something is wrong - return an error.
pub fn try_read_config_file<T: DeserializeOwned>(path: &Path) -> Result<Option<T>> {
    debug!("Attempting to read config file at {:?}", path);
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(e) => {
            debug!("Couldn't open config file: {}", e);
            return Ok(None);
        }
    };

    let mut string = String::new();
    match file.read_to_string(&mut string) {
        Ok(_) => (),
        Err(e) => {
            warn!("Failed to read config file: {}", e);
            return Ok(None);
        }
    }

    let res = if path.extension().is_some_and(|e| e == "json") {
        serde_json::from_str(&string)
            .with_context(|| format!("Failed to load json config file from {}", path.display()))?
    } else {
        toml::from_str(&string)
            .with_context(|| format!("Failed to load toml config file from {}", path.display()))?
    };

    Ok(Some(res))
}

#[derive(Debug)]
pub struct EnvConfig {
    cache: CacheConfigs,
    basedirs: Option<Vec<String>>,
}

fn key_prefix_from_env_var(env_var_name: &str) -> String {
    env::var(env_var_name)
        .ok()
        .as_ref()
        .map(|s| s.trim_end_matches('/'))
        .filter(|s| !s.is_empty())
        .unwrap_or_default()
        .to_owned()
}

fn number_from_env_var<A: std::str::FromStr>(env_var_name: &str) -> Option<Result<A>>
where
    <A as FromStr>::Err: std::fmt::Debug,
{
    let value = env::var(env_var_name).ok()?;

    value
        .parse::<A>()
        .map_err(|err| anyhow!("{env_var_name} value is invalid: {err:?}"))
        .into()
}

fn bool_from_env_var(env_var_name: &str) -> Result<Option<bool>> {
    env::var(env_var_name)
        .ok()
        .map(|value| match value.to_lowercase().as_str() {
            "true" | "on" | "1" => Ok(true),
            "false" | "off" | "0" => Ok(false),
            _ => bail!(
                "{} must be 'true', 'on', '1', 'false', 'off' or '0'.",
                env_var_name
            ),
        })
        .transpose()
}

fn config_from_env() -> Result<EnvConfig> {
    // ======= AWS =======
    let s3 = if let Ok(bucket) = env::var("SCCACHE_BUCKET") {
        let region = env::var("SCCACHE_REGION").ok();
        let no_credentials = bool_from_env_var("SCCACHE_S3_NO_CREDENTIALS")?.unwrap_or(false);
        let use_ssl = bool_from_env_var("SCCACHE_S3_USE_SSL")?;
        let server_side_encryption = bool_from_env_var("SCCACHE_S3_SERVER_SIDE_ENCRYPTION")?;
        let endpoint = env::var("SCCACHE_ENDPOINT").ok();
        let key_prefix = key_prefix_from_env_var("SCCACHE_S3_KEY_PREFIX");
        let enable_virtual_host_style = bool_from_env_var("SCCACHE_S3_ENABLE_VIRTUAL_HOST_STYLE")?;

        Some(S3CacheConfig {
            bucket,
            region,
            no_credentials,
            key_prefix,
            endpoint,
            use_ssl,
            server_side_encryption,
            enable_virtual_host_style,
        })
    } else {
        None
    };

    if s3.as_ref().map(|s3| s3.no_credentials).unwrap_or_default()
        && (env::var_os("AWS_ACCESS_KEY_ID").is_some()
            || env::var_os("AWS_SECRET_ACCESS_KEY").is_some())
    {
        bail!("If setting S3 credentials, SCCACHE_S3_NO_CREDENTIALS must not be set.");
    }

    // ======= redis =======
    let redis = match (
        env::var("SCCACHE_REDIS").ok(),
        env::var("SCCACHE_REDIS_ENDPOINT").ok(),
        env::var("SCCACHE_REDIS_CLUSTER_ENDPOINTS").ok(),
    ) {
        (None, None, None) => None,
        (url, endpoint, cluster_endpoints) => {
            let db = number_from_env_var("SCCACHE_REDIS_DB")
                .transpose()?
                .unwrap_or(DEFAULT_REDIS_DB);

            let username = env::var("SCCACHE_REDIS_USERNAME").ok();
            let password = env::var("SCCACHE_REDIS_PASSWORD").ok();

            let ttl = number_from_env_var("SCCACHE_REDIS_EXPIRATION")
                .or_else(|| number_from_env_var("SCCACHE_REDIS_TTL"))
                .transpose()?
                .unwrap_or(DEFAULT_REDIS_CACHE_TTL);

            let key_prefix = key_prefix_from_env_var("SCCACHE_REDIS_KEY_PREFIX");

            Some(RedisCacheConfig {
                url,
                endpoint,
                cluster_endpoints,
                username,
                password,
                db,
                ttl,
                key_prefix,
            })
        }
    };

    if env::var_os("SCCACHE_REDIS_EXPIRATION").is_some()
        && env::var_os("SCCACHE_REDIS_TTL").is_some()
    {
        bail!("You mustn't set both SCCACHE_REDIS_EXPIRATION and SCCACHE_REDIS_TTL. Use only one.");
    }

    // ======= memcached =======
    let memcached = if let Ok(url) =
        env::var("SCCACHE_MEMCACHED").or_else(|_| env::var("SCCACHE_MEMCACHED_ENDPOINT"))
    {
        let username = env::var("SCCACHE_MEMCACHED_USERNAME").ok();
        let password = env::var("SCCACHE_MEMCACHED_PASSWORD").ok();

        let expiration = number_from_env_var("SCCACHE_MEMCACHED_EXPIRATION")
            .transpose()?
            .unwrap_or(DEFAULT_MEMCACHED_CACHE_EXPIRATION);

        let key_prefix = key_prefix_from_env_var("SCCACHE_MEMCACHED_KEY_PREFIX");

        Some(MemcachedCacheConfig {
            url,
            username,
            password,
            expiration,
            key_prefix,
        })
    } else {
        None
    };

    if env::var_os("SCCACHE_MEMCACHED").is_some()
        && env::var_os("SCCACHE_MEMCACHED_ENDPOINT").is_some()
    {
        bail!(
            "You mustn't set both SCCACHE_MEMCACHED and SCCACHE_MEMCACHED_ENDPOINT. Please, use only SCCACHE_MEMCACHED_ENDPOINT."
        );
    }

    // ======= GCP/GCS =======
    if (env::var("SCCACHE_GCS_CREDENTIALS_URL").is_ok()
        || env::var("SCCACHE_GCS_OAUTH_URL").is_ok()
        || env::var("SCCACHE_GCS_KEY_PATH").is_ok())
        && env::var("SCCACHE_GCS_BUCKET").is_err()
    {
        bail!(
            "If setting GCS credentials, SCCACHE_GCS_BUCKET and an auth mechanism need to be set."
        );
    }

    let gcs = env::var("SCCACHE_GCS_BUCKET").ok().map(|bucket| {
        let key_prefix = key_prefix_from_env_var("SCCACHE_GCS_KEY_PREFIX");

        if env::var("SCCACHE_GCS_OAUTH_URL").is_ok() {
            eprintln!("SCCACHE_GCS_OAUTH_URL has been deprecated");
            eprintln!("if you intend to use vm metadata for auth, please set correct service account instead");
        }

        let credential_url = env::var("SCCACHE_GCS_CREDENTIALS_URL").ok();

        let cred_path = env::var("SCCACHE_GCS_KEY_PATH").ok();
        let service_account = env::var("SCCACHE_GCS_SERVICE_ACCOUNT").ok();

        let rw_mode = match env::var("SCCACHE_GCS_RW_MODE").as_ref().map(String::as_str) {
            Ok("READ_ONLY") => CacheModeConfig::ReadOnly,
            Ok("READ_WRITE") => CacheModeConfig::ReadWrite,
            // TODO: unsure if these should warn during the configuration loading
            // or at the time when they're actually used to connect to GCS
            Ok(_) => {
                warn!("Invalid SCCACHE_GCS_RW_MODE -- defaulting to READ_ONLY.");
                CacheModeConfig::ReadOnly
            }
            _ => {
                warn!("No SCCACHE_GCS_RW_MODE specified -- defaulting to READ_ONLY.");
                CacheModeConfig::ReadOnly
            }
        };

        GCSCacheConfig {
            bucket,
            key_prefix,
            cred_path,
            service_account,
            rw_mode,
            credential_url,
        }
    });

    // ======= GHA =======
    let gha = if let Ok(version) = env::var("SCCACHE_GHA_VERSION") {
        // If SCCACHE_GHA_VERSION has been set, we don't need to check
        // SCCACHE_GHA_ENABLED's value anymore.
        Some(GHACacheConfig {
            enabled: true,
            version,
        })
    } else if bool_from_env_var("SCCACHE_GHA_ENABLED")?.unwrap_or(false) {
        // If only SCCACHE_GHA_ENABLED has been set to the true value, enable with
        // default version.
        Some(GHACacheConfig {
            enabled: true,
            version: "".to_string(),
        })
    } else {
        None
    };

    // ======= Azure =======
    let azure = if let (Ok(connection_string), Ok(container)) = (
        env::var("SCCACHE_AZURE_CONNECTION_STRING"),
        env::var("SCCACHE_AZURE_BLOB_CONTAINER"),
    ) {
        let key_prefix = key_prefix_from_env_var("SCCACHE_AZURE_KEY_PREFIX");
        Some(AzureCacheConfig {
            connection_string,
            container,
            key_prefix,
        })
    } else {
        None
    };

    // ======= WebDAV =======
    let webdav = if let Ok(endpoint) = env::var("SCCACHE_WEBDAV_ENDPOINT") {
        let key_prefix = key_prefix_from_env_var("SCCACHE_WEBDAV_KEY_PREFIX");
        let username = env::var("SCCACHE_WEBDAV_USERNAME").ok();
        let password = env::var("SCCACHE_WEBDAV_PASSWORD").ok();
        let token = env::var("SCCACHE_WEBDAV_TOKEN").ok();

        Some(WebdavCacheConfig {
            endpoint,
            key_prefix,
            username,
            password,
            token,
        })
    } else {
        None
    };

    // ======= OSS =======
    let oss = if let Ok(bucket) = env::var("SCCACHE_OSS_BUCKET") {
        let endpoint = env::var("SCCACHE_OSS_ENDPOINT").ok();
        let key_prefix = key_prefix_from_env_var("SCCACHE_OSS_KEY_PREFIX");

        let no_credentials = bool_from_env_var("SCCACHE_OSS_NO_CREDENTIALS")?.unwrap_or(false);

        Some(OSSCacheConfig {
            bucket,
            endpoint,
            key_prefix,
            no_credentials,
        })
    } else {
        None
    };

    if oss
        .as_ref()
        .map(|oss| oss.no_credentials)
        .unwrap_or_default()
        && (env::var_os("ALIBABA_CLOUD_ACCESS_KEY_ID").is_some()
            || env::var_os("ALIBABA_CLOUD_ACCESS_KEY_SECRET").is_some())
    {
        bail!("If setting OSS credentials, SCCACHE_OSS_NO_CREDENTIALS must not be set.");
    }

    // ======= COS =======
    let cos = if let Ok(bucket) = env::var("SCCACHE_COS_BUCKET") {
        let endpoint = env::var("SCCACHE_COS_ENDPOINT").ok();
        let key_prefix = key_prefix_from_env_var("SCCACHE_COS_KEY_PREFIX");

        Some(COSCacheConfig {
            bucket,
            endpoint,
            key_prefix,
        })
    } else {
        None
    };

    // ======= Local =======
    let disk_dir = env::var_os("SCCACHE_DIR").map(PathBuf::from);
    let disk_sz = env::var("SCCACHE_CACHE_SIZE")
        .ok()
        .and_then(|v| parse_size(&v));

    let mut preprocessor_mode_config = PreprocessorCacheModeConfig::activated();
    let preprocessor_mode_overridden = if let Some(value) = bool_from_env_var("SCCACHE_DIRECT")? {
        preprocessor_mode_config.use_preprocessor_cache_mode = value;
        true
    } else {
        false
    };

    let (disk_rw_mode, disk_rw_mode_overridden) = match env::var("SCCACHE_LOCAL_RW_MODE")
        .as_ref()
        .map(String::as_str)
    {
        Ok("READ_ONLY") => (CacheModeConfig::ReadOnly, true),
        Ok("READ_WRITE") => (CacheModeConfig::ReadWrite, true),
        Ok(_) => {
            warn!("Invalid SCCACHE_LOCAL_RW_MODE -- defaulting to READ_WRITE.");
            (CacheModeConfig::ReadWrite, false)
        }
        _ => (CacheModeConfig::ReadWrite, false),
    };

    let any_overridden = disk_dir.is_some()
        || disk_sz.is_some()
        || preprocessor_mode_overridden
        || disk_rw_mode_overridden;
    let disk = if any_overridden {
        Some(DiskCacheConfig {
            dir: disk_dir.unwrap_or_else(default_disk_cache_dir),
            size: disk_sz.unwrap_or_else(default_disk_cache_size),
            preprocessor_cache_mode: preprocessor_mode_config,
            rw_mode: disk_rw_mode,
        })
    } else {
        None
    };

    let cache = CacheConfigs {
        azure,
        disk,
        gcs,
        gha,
        memcached,
        redis,
        s3,
        webdav,
        oss,
        cos,
    };

    // ======= Base directory =======
    // Support multiple paths separated by ';' on Windows and ':' on other platforms
    // to match PATH behavior.
    #[cfg(target_os = "windows")]
    let split_symbol = ';';
    #[cfg(not(target_os = "windows"))]
    let split_symbol = ':';
    let basedirs = env::var_os("SCCACHE_BASEDIRS").map(|s| {
        s.to_string_lossy()
            .split(split_symbol)
            .filter(|s| !s.is_empty())
            .map(|s| s.to_owned())
            .collect()
    });

    Ok(EnvConfig { cache, basedirs })
}

// The directories crate changed the location of `config_dir` on macos in version 3,
// so we also check the config in `preference_dir` (new in that version), which
// corresponds to the old location, for compatibility with older setups.
fn config_file(env_var: &str, leaf: &str) -> PathBuf {
    if let Some(env_value) = env::var_os(env_var) {
        return env_value.into();
    }
    let dirs =
        ProjectDirs::from("", ORGANIZATION, APP_NAME).expect("Unable to get config directory");
    // If the new location exists, use that.
    let path = dirs.config_dir().join(leaf);
    if path.exists() {
        return path;
    }
    // If the old location exists, use that.
    let path = dirs.preference_dir().join(leaf);
    if path.exists() {
        return path;
    }
    // Otherwise, use the new location.
    dirs.config_dir().join(leaf)
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Config {
    pub cache: Option<CacheType>,
    pub fallback_cache: DiskCacheConfig,
    pub dist: DistConfig,
    pub server_startup_timeout: Option<std::time::Duration>,
    /// Base directory (or directories) to strip from paths for cache key computation.
    /// Similar to ccache's CCACHE_BASEDIR.
    pub basedirs: Vec<Vec<u8>>,
}

impl Config {
    pub fn load() -> Result<Self> {
        let env_conf = config_from_env()?;

        let file_conf_path = config_file("SCCACHE_CONF", "config");
        let file_conf = try_read_config_file(&file_conf_path)
            .context("Failed to load config file")?
            .unwrap_or_default();

        Self::from_env_and_file_configs(env_conf, file_conf)
    }

    fn from_env_and_file_configs(env_conf: EnvConfig, file_conf: FileConfig) -> Result<Self> {
        let mut conf_caches: CacheConfigs = Default::default();

        let FileConfig {
            cache,
            dist,
            server_startup_timeout_ms,
            basedirs: file_basedirs,
        } = file_conf;
        conf_caches.merge(cache);

        let server_startup_timeout =
            server_startup_timeout_ms.map(std::time::Duration::from_millis);

        let EnvConfig {
            cache,
            basedirs: env_basedirs,
        } = env_conf;
        conf_caches.merge(cache);

        // Environment variable takes precedence over file config if it is set
        let basedirs_raw = if let Some(basedirs) = env_basedirs {
            basedirs
        } else {
            file_basedirs
        };

        // Validate that all basedirs are absolute paths
        // basedirs_raw is Vec<PathBuf>
        let mut basedirs = Vec::with_capacity(basedirs_raw.len());
        for d in basedirs_raw {
            let p = Utf8TypedPathBuf::from(d);
            if !p.is_absolute() {
                bail!("Basedir path must be absolute: {:?}", p);
            }
            // Normalize basedir:
            // remove double separators, cur_dirs, parent_dirs, trailing slashes
            let p_norm = p.normalize();
            let mut bytes = p_norm.to_string().into_bytes();

            // Always add a trailing `/` to basedirs to ensure we only match complete path
            // components
            bytes.push(b'/');

            // normalize windows paths: use slashes and lowercase
            let normalized = {
                #[cfg(target_os = "windows")]
                {
                    normalize_win_path(&bytes)
                }

                #[cfg(not(target_os = "windows"))]
                {
                    bytes
                }
            };
            // push only if not already present
            if !basedirs.contains(&normalized) {
                basedirs.push(normalized);
            }
        }

        if !basedirs.is_empty() && log::log_enabled!(log::Level::Debug) {
            let basedirs_str: Vec<String> = basedirs
                .iter()
                .map(|b| String::from_utf8_lossy(b).into_owned())
                .collect();
            debug!("Using basedirs for path normalization: {:?}", basedirs_str);
        }

        let (caches, fallback_cache) = conf_caches.into_fallback();
        Ok(Self {
            cache: caches,
            fallback_cache,
            dist,
            server_startup_timeout,
            basedirs,
        })
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct CachedDistConfig {
    pub auth_tokens: HashMap<String, String>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct CachedFileConfig {
    pub dist: CachedDistConfig,
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct CachedConfig(());

impl CachedConfig {
    pub fn load() -> Result<Self> {
        let mut cached_file_config = CACHED_CONFIG.lock().unwrap();

        if cached_file_config.is_none() {
            let cfg = Self::load_file_config().context("Unable to initialise cached config")?;
            *cached_file_config = Some(cfg);
        }
        Ok(CachedConfig(()))
    }
    pub fn reload() -> Result<Self> {
        {
            let mut cached_file_config = CACHED_CONFIG.lock().unwrap();
            *cached_file_config = None;
        };
        Self::load()
    }
    pub fn with<F: FnOnce(&CachedFileConfig) -> T, T>(&self, f: F) -> T {
        let cached_file_config = CACHED_CONFIG.lock().unwrap();
        let cached_file_config = cached_file_config.as_ref().unwrap();

        f(cached_file_config)
    }
    pub fn with_mut<F: FnOnce(&mut CachedFileConfig)>(&self, f: F) -> Result<()> {
        let mut cached_file_config = CACHED_CONFIG.lock().unwrap();
        let cached_file_config = cached_file_config.as_mut().unwrap();

        let mut new_config = cached_file_config.clone();
        f(&mut new_config);
        Self::save_file_config(&new_config)?;
        *cached_file_config = new_config;
        Ok(())
    }

    fn file_config_path() -> PathBuf {
        config_file("SCCACHE_CACHED_CONF", "cached-config")
    }
    fn load_file_config() -> Result<CachedFileConfig> {
        let file_conf_path = &*CACHED_CONFIG_PATH;

        if !file_conf_path.exists() {
            let file_conf_dir = file_conf_path
                .parent()
                .expect("Cached conf file has no parent directory");
            if !file_conf_dir.is_dir() {
                fs::create_dir_all(file_conf_dir)
                    .context("Failed to create dir to hold cached config")?;
            }
            Self::save_file_config(&Default::default()).with_context(|| {
                format!(
                    "Unable to create cached config file at {}",
                    file_conf_path.display()
                )
            })?;
        }
        try_read_config_file(file_conf_path)
            .context("Failed to load cached config file")?
            .with_context(|| format!("Failed to load from {}", file_conf_path.display()))
    }
    fn save_file_config(c: &CachedFileConfig) -> Result<()> {
        let file_conf_path = &*CACHED_CONFIG_PATH;
        let mut file = File::create(file_conf_path).context("Could not open config for writing")?;
        file.write_all(toml::to_string(c).unwrap().as_bytes())
            .map_err(Into::into)
    }
}

#[cfg(feature = "dist-server")]
pub mod scheduler {
    use std::net::SocketAddr;
    use std::path::Path;

    use crate::errors::*;

    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(tag = "type")]
    #[serde(deny_unknown_fields)]
    pub enum ClientAuth {
        #[serde(rename = "DANGEROUSLY_INSECURE")]
        Insecure,
        #[serde(rename = "token")]
        Token { token: String },
        #[serde(rename = "jwt_validate")]
        JwtValidate {
            audience: String,
            issuer: String,
            jwks_url: String,
        },
        #[serde(rename = "proxy_token")]
        ProxyToken {
            url: String,
            cache_secs: Option<u64>,
        },
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(tag = "type")]
    #[serde(deny_unknown_fields)]
    pub enum ServerAuth {
        #[serde(rename = "DANGEROUSLY_INSECURE")]
        Insecure,
        #[serde(rename = "jwt_hs256")]
        JwtHS256 { secret_key: String },
        #[serde(rename = "token")]
        Token { token: String },
    }

    #[derive(Debug, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct Config {
        pub public_addr: SocketAddr,
        pub client_auth: ClientAuth,
        pub server_auth: ServerAuth,
    }

    pub fn from_path(conf_path: &Path) -> Result<Option<Config>> {
        super::try_read_config_file(conf_path).context("Failed to load scheduler config file")
    }
}

#[cfg(feature = "dist-server")]
pub mod server {
    use super::HTTPUrl;
    use serde::{Deserialize, Serialize};
    use std::net::SocketAddr;
    use std::path::{Path, PathBuf};

    use crate::errors::*;

    const TEN_GIGS: u64 = 10 * 1024 * 1024 * 1024;
    fn default_toolchain_cache_size() -> u64 {
        TEN_GIGS
    }

    const DEFAULT_POT_CLONE_FROM: &str = "sccache-template";
    const DEFAULT_POT_FS_ROOT: &str = "/opt/pot";
    const DEFAULT_POT_CMD: &str = "pot";
    const DEFAULT_POT_CLONE_ARGS: &[&str] = &["-i", "lo0|127.0.0.2"];

    fn default_pot_clone_from() -> String {
        DEFAULT_POT_CLONE_FROM.to_string()
    }

    fn default_pot_fs_root() -> PathBuf {
        DEFAULT_POT_FS_ROOT.into()
    }

    fn default_pot_cmd() -> PathBuf {
        DEFAULT_POT_CMD.into()
    }

    fn default_pot_clone_args() -> Vec<String> {
        DEFAULT_POT_CLONE_ARGS
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    #[serde(tag = "type")]
    #[serde(deny_unknown_fields)]
    pub enum BuilderType {
        #[serde(rename = "docker")]
        Docker,
        #[serde(rename = "overlay")]
        Overlay {
            build_dir: PathBuf,
            bwrap_path: PathBuf,
        },
        #[serde(rename = "pot")]
        Pot {
            #[serde(default = "default_pot_fs_root")]
            pot_fs_root: PathBuf,
            #[serde(default = "default_pot_clone_from")]
            clone_from: String,
            #[serde(default = "default_pot_cmd")]
            pot_cmd: PathBuf,
            #[serde(default = "default_pot_clone_args")]
            pot_clone_args: Vec<String>,
        },
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    #[serde(tag = "type")]
    #[serde(deny_unknown_fields)]
    pub enum SchedulerAuth {
        #[serde(rename = "DANGEROUSLY_INSECURE")]
        Insecure,
        #[serde(rename = "jwt_token")]
        JwtToken { token: String },
        #[serde(rename = "token")]
        Token { token: String },
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    #[serde(deny_unknown_fields)]
    pub struct Config {
        pub builder: BuilderType,
        pub cache_dir: PathBuf,
        pub public_addr: SocketAddr,
        pub bind_address: Option<SocketAddr>,
        pub scheduler_url: HTTPUrl,
        pub scheduler_auth: SchedulerAuth,
        #[serde(default = "default_toolchain_cache_size")]
        pub toolchain_cache_size: u64,
    }

    pub fn from_path(conf_path: &Path) -> Result<Option<Config>> {
        super::try_read_config_file(conf_path).context("Failed to load server config file")
    }
}

#[test]
fn test_parse_size() {
    assert_eq!(None, parse_size(""));
    assert_eq!(None, parse_size("bogus value"));
    assert_eq!(Some(100), parse_size("100"));
    assert_eq!(Some(2048), parse_size("2K"));
    assert_eq!(Some(2048), parse_size("2k"));
    assert_eq!(Some(10 * 1024 * 1024), parse_size("10M"));
    assert_eq!(Some(TEN_GIGS), parse_size("10G"));
    assert_eq!(Some(1024 * TEN_GIGS), parse_size("10T"));
}

#[test]
fn config_overrides() {
    let env_conf = EnvConfig {
        cache: CacheConfigs {
            azure: Some(AzureCacheConfig {
                connection_string: String::new(),
                container: String::new(),
                key_prefix: String::new(),
            }),
            disk: Some(DiskCacheConfig {
                dir: "/env-cache".into(),
                size: 5,
                preprocessor_cache_mode: Default::default(),
                rw_mode: CacheModeConfig::ReadWrite,
            }),
            redis: Some(RedisCacheConfig {
                endpoint: Some("myotherredisurl".to_owned()),
                ttl: 24 * 3600,
                key_prefix: "/redis/prefix".into(),
                db: 10,
                username: Some("user".to_owned()),
                password: Some("secret".to_owned()),
                ..Default::default()
            }),
            ..Default::default()
        },
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: CacheConfigs {
            disk: Some(DiskCacheConfig {
                dir: "/file-cache".into(),
                size: 15,
                preprocessor_cache_mode: Default::default(),
                rw_mode: CacheModeConfig::ReadWrite,
            }),
            memcached: Some(MemcachedCacheConfig {
                url: "memurl".to_owned(),
                expiration: 24 * 3600,
                key_prefix: String::new(),
                ..Default::default()
            }),
            redis: Some(RedisCacheConfig {
                url: Some("myredisurl".to_owned()),
                ttl: 25 * 3600,
                key_prefix: String::new(),
                ..Default::default()
            }),
            ..Default::default()
        },
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec![],
    };

    assert_eq!(
        Config::from_env_and_file_configs(env_conf, file_conf).unwrap(),
        Config {
            cache: Some(CacheType::Redis(RedisCacheConfig {
                endpoint: Some("myotherredisurl".to_owned()),
                ttl: 24 * 3600,
                key_prefix: "/redis/prefix".into(),
                db: 10,
                username: Some("user".to_owned()),
                password: Some("secret".to_owned()),
                ..Default::default()
            })),
            fallback_cache: DiskCacheConfig {
                dir: "/env-cache".into(),
                size: 5,
                preprocessor_cache_mode: Default::default(),
                rw_mode: CacheModeConfig::ReadWrite,
            },
            dist: Default::default(),
            server_startup_timeout: None,
            basedirs: vec![],
        }
    );
}

#[test]
#[cfg(target_os = "windows")]
fn config_basedirs_overrides() {
    // Test that env variable takes precedence over file config
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: vec!["C:/env/basedir".to_string()].into(),
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["C:/file/basedir".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert_eq!(config.basedirs, vec![b"c:/env/basedir/".to_vec()]);

    // Test that file config is used when env is None
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["C:/file/basedir".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert_eq!(config.basedirs, vec![b"c:/file/basedir/".to_vec()]);

    // Test that env config is used when env is set but empty
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: vec![].into(),
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["C:/file/basedir".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert!(config.basedirs.is_empty());

    // Test that both empty results in empty
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: vec![].into(),
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec![],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert!(config.basedirs.is_empty());
}

#[test]
#[cfg(not(target_os = "windows"))]
fn config_basedirs_overrides() {
    // Test that env variable takes precedence over file config
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: vec!["/env/basedir".to_string()].into(),
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/file/basedir".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert_eq!(config.basedirs, vec![b"/env/basedir/".to_vec()]);

    // Test that file config is used when env is None
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/file/basedir".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert_eq!(config.basedirs, vec![b"/file/basedir/".to_vec()]);

    // Test that env config is used when env is set but empty
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: vec![].into(),
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/file/basedir".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert!(config.basedirs.is_empty());

    // Test that both empty results in empty
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: vec![].into(),
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec![],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert!(config.basedirs.is_empty());
    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec![],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert!(config.basedirs.is_empty());
}

#[test]
#[cfg(not(target_os = "windows"))]
fn test_deserialize_basedirs() {
    // Test array of paths
    let toml = r#"
        basedirs = ["/home/user/project", "/home/user/workspace"]

        [cache.disk]
        dir = "/tmp/cache"
        size = 1073741824

        [dist]
    "#;

    let config: FileConfig = toml::from_str(toml).unwrap();
    assert_eq!(
        config.basedirs,
        vec![
            "/home/user/project".to_string(),
            "/home/user/workspace".to_string()
        ]
    );
}

#[test]
fn test_deserialize_basedirs_missing() {
    // Test no basedirs specified (should default to empty vec)
    let toml = r#"
        [cache.disk]
        dir = "/tmp/cache"
        size = 1073741824

        [dist]
    "#;

    let config: FileConfig = toml::from_str(toml).unwrap();
    assert!(config.basedirs.is_empty());
}

#[test]
#[serial(config_from_env)]
#[cfg(not(target_os = "windows"))]
fn test_env_basedirs_single() {
    unsafe {
        std::env::set_var("SCCACHE_BASEDIRS", "/home/user/project");
    }
    let config = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        config.basedirs.expect("SCCACHE_BASEDIRS is set"),
        vec!["/home/user/project".to_string()]
    );
}

#[test]
#[serial(config_from_env)]
#[cfg(target_os = "windows")]
fn test_env_basedirs_single() {
    unsafe {
        std::env::set_var("SCCACHE_BASEDIRS", "C:/home/user/project");
    }
    let config = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        config.basedirs.expect("SCCACHE_BASEDIRS is set"),
        vec!["C:/home/user/project".to_string()]
    );
}

#[test]
#[serial(config_from_env)]
#[cfg(not(target_os = "windows"))]
fn test_env_basedirs_multiple() {
    unsafe {
        std::env::set_var(
            "SCCACHE_BASEDIRS",
            "/home/user/project:/home/user/workspace",
        );
    }
    let config = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        config.basedirs.expect("SCCACHE_BASEDIRS is set"),
        vec![
            "/home/user/project".to_string(),
            "/home/user/workspace".to_string()
        ]
    );
}

#[test]
#[serial(config_from_env)]
#[cfg(target_os = "windows")]
fn test_env_basedirs_multiple() {
    unsafe {
        std::env::set_var(
            "SCCACHE_BASEDIRS",
            "C:/home/user/project;C:/home/user/workspace",
        );
    }
    let config = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        config.basedirs.expect("SCCACHE_BASEDIRS is set"),
        vec![
            "C:/home/user/project".to_string(),
            "C:/home/user/workspace".to_string()
        ]
    );
}

#[test]
#[serial(config_from_env)]
#[cfg(not(target_os = "windows"))]
fn test_env_basedirs_with_spaces() {
    // Test that spaces around paths are not trimmed
    unsafe {
        std::env::set_var(
            "SCCACHE_BASEDIRS",
            " /home/user/project : /home/user/workspace ",
        );
    }
    let env_conf = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        env_conf.basedirs.clone().expect("SCCACHE_BASEDIRS is set"),
        vec![
            " /home/user/project ".to_string(),
            " /home/user/workspace ".to_string()
        ]
    );
    // The lead to trailing spaces are preserved and server fails to start
    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec![],
    };
    Config::from_env_and_file_configs(env_conf, file_conf)
        .expect_err("Should fail due to non-absolute path");
}

#[test]
#[serial(config_from_env)]
#[cfg(target_os = "windows")]
fn test_env_basedirs_with_spaces() {
    // Test that spaces around paths are not trimmed
    unsafe {
        std::env::set_var(
            "SCCACHE_BASEDIRS",
            " C:/home/user/project ; C:/home/user/workspace ",
        );
    }
    let env_conf = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        env_conf.basedirs.clone().expect("SCCACHE_BASEDIRS is set"),
        vec![
            " C:/home/user/project ".to_string(),
            " C:/home/user/workspace ".to_string()
        ]
    );
    // The lead to trailing spaces are preserved and server fails to start
    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec![],
    };
    Config::from_env_and_file_configs(env_conf, file_conf)
        .expect_err("Should fail due to non-absolute path");
}

#[test]
#[serial(config_from_env)]
#[cfg(not(target_os = "windows"))]
fn test_env_basedirs_empty_entries() {
    // Test that empty entries are filtered out
    unsafe {
        std::env::set_var(
            "SCCACHE_BASEDIRS",
            "/home/user/project::/home/user/workspace",
        );
    }
    let config = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        config.basedirs.expect("SCCACHE_BASEDIRS is set"),
        vec![
            "/home/user/project".to_string(),
            "/home/user/workspace".to_string()
        ]
    );
}

#[test]
#[serial(config_from_env)]
#[cfg(target_os = "windows")]
fn test_env_basedirs_empty_entries() {
    // Test that empty entries are filtered out
    unsafe {
        std::env::set_var(
            "SCCACHE_BASEDIRS",
            "c:/home/user/project;;c:/home/user/workspace",
        );
    }
    let config = config_from_env().unwrap();
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }

    assert_eq!(
        config.basedirs.expect("SCCACHE_BASEDIRS is set"),
        vec![
            "c:/home/user/project".to_string(),
            "c:/home/user/workspace".to_string()
        ]
    );
}

#[test]
#[serial(config_from_env)]
fn test_env_basedirs_not_set() {
    unsafe {
        std::env::remove_var("SCCACHE_BASEDIRS");
    }
    let config = config_from_env().unwrap();
    assert!(config.basedirs.is_none());
}

#[test]
#[serial(config_from_env)]
#[cfg(feature = "s3")]
fn test_s3_no_credentials_conflict() {
    unsafe {
        env::set_var("SCCACHE_S3_NO_CREDENTIALS", "true");
        env::set_var("SCCACHE_BUCKET", "my-bucket");
        env::set_var("AWS_ACCESS_KEY_ID", "aws-access-key-id");
        env::set_var("AWS_SECRET_ACCESS_KEY", "aws-secret-access-key");
    }

    let cfg = config_from_env();

    unsafe {
        env::remove_var("SCCACHE_S3_NO_CREDENTIALS");
        env::remove_var("SCCACHE_BUCKET");
        env::remove_var("AWS_ACCESS_KEY_ID");
        env::remove_var("AWS_SECRET_ACCESS_KEY");
    }

    let error = cfg.unwrap_err();
    assert_eq!(
        "If setting S3 credentials, SCCACHE_S3_NO_CREDENTIALS must not be set.",
        error.to_string()
    );
}

#[test]
#[serial(config_from_env)]
fn test_s3_no_credentials_invalid() {
    unsafe {
        env::set_var("SCCACHE_S3_NO_CREDENTIALS", "yes");
        env::set_var("SCCACHE_BUCKET", "my-bucket");
    }

    let cfg = config_from_env();

    unsafe {
        env::remove_var("SCCACHE_S3_NO_CREDENTIALS");
        env::remove_var("SCCACHE_BUCKET");
    }

    let error = cfg.unwrap_err();
    assert_eq!(
        "SCCACHE_S3_NO_CREDENTIALS must be 'true', 'on', '1', 'false', 'off' or '0'.",
        error.to_string()
    );
}

#[test]
#[serial(config_from_env)]
fn test_s3_no_credentials_valid_true() {
    unsafe {
        env::set_var("SCCACHE_S3_NO_CREDENTIALS", "true");
        env::set_var("SCCACHE_BUCKET", "my-bucket");
    }

    let cfg = config_from_env();

    unsafe {
        env::remove_var("SCCACHE_S3_NO_CREDENTIALS");
        env::remove_var("SCCACHE_BUCKET");
    }

    let env_cfg = cfg.unwrap();
    match env_cfg.cache.s3 {
        Some(S3CacheConfig {
            ref bucket,
            no_credentials,
            ..
        }) => {
            assert_eq!(bucket, "my-bucket");
            assert!(no_credentials);
        }
        None => unreachable!(),
    };
}

#[test]
#[serial(config_from_env)]
fn test_s3_no_credentials_valid_false() {
    unsafe {
        env::set_var("SCCACHE_S3_NO_CREDENTIALS", "false");
        env::set_var("SCCACHE_BUCKET", "my-bucket");
    }

    let cfg = config_from_env();

    unsafe {
        env::remove_var("SCCACHE_S3_NO_CREDENTIALS");
        env::remove_var("SCCACHE_BUCKET");
    }

    let env_cfg = cfg.unwrap();
    match env_cfg.cache.s3 {
        Some(S3CacheConfig {
            ref bucket,
            no_credentials,
            ..
        }) => {
            assert_eq!(bucket, "my-bucket");
            assert!(!no_credentials);
        }
        None => unreachable!(),
    };
}

#[test]
#[serial(config_from_env)]
#[cfg(feature = "gcs")]
fn test_gcs_service_account() {
    unsafe {
        env::set_var("SCCACHE_GCS_BUCKET", "my-bucket");
        env::set_var("SCCACHE_GCS_SERVICE_ACCOUNT", "my@example.com");
        env::set_var("SCCACHE_GCS_RW_MODE", "READ_WRITE");
    }

    let cfg = config_from_env();

    unsafe {
        env::remove_var("SCCACHE_GCS_BUCKET");
        env::remove_var("SCCACHE_GCS_SERVICE_ACCOUNT");
        env::remove_var("SCCACHE_GCS_RW_MODE");
    }

    let env_cfg = cfg.unwrap();
    match env_cfg.cache.gcs {
        Some(GCSCacheConfig {
            ref bucket,
            service_account,
            rw_mode,
            ..
        }) => {
            assert_eq!(bucket, "my-bucket");
            assert_eq!(service_account, Some("my@example.com".to_string()));
            assert_eq!(rw_mode, CacheModeConfig::ReadWrite);
        }
        None => unreachable!(),
    };
}

#[test]
fn full_toml_parse() {
    const CONFIG_STR: &str = r#"
server_startup_timeout_ms = 10000

[dist]
# where to find the scheduler
scheduler_url = "http://1.2.3.4:10600"
# a set of prepackaged toolchains
toolchains = []
# the maximum size of the toolchain cache in bytes
toolchain_cache_size = 5368709120
cache_dir = "/home/user/.cache/sccache-dist-client"

[dist.auth]
type = "token"
token = "secrettoken"


#[cache.azure]
# does not work as it appears

[cache.disk]
dir = "/tmp/.cache/sccache"
size = 7516192768 # 7 GiBytes

[cache.gcs]
rw_mode = "READ_ONLY"
# rw_mode = "READ_WRITE"
cred_path = "/psst/secret/cred"
bucket = "bucket"
key_prefix = "prefix"
service_account = "example_service_account"

[cache.gha]
enabled = true
version = "sccache"

[cache.memcached]
# Deprecated alias for `endpoint`
# url = "127.0.0.1:11211"
endpoint = "tcp://127.0.0.1:11211"
# Username and password for authentication
username = "user"
password = "passwd"
expiration = 90000
key_prefix = "/custom/prefix/if/need"

[cache.redis]
url = "redis://user:passwd@1.2.3.4:6379/?db=1"
endpoint = "redis://127.0.0.1:6379"
cluster_endpoints = "tcp://10.0.0.1:6379,redis://10.0.0.2:6379"
username = "another_user"
password = "new_passwd"
db = 12
expiration = 86400
key_prefix = "/my/redis/cache"

[cache.s3]
bucket = "name"
region = "us-east-2"
endpoint = "s3-us-east-1.amazonaws.com"
use_ssl = true
key_prefix = "s3prefix"
no_credentials = true
server_side_encryption = false

[cache.webdav]
endpoint = "http://127.0.0.1:8080"
key_prefix = "webdavprefix"
username = "webdavusername"
password = "webdavpassword"
token = "webdavtoken"

[cache.oss]
bucket = "name"
endpoint = "oss-us-east-1.aliyuncs.com"
key_prefix = "ossprefix"
no_credentials = true

[cache.cos]
bucket = "name"
endpoint = "cos.na-siliconvalley.myqcloud.com"
key_prefix = "cosprefix"
"#;

    let file_config: FileConfig = toml::from_str(CONFIG_STR).expect("Is valid toml.");
    assert_eq!(
        file_config,
        FileConfig {
            cache: CacheConfigs {
                azure: None, // TODO not sure how to represent a unit struct in TOML Some(AzureCacheConfig),
                disk: Some(DiskCacheConfig {
                    dir: PathBuf::from("/tmp/.cache/sccache"),
                    size: 7 * 1024 * 1024 * 1024,
                    preprocessor_cache_mode: PreprocessorCacheModeConfig::activated(),
                    rw_mode: CacheModeConfig::ReadWrite,
                }),
                gcs: Some(GCSCacheConfig {
                    bucket: "bucket".to_owned(),
                    cred_path: Some("/psst/secret/cred".to_string()),
                    service_account: Some("example_service_account".to_string()),
                    rw_mode: CacheModeConfig::ReadOnly,
                    key_prefix: "prefix".into(),
                    credential_url: None,
                }),
                gha: Some(GHACacheConfig {
                    enabled: true,
                    version: "sccache".to_string()
                }),
                redis: Some(RedisCacheConfig {
                    url: Some("redis://user:passwd@1.2.3.4:6379/?db=1".to_owned()),
                    endpoint: Some("redis://127.0.0.1:6379".to_owned()),
                    cluster_endpoints: Some("tcp://10.0.0.1:6379,redis://10.0.0.2:6379".to_owned()),
                    username: Some("another_user".to_owned()),
                    password: Some("new_passwd".to_owned()),
                    db: 12,
                    ttl: 24 * 3600,
                    key_prefix: "/my/redis/cache".into(),
                }),
                memcached: Some(MemcachedCacheConfig {
                    url: "tcp://127.0.0.1:11211".to_owned(),
                    username: Some("user".to_owned()),
                    password: Some("passwd".to_owned()),
                    expiration: 25 * 3600,
                    key_prefix: "/custom/prefix/if/need".into(),
                }),
                s3: Some(S3CacheConfig {
                    bucket: "name".to_owned(),
                    region: Some("us-east-2".to_owned()),
                    endpoint: Some("s3-us-east-1.amazonaws.com".to_owned()),
                    use_ssl: Some(true),
                    key_prefix: "s3prefix".into(),
                    no_credentials: true,
                    server_side_encryption: Some(false),
                    enable_virtual_host_style: None,
                }),
                webdav: Some(WebdavCacheConfig {
                    endpoint: "http://127.0.0.1:8080".to_string(),
                    key_prefix: "webdavprefix".into(),
                    username: Some("webdavusername".to_string()),
                    password: Some("webdavpassword".to_string()),
                    token: Some("webdavtoken".to_string()),
                }),
                oss: Some(OSSCacheConfig {
                    bucket: "name".to_owned(),
                    endpoint: Some("oss-us-east-1.aliyuncs.com".to_owned()),
                    key_prefix: "ossprefix".into(),
                    no_credentials: true,
                }),
                cos: Some(COSCacheConfig {
                    bucket: "name".to_owned(),
                    endpoint: Some("cos.na-siliconvalley.myqcloud.com".to_owned()),
                    key_prefix: "cosprefix".into(),
                }),
            },
            dist: DistConfig {
                auth: DistAuth::Token {
                    token: "secrettoken".to_owned()
                },
                #[cfg(any(feature = "dist-client", feature = "dist-server"))]
                scheduler_url: Some(
                    parse_http_url("http://1.2.3.4:10600")
                        .map(|url| { HTTPUrl::from_url(url) })
                        .expect("Scheduler url must be valid url str")
                ),
                #[cfg(not(any(feature = "dist-client", feature = "dist-server")))]
                scheduler_url: Some("http://1.2.3.4:10600".to_owned()),
                cache_dir: PathBuf::from("/home/user/.cache/sccache-dist-client"),
                toolchains: vec![],
                toolchain_cache_size: 5368709120,
                rewrite_includes_only: false,
            },
            server_startup_timeout_ms: Some(10000),
            basedirs: vec![],
        }
    )
}

#[test]
#[cfg(feature = "dist-server")]
fn server_toml_parse() {
    use server::BuilderType;
    use server::SchedulerAuth;
    const CONFIG_STR: &str = r#"
    # This is where client toolchains will be stored.
    cache_dir = "/tmp/toolchains"
    # The maximum size of the toolchain cache, in bytes.
    # If unspecified the default is 10GB.
    toolchain_cache_size = 10737418240
    # A public IP address and port that clients will use to connect to this builder.
    public_addr = "192.168.1.1:10501"
    # The socket address the builder will listen on.
    bind_address = "0.0.0.0:10501"
    # The URL used to connect to the scheduler (should use https, given an ideal
    # setup of a HTTPS server in front of the scheduler)
    scheduler_url = "https://192.168.1.1"

    [builder]
    type = "overlay"
    # The directory under which a sandboxed filesystem will be created for builds.
    build_dir = "/tmp/build"
    # The path to the bubblewrap version 0.3.0+ `bwrap` binary.
    bwrap_path = "/usr/bin/bwrap"

    [scheduler_auth]
    type = "jwt_token"
    # This will be generated by the `generate-jwt-hs256-server-token` command or
    # provided by an administrator of the sccache cluster.
    token = "my server's token"
    "#;

    let server_config: server::Config = toml::from_str(CONFIG_STR).expect("Is valid toml.");
    assert_eq!(
        server_config,
        server::Config {
            builder: BuilderType::Overlay {
                build_dir: PathBuf::from("/tmp/build"),
                bwrap_path: PathBuf::from("/usr/bin/bwrap"),
            },
            cache_dir: PathBuf::from("/tmp/toolchains"),
            public_addr: "192.168.1.1:10501"
                .parse()
                .expect("Public address must be valid socket address"),
            bind_address: Some(
                "0.0.0.0:10501"
                    .parse()
                    .expect("Bind address must be valid socket address")
            ),

            scheduler_url: parse_http_url("https://192.168.1.1")
                .map(|url| { HTTPUrl::from_url(url) })
                .expect("Scheduler url must be valid url str"),
            scheduler_auth: SchedulerAuth::JwtToken {
                token: "my server's token".to_owned()
            },
            toolchain_cache_size: 10737418240,
        }
    )
}

#[test]
fn human_units_parse() {
    const CONFIG_STR: &str = r#"
[dist]
toolchain_cache_size = "5g"

[cache.disk]
size = "7g"
"#;

    let file_config: FileConfig = toml::from_str(CONFIG_STR).expect("Is valid toml.");
    assert_eq!(
        file_config,
        FileConfig {
            cache: CacheConfigs {
                disk: Some(DiskCacheConfig {
                    size: 7 * 1024 * 1024 * 1024,
                    ..Default::default()
                }),
                ..Default::default()
            },
            dist: DistConfig {
                toolchain_cache_size: 5 * 1024 * 1024 * 1024,
                ..Default::default()
            },
            server_startup_timeout_ms: None,
            basedirs: vec![],
        }
    );
}

// Integration tests: Config normalization + strip_basedirs usage

#[test]
#[cfg(not(target_os = "windows"))]
fn test_integration_config_normalizes_and_strips() {
    // Test that Config normalizes basedirs and strip_basedirs uses them correctly
    use crate::util::strip_basedirs;
    use std::borrow::Cow;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/home/user/project".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();

    // Verify config normalized the basedir with trailing slash
    assert_eq!(config.basedirs, vec![b"/home/user/project/"]);

    // Test that strip_basedirs uses the normalized basedir
    let input = b"# 1 \"/home/user/project/src/main.c\"\nint main() { return 0; }";
    let output = strip_basedirs(input, &config.basedirs);

    // Should strip the basedir
    let expected = b"# 1 \"src/main.c\"\nint main() { return 0; }";
    assert_eq!(&*output, expected);
    assert!(matches!(output, Cow::Owned(_)));
}

#[test]
#[cfg(not(target_os = "windows"))]
fn test_integration_normalized_path_with_double_slashes() {
    // Test that Config normalizes paths with double slashes
    use crate::util::strip_basedirs;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/home//user///project/".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();

    // Config should normalize to single slashes with one trailing slash
    assert_eq!(config.basedirs, vec![b"/home/user/project/"]);

    // Verify it works with strip_basedirs
    let input = b"# 1 \"/home/user/project/src/main.c\"";
    let output = strip_basedirs(input, &config.basedirs);
    assert_eq!(&*output, b"# 1 \"src/main.c\"");
}

#[test]
#[cfg(target_os = "windows")]
fn test_integration_windows_path_normalization() {
    // Test that Config normalizes Windows paths correctly
    use crate::util::strip_basedirs;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["C:\\Users\\Test\\Project".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();

    // Should be normalized to lowercase with forward slashes
    assert_eq!(config.basedirs, vec![b"c:/users/test/project/"]);

    // Test with mixed case preprocessor output
    let input = b"# 1 \"C:\\Users\\Test\\Project\\src\\main.c\"";
    let output = strip_basedirs(input, &config.basedirs);
    assert_eq!(&*output, b"# 1 \"src\\main.c\"");
}

#[test]
#[cfg(not(target_os = "windows"))]
fn test_integration_cow_borrowed_when_no_match() {
    // Test that strip_basedirs returns Cow::Borrowed when no stripping occurs
    use crate::util::strip_basedirs;
    use std::borrow::Cow;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/home/user/project".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();

    // Input doesn't contain the basedir
    let input = b"# 1 \"/other/path/main.c\"\nint main() { return 0; }";
    let output = strip_basedirs(input, &config.basedirs);

    // Should return borrowed reference (no allocation)
    assert!(matches!(output, Cow::Borrowed(_)));
    assert_eq!(&*output, input);
}

#[test]
#[cfg(not(target_os = "windows"))]
fn test_integration_cow_borrowed_when_empty_basedirs() {
    // Test that strip_basedirs returns Cow::Borrowed when basedirs is empty
    use crate::util::strip_basedirs;
    use std::borrow::Cow;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec![],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert!(config.basedirs.is_empty());

    let input = b"# 1 \"/home/user/project/src/main.c\"";
    let output = strip_basedirs(input, &config.basedirs);

    // Should return borrowed reference when basedirs is empty
    assert!(matches!(output, Cow::Borrowed(_)));
    assert_eq!(&*output, input);
}

#[test]
#[cfg(not(target_os = "windows"))]
fn test_integration_multiple_basedirs_longest_match() {
    // Test that strip_basedirs prefers longest match with normalized basedirs
    use crate::util::strip_basedirs;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/home/user".to_string(), "/home/user/project".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();

    // Both should be normalized with trailing slashes
    assert_eq!(config.basedirs.len(), 2);
    assert_eq!(config.basedirs[0], b"/home/user/");
    assert_eq!(config.basedirs[1], b"/home/user/project/");

    // Input matches both, but longest should win
    let input = b"# 1 \"/home/user/project/src/main.c\"";
    let output = strip_basedirs(input, &config.basedirs);

    // Should match the longest basedir (/home/user/project/)
    let expected = b"# 1 \"src/main.c\"";
    assert_eq!(&*output, expected);
}

#[test]
#[cfg(not(target_os = "windows"))]
fn test_integration_paths_with_dots_normalized() {
    // Test that paths with . and .. are normalized correctly
    use crate::util::strip_basedirs;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["/home/user/./project/../project".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();

    // Should be normalized to remove ./ and ../
    assert_eq!(config.basedirs[0], b"/home/user/project/");

    // Verify it works with strip_basedirs
    let input = b"# 1 \"/home/user/project/src/main.c\"";
    let output = strip_basedirs(input, &config.basedirs);
    let expected = b"# 1 \"src/main.c\"";
    assert_eq!(&*output, expected);
}

#[test]
#[cfg(target_os = "windows")]
fn test_integration_windows_mixed_slashes() {
    // Test Windows path with mixed slashes in preprocessor output
    use crate::util::strip_basedirs;

    let env_conf = EnvConfig {
        cache: Default::default(),
        basedirs: None,
    };

    let file_conf = FileConfig {
        cache: Default::default(),
        dist: Default::default(),
        server_startup_timeout_ms: None,
        basedirs: vec!["C:\\Users\\test\\project".to_string()],
    };

    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();
    assert_eq!(config.basedirs[0], b"c:/users/test/project/");

    // Preprocessor output with mixed slashes
    let input = b"# 1 \"C:/Users\\test\\project\\src/main.c\"";
    let output = strip_basedirs(input, &config.basedirs);

    // Should strip despite mixed slashes
    let expected = b"# 1 \"src/main.c\"";
    assert_eq!(&*output, expected);
}

#[test]
#[serial(config_from_env)]
#[cfg(not(target_os = "windows"))]
fn test_integration_env_variable_to_strip() {
    // Test full flow: SCCACHE_BASEDIRS env var -> Config -> strip_basedirs
    use crate::util::strip_basedirs;

    unsafe {
        env::set_var("SCCACHE_BASEDIRS", "/home/user/project:/tmp/build");
    }

    let env_conf = config_from_env().unwrap();
    let file_conf = FileConfig::default();
    let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap();

    unsafe {
        env::remove_var("SCCACHE_BASEDIRS");
    }

    // Should have two normalized basedirs
    assert_eq!(config.basedirs.len(), 2);
    assert_eq!(config.basedirs[0], b"/home/user/project/");
    assert_eq!(config.basedirs[1], b"/tmp/build/");

    // Test stripping with both
    let input1 = b"# 1 \"/home/user/project/src/main.c\"";
    let output1 = strip_basedirs(input1, &config.basedirs);
    assert_eq!(&*output1, b"# 1 \"src/main.c\"");

    let input2 = b"# 1 \"/tmp/build/obj/file.o\"";
    let output2 = strip_basedirs(input2, &config.basedirs);
    assert_eq!(&*output2, b"# 1 \"obj/file.o\"");
}