summaryrefslogtreecommitdiff
path: root/usr/src/tools/scripts/webrev.sh
blob: 104ce0512c307b4c80f949f11e7105a9ec7ffa1a (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
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
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
#!/usr/bin/ksh93 -p
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2008, 2010, Richard Lowe
# Copyright 2012 Marcel Telka <marcel@telka.sk>
# Copyright 2014 Bart Coddens <bart.coddens@gmail.com>
# Copyright 2017 Nexenta Systems, Inc.
# Copyright 2019 Joyent, Inc.
# Copyright 2016 RackTop Systems.
#

#
# This script takes a file list and a workspace and builds a set of html files
# suitable for doing a code review of source changes via a web page.
# Documentation is available via the manual page, webrev.1, or just
# type 'webrev -h'.
#
# Acknowledgements to contributors to webrev are listed in the webrev(1)
# man page.
#

REMOVED_COLOR=brown
CHANGED_COLOR=blue
NEW_COLOR=blue

HTML='<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n'

FRAMEHTML='<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n'

STDHEAD='<meta http-equiv="cache-control" content="no-cache"></meta>
<meta http-equiv="Content-Type" content="text/xhtml;charset=utf-8"></meta>
<meta http-equiv="Pragma" content="no-cache"></meta>
<meta http-equiv="Expires" content="-1"></meta>
<!--
   Note to customizers: the body of the webrev is IDed as SUNWwebrev
   to allow easy overriding by users of webrev via the userContent.css
   mechanism available in some browsers.

   For example, to have all "removed" information be red instead of
   brown, set a rule in your userContent.css file like:

       body#SUNWwebrev span.removed { color: red ! important; }
-->
<style type="text/css" media="screen">
body {
    background-color: #eeeeee;
}
hr {
    border: none 0;
    border-top: 1px solid #aaa;
    height: 1px;
}
div.summary {
    font-size: .8em;
    border-bottom: 1px solid #aaa;
    padding-left: 1em;
    padding-right: 1em;
}
div.summary h2 {
    margin-bottom: 0.3em;
}
div.summary table th {
    text-align: right;
    vertical-align: top;
    white-space: nowrap;
}
span.lineschanged {
    font-size: 0.7em;
}
span.oldmarker {
    color: red;
    font-size: large;
    font-weight: bold;
}
span.newmarker {
    color: green;
    font-size: large;
    font-weight: bold;
}
span.removed {
    color: brown;
}
span.changed {
    color: blue;
}
span.new {
    color: blue;
    font-weight: bold;
}
span.chmod {
    font-size: 0.7em;
    color: #db7800;
}
a.print { font-size: x-small; }
a:hover { background-color: #ffcc99; }
</style>

<style type="text/css" media="print">
pre { font-size: 0.8em; font-family: courier, monospace; }
span.removed { color: #444; font-style: italic }
span.changed { font-weight: bold; }
span.new { font-weight: bold; }
span.newmarker { font-size: 1.2em; font-weight: bold; }
span.oldmarker { font-size: 1.2em; font-weight: bold; }
a.print {display: none}
hr { border: none 0; border-top: 1px solid #aaa; height: 1px; }
</style>
'

#
# UDiffs need a slightly different CSS rule for 'new' items (we don't
# want them to be bolded as we do in cdiffs or sdiffs).
#
UDIFFCSS='
<style type="text/css" media="screen">
span.new {
    color: blue;
    font-weight: normal;
}
</style>
'

# CSS for the HTML version of the man pages.
# Current version is from mandoc 1.14.5.
MANCSS='
/* $Id: mandoc.css,v 1.45 2019/03/01 10:57:18 schwarze Exp $ */
/*
 * Standard style sheet for mandoc(1) -Thtml and man.cgi(8).
 *
 * Written by Ingo Schwarze <schwarze@openbsd.org>.
 * I place this file into the public domain.
 * Permission to use, copy, modify, and distribute it for any purpose
 * with or without fee is hereby granted, without any conditions.
 */

/* Global defaults. */

html {		max-width: 65em; }
body {		font-family: Helvetica,Arial,sans-serif; }
table {		margin-top: 0em;
		margin-bottom: 0em;
		border-collapse: collapse; }
/* Some browsers set border-color in a browser style for tbody,
 * but not for table, resulting in inconsistent border styling. */
tbody {		border-color: inherit; }
tr {		border-color: inherit; }
td {		vertical-align: top;
		padding-left: 0.2em;
		padding-right: 0.2em;
		border-color: inherit; }
ul, ol, dl {	margin-top: 0em;
		margin-bottom: 0em; }
li, dt {	margin-top: 1em; }

.permalink {	border-bottom: thin dotted;
		color: inherit;
		font: inherit;
		text-decoration: inherit; }
* {		clear: both }

/* Search form and search results. */

fieldset {	border: thin solid silver;
		border-radius: 1em;
		text-align: center; }
input[name=expr] {
		width: 25%; }

table.results {	margin-top: 1em;
		margin-left: 2em;
		font-size: smaller; }

/* Header and footer lines. */

table.head {	width: 100%;
		border-bottom: 1px dotted #808080;
		margin-bottom: 1em;
		font-size: smaller; }
td.head-vol {	text-align: center; }
td.head-rtitle {
		text-align: right; }

table.foot {	width: 100%;
		border-top: 1px dotted #808080;
		margin-top: 1em;
		font-size: smaller; }
td.foot-os {	text-align: right; }

/* Sections and paragraphs. */

.manual-text {
		margin-left: 3.8em; }
.Nd { }
section.Sh { }
h1.Sh {		margin-top: 1.2em;
		margin-bottom: 0.6em;
		margin-left: -3.2em;
		font-size: 110%; }
section.Ss { }
h2.Ss {		margin-top: 1.2em;
		margin-bottom: 0.6em;
		margin-left: -1.2em;
		font-size: 105%; }
.Pp {		margin: 0.6em 0em; }
.Sx { }
.Xr { }

/* Displays and lists. */

.Bd { }
.Bd-indent {	margin-left: 3.8em; }

.Bl-bullet {	list-style-type: disc;
		padding-left: 1em; }
.Bl-bullet > li { }
.Bl-dash {	list-style-type: none;
		padding-left: 0em; }
.Bl-dash > li:before {
		content: "\2014  "; }
.Bl-item {	list-style-type: none;
		padding-left: 0em; }
.Bl-item > li { }
.Bl-compact > li {
		margin-top: 0em; }

.Bl-enum {	padding-left: 2em; }
.Bl-enum > li { }
.Bl-compact > li {
		margin-top: 0em; }

.Bl-diag { }
.Bl-diag > dt {
		font-style: normal;
		font-weight: bold; }
.Bl-diag > dd {
		margin-left: 0em; }
.Bl-hang { }
.Bl-hang > dt { }
.Bl-hang > dd {
		margin-left: 5.5em; }
.Bl-inset { }
.Bl-inset > dt { }
.Bl-inset > dd {
		margin-left: 0em; }
.Bl-ohang { }
.Bl-ohang > dt { }
.Bl-ohang > dd {
		margin-left: 0em; }
.Bl-tag {	margin-top: 0.6em;
		margin-left: 5.5em; }
.Bl-tag > dt {
		float: left;
		margin-top: 0em;
		margin-left: -5.5em;
		padding-right: 0.5em;
		vertical-align: top; }
.Bl-tag > dd {
		clear: right;
		width: 100%;
		margin-top: 0em;
		margin-left: 0em;
		margin-bottom: 0.6em;
		vertical-align: top;
		overflow: auto; }
.Bl-compact {	margin-top: 0em; }
.Bl-compact > dd {
		margin-bottom: 0em; }
.Bl-compact > dt {
		margin-top: 0em; }

.Bl-column { }
.Bl-column > tbody > tr { }
.Bl-column > tbody > tr > td {
		margin-top: 1em; }
.Bl-compact > tbody > tr > td {
		margin-top: 0em; }

.Rs {		font-style: normal;
		font-weight: normal; }
.RsA { }
.RsB {		font-style: italic;
		font-weight: normal; }
.RsC { }
.RsD { }
.RsI {		font-style: italic;
		font-weight: normal; }
.RsJ {		font-style: italic;
		font-weight: normal; }
.RsN { }
.RsO { }
.RsP { }
.RsQ { }
.RsR { }
.RsT {		text-decoration: underline; }
.RsU { }
.RsV { }

.eqn { }
.tbl td {	vertical-align: middle; }

.HP {		margin-left: 3.8em;
		text-indent: -3.8em; }

/* Semantic markup for command line utilities. */

table.Nm { }
code.Nm {	font-style: normal;
		font-weight: bold;
		font-family: inherit; }
.Fl {		font-style: normal;
		font-weight: bold;
		font-family: inherit; }
.Cm {		font-style: normal;
		font-weight: bold;
		font-family: inherit; }
.Ar {		font-style: italic;
		font-weight: normal; }
.Op {		display: inline; }
.Ic {		font-style: normal;
		font-weight: bold;
		font-family: inherit; }
.Ev {		font-style: normal;
		font-weight: normal;
		font-family: monospace; }
.Pa {		font-style: italic;
		font-weight: normal; }

/* Semantic markup for function libraries. */

.Lb { }
code.In {	font-style: normal;
		font-weight: bold;
		font-family: inherit; }
a.In { }
.Fd {		font-style: normal;
		font-weight: bold;
		font-family: inherit; }
.Ft {		font-style: italic;
		font-weight: normal; }
.Fn {		font-style: normal;
		font-weight: bold;
		font-family: inherit; }
.Fa {		font-style: italic;
		font-weight: normal; }
.Vt {		font-style: italic;
		font-weight: normal; }
.Va {		font-style: italic;
		font-weight: normal; }
.Dv {		font-style: normal;
		font-weight: normal;
		font-family: monospace; }
.Er {		font-style: normal;
		font-weight: normal;
		font-family: monospace; }

/* Various semantic markup. */

.An { }
.Lk { }
.Mt { }
.Cd {		font-style: normal;
		font-weight: bold;
		font-family: inherit; }
.Ad {		font-style: italic;
		font-weight: normal; }
.Ms {		font-style: normal;
		font-weight: bold; }
.St { }
.Ux { }

/* Physical markup. */

.Bf {		display: inline; }
.No {		font-style: normal;
		font-weight: normal; }
.Em {		font-style: italic;
		font-weight: normal; }
.Sy {		font-style: normal;
		font-weight: bold; }
.Li {		font-style: normal;
		font-weight: normal;
		font-family: monospace; }

/* Tooltip support. */

h1.Sh, h2.Ss {	position: relative; }
.An, .Ar, .Cd, .Cm, .Dv, .Em, .Er, .Ev, .Fa, .Fd, .Fl, .Fn, .Ft,
.Ic, code.In, .Lb, .Lk, .Ms, .Mt, .Nd, code.Nm, .Pa, .Rs,
.St, .Sx, .Sy, .Va, .Vt, .Xr {
		display: inline-block;
		position: relative; }

.An::before {	content: "An"; }
.Ar::before {	content: "Ar"; }
.Cd::before {	content: "Cd"; }
.Cm::before {	content: "Cm"; }
.Dv::before {	content: "Dv"; }
.Em::before {	content: "Em"; }
.Er::before {	content: "Er"; }
.Ev::before {	content: "Ev"; }
.Fa::before {	content: "Fa"; }
.Fd::before {	content: "Fd"; }
.Fl::before {	content: "Fl"; }
.Fn::before {	content: "Fn"; }
.Ft::before {	content: "Ft"; }
.Ic::before {	content: "Ic"; }
code.In::before { content: "In"; }
.Lb::before {	content: "Lb"; }
.Lk::before {	content: "Lk"; }
.Ms::before {	content: "Ms"; }
.Mt::before {	content: "Mt"; }
.Nd::before {	content: "Nd"; }
code.Nm::before { content: "Nm"; }
.Pa::before {	content: "Pa"; }
.Rs::before {	content: "Rs"; }
h1.Sh::before {	content: "Sh"; }
h2.Ss::before {	content: "Ss"; }
.St::before {	content: "St"; }
.Sx::before {	content: "Sx"; }
.Sy::before {	content: "Sy"; }
.Va::before {	content: "Va"; }
.Vt::before {	content: "Vt"; }
.Xr::before {	content: "Xr"; }

.An::before, .Ar::before, .Cd::before, .Cm::before,
.Dv::before, .Em::before, .Er::before, .Ev::before,
.Fa::before, .Fd::before, .Fl::before, .Fn::before, .Ft::before,
.Ic::before, code.In::before, .Lb::before, .Lk::before,
.Ms::before, .Mt::before, .Nd::before, code.Nm::before,
.Pa::before, .Rs::before,
h1.Sh::before, h2.Ss::before, .St::before, .Sx::before, .Sy::before,
.Va::before, .Vt::before, .Xr::before {
		opacity: 0;
		transition: .15s ease opacity;
		pointer-events: none;
		position: absolute;
		bottom: 100%;
		box-shadow: 0 0 .35em #000;
		padding: .15em .25em;
		white-space: nowrap;
		font-family: Helvetica,Arial,sans-serif;
		font-style: normal;
		font-weight: bold;
		color: black;
		background: #fff; }
.An:hover::before, .Ar:hover::before, .Cd:hover::before, .Cm:hover::before,
.Dv:hover::before, .Em:hover::before, .Er:hover::before, .Ev:hover::before,
.Fa:hover::before, .Fd:hover::before, .Fl:hover::before, .Fn:hover::before,
.Ft:hover::before, .Ic:hover::before, code.In:hover::before,
.Lb:hover::before, .Lk:hover::before, .Ms:hover::before, .Mt:hover::before,
.Nd:hover::before, code.Nm:hover::before, .Pa:hover::before,
.Rs:hover::before, h1.Sh:hover::before, h2.Ss:hover::before, .St:hover::before,
.Sx:hover::before, .Sy:hover::before, .Va:hover::before, .Vt:hover::before,
.Xr:hover::before {
		opacity: 1;
		pointer-events: inherit; }

/* Overrides to avoid excessive margins on small devices. */

@media (max-width: 37.5em) {
.manual-text {
		margin-left: 0.5em; }
h1.Sh, h2.Ss {	margin-left: 0em; }
.Bd-indent {	margin-left: 2em; }
.Bl-hang > dd {
		margin-left: 2em; }
.Bl-tag {	margin-left: 2em; }
.Bl-tag > dt {
		margin-left: -2em; }
.HP {		margin-left: 2em;
		text-indent: -2em; }
}
'

#
# Display remote target with prefix and trailing slash.
#
function print_upload_header
{
	typeset -r prefix=$1
	typeset display_target

	if [[ -z $tflag ]]; then
		display_target=${prefix}${remote_target}
	else
		display_target=${remote_target}
	fi

	if [[ ${display_target} != */ ]]; then
		display_target=${display_target}/
	fi

	print "      Upload to: ${display_target}\n" \
	    "     Uploading: \c"
}

#
# Upload the webrev via rsync. Return 0 on success, 1 on error.
#
function rsync_upload
{
	if (( $# != 2 )); then
		print "\nERROR: rsync_upload: wrong usage ($#)"
		exit 1
	fi

	typeset -r dst=$1
	integer -r print_err_msg=$2

	print_upload_header ${rsync_prefix}
	print "rsync ... \c"
	typeset -r err_msg=$( $MKTEMP /tmp/rsync_err.XXXXXX )
	if [[ -z $err_msg ]]; then
		print "\nERROR: rsync_upload: cannot create temporary file"
		return 1
	fi
	#
	# The source directory must end with a slash in order to copy just
	# directory contents, not the whole directory.
	#
	typeset src_dir=$WDIR
	if [[ ${src_dir} != */ ]]; then
		src_dir=${src_dir}/
	fi
	$RSYNC -r -q ${src_dir} $dst 2>$err_msg
	if (( $? != 0 )); then
		if (( ${print_err_msg} > 0 )); then
			print "Failed.\nERROR: rsync failed"
			print "src dir: '${src_dir}'\ndst dir: '$dst'"
			print "error messages:"
			$SED 's/^/> /' $err_msg
			rm -f $err_msg
		fi
		return 1
	fi

	rm -f $err_msg
	print "Done."
	return 0
}

#
# Create directories on remote host using SFTP. Return 0 on success,
# 1 on failure.
#
function remote_mkdirs
{
	typeset -r dir_spec=$1
	typeset -r host_spec=$2

	#
	# If the supplied path is absolute we assume all directories are
	# created, otherwise try to create all directories in the path
	# except the last one which will be created by scp.
	#
	if [[ "${dir_spec}" == */* && "${dir_spec}" != /* ]]; then
		print "mkdirs \c"
		#
		# Remove the last directory from directory specification.
		#
		typeset -r dirs_mk=${dir_spec%/*}
		typeset -r batch_file_mkdir=$( $MKTEMP \
		    /tmp/webrev_mkdir.XXXXXX )
		if [[ -z $batch_file_mkdir ]]; then
			print "\nERROR: remote_mkdirs:" \
			    "cannot create temporary file for batch file"
			return 1
		fi
		OLDIFS=$IFS
		IFS=/
		typeset dir
		for dir in ${dirs_mk}; do
			#
			# Use the '-' prefix to ignore mkdir errors in order
			# to avoid an error in case the directory already
			# exists. We check the directory with chdir to be sure
			# there is one.
			#
			print -- "-mkdir ${dir}" >> ${batch_file_mkdir}
			print "chdir ${dir}" >> ${batch_file_mkdir}
		done
		IFS=$OLDIFS
		typeset -r sftp_err_msg=$( $MKTEMP /tmp/webrev_scp_err.XXXXXX )
		if [[ -z ${sftp_err_msg} ]]; then
			print "\nERROR: remote_mkdirs:" \
			    "cannot create temporary file for error messages"
			return 1
		fi
		$SFTP -b ${batch_file_mkdir} ${host_spec} 2>${sftp_err_msg} 1>&2
		if (( $? != 0 )); then
			print "\nERROR: failed to create remote directories"
			print "error messages:"
			$SED 's/^/> /' ${sftp_err_msg}
			rm -f ${sftp_err_msg} ${batch_file_mkdir}
			return 1
		fi
		rm -f ${sftp_err_msg} ${batch_file_mkdir}
	fi

	return 0
}

#
# Upload the webrev via SSH. Return 0 on success, 1 on error.
#
function ssh_upload
{
	if (( $# != 1 )); then
		print "\nERROR: ssh_upload: wrong number of arguments"
		exit 1
	fi

	typeset dst=$1
	typeset -r host_spec=${dst%%:*}
	typeset -r dir_spec=${dst#*:}

	#
	# Display the upload information before calling delete_webrev
	# because it will also print its progress.
	#
	print_upload_header ${ssh_prefix}

	#
	# If the deletion was explicitly requested there is no need
	# to perform it again.
	#
	if [[ -z $Dflag ]]; then
		#
		# We do not care about return value because this might be
		# the first time this directory is uploaded.
		#
		delete_webrev 0
	fi

	#
	# Create remote directories. Any error reporting will be done
	# in remote_mkdirs function.
	#
	remote_mkdirs ${dir_spec} ${host_spec}
	if (( $? != 0 )); then
		return 1
	fi

	print "upload ... \c"
	typeset -r scp_err_msg=$( $MKTEMP /tmp/scp_err.XXXXXX )
	if [[ -z ${scp_err_msg} ]]; then
		print "\nERROR: ssh_upload:" \
		    "cannot create temporary file for error messages"
		return 1
	fi
	$SCP -q -C -B -o PreferredAuthentications=publickey -r \
		$WDIR $dst 2>${scp_err_msg}
	if (( $? != 0 )); then
		print "Failed.\nERROR: scp failed"
		print "src dir: '$WDIR'\ndst dir: '$dst'"
		print "error messages:"
		$SED 's/^/> /' ${scp_err_msg}
		rm -f ${scp_err_msg}
		return 1
	fi

	rm -f ${scp_err_msg}
	print "Done."
	return 0
}

#
# Delete webrev at remote site. Return 0 on success, 1 or exit code from sftp
# on failure. If first argument is 1 then perform the check of sftp return
# value otherwise ignore it. If second argument is present it means this run
# only performs deletion.
#
function delete_webrev
{
	if (( $# < 1 )); then
		print "delete_webrev: wrong number of arguments"
		exit 1
	fi

	integer -r check=$1
	integer delete_only=0
	if (( $# == 2 )); then
		delete_only=1
	fi

	#
	# Strip the transport specification part of remote target first.
	#
	typeset -r stripped_target=${remote_target##*://}
	typeset -r host_spec=${stripped_target%%:*}
	typeset -r dir_spec=${stripped_target#*:}
	typeset dir_rm

	#
	# Do not accept an absolute path.
	#
	if [[ ${dir_spec} == /* ]]; then
		return 1
	fi

	#
	# Strip the ending slash.
	#
	if [[ ${dir_spec} == */ ]]; then
		dir_rm=${dir_spec%%/}
	else
		dir_rm=${dir_spec}
	fi

	if (( ${delete_only} > 0 )); then
		print "       Removing: \c"
	else
		print "rmdir \c"
	fi
	if [[ -z "$dir_rm" ]]; then
		print "\nERROR: empty directory for removal"
		return 1
	fi

	#
	# Prepare batch file.
	#
	typeset -r batch_file_rm=$( $MKTEMP /tmp/webrev_remove.XXXXXX )
	if [[ -z $batch_file_rm ]]; then
		print "\nERROR: delete_webrev: cannot create temporary file"
		return 1
	fi
	print "rename $dir_rm $TRASH_DIR/removed.$$" > $batch_file_rm

	#
	# Perform remote deletion and remove the batch file.
	#
	typeset -r sftp_err_msg=$( $MKTEMP /tmp/webrev_scp_err.XXXXXX )
	if [[ -z ${sftp_err_msg} ]]; then
		print "\nERROR: delete_webrev:" \
		    "cannot create temporary file for error messages"
		return 1
	fi
	$SFTP -b $batch_file_rm $host_spec 2>${sftp_err_msg} 1>&2
	integer -r ret=$?
	rm -f $batch_file_rm
	if (( $ret != 0 && $check > 0 )); then
		print "Failed.\nERROR: failed to remove remote directories"
		print "error messages:"
		$SED 's/^/> /' ${sftp_err_msg}
		rm -f ${sftp_err_msg}
		return $ret
	fi
	rm -f ${sftp_err_msg}
	if (( ${delete_only} > 0 )); then
		print "Done."
	fi

	return 0
}

#
# Upload webrev to remote site
#
function upload_webrev
{
	integer ret

	if [[ ! -d "$WDIR" ]]; then
		print "\nERROR: webrev directory '$WDIR' does not exist"
		return 1
	fi

	#
	# Perform a late check to make sure we do not upload closed source
	# to remote target when -n is used. If the user used custom remote
	# target he probably knows what he is doing.
	#
	if [[ -n $nflag && -z $tflag ]]; then
		$FIND $WDIR -type d -name closed \
			| $GREP closed >/dev/null
		if (( $? == 0 )); then
			print "\nERROR: directory '$WDIR' contains" \
			    "\"closed\" directory"
			return 1
		fi
	fi


	#
	# We have the URI for remote destination now so let's start the upload.
	#
	if [[ -n $tflag ]]; then
		if [[ "${remote_target}" == ${rsync_prefix}?* ]]; then
			rsync_upload ${remote_target##$rsync_prefix} 1
			ret=$?
			return $ret
		elif [[ "${remote_target}" == ${ssh_prefix}?* ]]; then
			ssh_upload ${remote_target##$ssh_prefix}
			ret=$?
			return $ret
		fi
	else
		#
		# Try rsync first and fallback to SSH in case it fails.
		#
		rsync_upload ${remote_target} 0
		ret=$?
		if (( $ret != 0 )); then
			print "Failed. (falling back to SSH)"
			ssh_upload ${remote_target}
			ret=$?
		fi
		return $ret
	fi
}

#
# input_cmd | url_encode | output_cmd
#
# URL-encode (percent-encode) reserved characters as defined in RFC 3986.
#
# Reserved characters are: :/?#[]@!$&'()*+,;=
#
# While not a reserved character itself, percent '%' is reserved by definition
# so encode it first to avoid recursive transformation, and skip '/' which is
# a path delimiter.
#
# The quotation character is deliberately not escaped in order to make
# the substitution work with GNU sed.
#
function url_encode
{
	$SED -e "s|%|%25|g" -e "s|:|%3A|g" -e "s|\&|%26|g" \
	    -e "s|?|%3F|g" -e "s|#|%23|g" -e "s|\[|%5B|g" \
	    -e "s|*|%2A|g" -e "s|@|%40|g" -e "s|\!|%21|g" \
	    -e "s|=|%3D|g" -e "s|;|%3B|g" -e "s|\]|%5D|g" \
	    -e "s|(|%28|g" -e "s|)|%29|g" -e "s|'|%27|g" \
	    -e "s|+|%2B|g" -e "s|\,|%2C|g" -e "s|\\\$|%24|g"
}

#
# input_cmd | html_quote | output_cmd
# or
# html_quote filename | output_cmd
#
# Make a piece of source code safe for display in an HTML <pre> block.
#
html_quote()
{
	$SED -e "s/&/\&amp;/g" -e "s/</\&lt;/g" -e "s/>/\&gt;/g" "$@" | expand
}

#
# Trim a digest-style revision to a conventionally readable yet useful length
#
trim_digest()
{
	typeset digest=$1

	echo $digest | $SED -e 's/\([0-9a-f]\{12\}\).*/\1/'
}

#
# input_cmd | its2url | output_cmd
#
# Scan for information tracking system references and insert <a> links to the
# relevant databases.
#
its2url()
{
	$SED -f ${its_sed_script}
}

#
# strip_unchanged <infile> | output_cmd
#
# Removes chunks of sdiff documents that have not changed. This makes it
# easier for a code reviewer to find the bits that have changed.
#
# Deleted lines of text are replaced by a horizontal rule. Some
# identical lines are retained before and after the changed lines to
# provide some context.  The number of these lines is controlled by the
# variable C in the $AWK script below.
#
# The script detects changed lines as any line that has a "<span class="
# string embedded (unchanged lines have no particular class and are not
# part of a <span>).  Blank lines (without a sequence number) are also
# detected since they flag lines that have been inserted or deleted.
#
strip_unchanged()
{
	$AWK '
	BEGIN	{ C = c = 20 }
	NF == 0 || /<span class="/ {
		if (c > C) {
			c -= C
			inx = 0
			if (c > C) {
				print "\n</pre><hr></hr><pre>"
				inx = c % C
				c = C
			}

			for (i = 0; i < c; i++)
				print ln[(inx + i) % C]
		}
		c = 0;
		print
		next
	}
	{	if (c >= C) {
			ln[c % C] = $0
			c++;
			next;
		}
		c++;
		print
	}
	END	{ if (c > (C * 2)) print "\n</pre><hr></hr>" }

	' $1
}

#
# sdiff_to_html
#
# This function takes two files as arguments, obtains their diff, and
# processes the diff output to present the files as an HTML document with
# the files displayed side-by-side, differences shown in color.  It also
# takes a delta comment, rendered as an HTML snippet, as the third
# argument.  The function takes two files as arguments, then the name of
# file, the path, and the comment.  The HTML will be delivered on stdout,
# e.g.
#
#   $ sdiff_to_html old/usr/src/tools/scripts/webrev.sh \
#         new/usr/src/tools/scripts/webrev.sh \
#         webrev.sh usr/src/tools/scripts \
#         '<a href="http://monaco.sfbay.sun.com/detail.jsp?cr=1234567">
#          1234567</a> my bugid' > <file>.html
#
# framed_sdiff() is then called which creates $2.frames.html
# in the webrev tree.
#
# FYI: This function is rather unusual in its use of awk.  The initial
# diff run produces conventional diff output showing changed lines mixed
# with editing codes.  The changed lines are ignored - we're interested in
# the editing codes, e.g.
#
#      8c8
#      57a61
#      63c66,76
#      68,93d80
#      106d90
#      108,110d91
#
#  These editing codes are parsed by the awk script and used to generate
#  another awk script that generates HTML, e.g the above lines would turn
#  into something like this:
#
#      BEGIN { printf "<pre>\n" }
#      function sp(n) {for (i=0;i<n;i++)printf "\n"}
#      function wl(n) {printf "<font color=%s>%4d %s </font>\n", n, NR, $0}
#      NR==8           {wl("#7A7ADD");next}
#      NR==54          {wl("#7A7ADD");sp(3);next}
#      NR==56          {wl("#7A7ADD");next}
#      NR==57          {wl("black");printf "\n"; next}
#        :               :
#
#  This script is then run on the original source file to generate the
#  HTML that corresponds to the source file.
#
#  The two HTML files are then combined into a single piece of HTML that
#  uses an HTML table construct to present the files side by side.  You'll
#  notice that the changes are color-coded:
#
#   black     - unchanged lines
#   blue      - changed lines
#   bold blue - new lines
#   brown     - deleted lines
#
#  Blank lines are inserted in each file to keep unchanged lines in sync
#  (side-by-side).  This format is familiar to users of sdiff(1) or
#  Teamware's filemerge tool.
#
sdiff_to_html()
{
	diff -b $1 $2 > /tmp/$$.diffs

	TNAME=$3
	TPATH=$4
	COMMENT=$5

	#
	#  Now we have the diffs, generate the HTML for the old file.
	#
	$AWK '
	BEGIN	{
		printf "function sp(n) {for (i=0;i<n;i++)printf \"\\n\"}\n"
		printf "function removed() "
		printf "{printf \"<span class=\\\"removed\\\">%%4d %%s</span>\\n\", NR, $0}\n"
		printf "function changed() "
		printf "{printf \"<span class=\\\"changed\\\">%%4d %%s</span>\\n\", NR, $0}\n"
		printf "function bl() {printf \"%%4d %%s\\n\", NR, $0}\n"
}
	/^</	{next}
	/^>/	{next}
	/^---/	{next}

	{
	split($1, a, /[cad]/) ;
	if (index($1, "a")) {
		if (a[1] == 0) {
			n = split(a[2], r, /,/);
			if (n == 1)
				printf "BEGIN\t\t{sp(1)}\n"
			else
				printf "BEGIN\t\t{sp(%d)}\n",\
				(r[2] - r[1]) + 1
			next
		}

		printf "NR==%s\t\t{", a[1]
		n = split(a[2], r, /,/);
		s = r[1];
		if (n == 1)
			printf "bl();printf \"\\n\"; next}\n"
		else {
			n = r[2] - r[1]
			printf "bl();sp(%d);next}\n",\
			(r[2] - r[1]) + 1
		}
		next
	}
	if (index($1, "d")) {
		n = split(a[1], r, /,/);
		n1 = r[1]
		n2 = r[2]
		if (n == 1)
			printf "NR==%s\t\t{removed(); next}\n" , n1
		else
			printf "NR==%s,NR==%s\t{removed(); next}\n" , n1, n2
		next
	}
	if (index($1, "c")) {
		n = split(a[1], r, /,/);
		n1 = r[1]
		n2 = r[2]
		final = n2
		d1 = 0
		if (n == 1)
			printf "NR==%s\t\t{changed();" , n1
		else {
			d1 = n2 - n1
			printf "NR==%s,NR==%s\t{changed();" , n1, n2
		}
		m = split(a[2], r, /,/);
		n1 = r[1]
		n2 = r[2]
		if (m > 1) {
			d2  = n2 - n1
			if (d2 > d1) {
				if (n > 1) printf "if (NR==%d)", final
				printf "sp(%d);", d2 - d1
			}
		}
		printf "next}\n" ;

		next
	}
	}

	END	{ printf "{printf \"%%4d %%s\\n\", NR, $0 }\n" }
	' /tmp/$$.diffs > /tmp/$$.file1

	#
	#  Now generate the HTML for the new file
	#
	$AWK '
	BEGIN	{
		printf "function sp(n) {for (i=0;i<n;i++)printf \"\\n\"}\n"
		printf "function new() "
		printf "{printf \"<span class=\\\"new\\\">%%4d %%s</span>\\n\", NR, $0}\n"
		printf "function changed() "
		printf "{printf \"<span class=\\\"changed\\\">%%4d %%s</span>\\n\", NR, $0}\n"
		printf "function bl() {printf \"%%4d %%s\\n\", NR, $0}\n"
	}

	/^</	{next}
	/^>/	{next}
	/^---/	{next}

	{
	split($1, a, /[cad]/) ;
	if (index($1, "d")) {
		if (a[2] == 0) {
			n = split(a[1], r, /,/);
			if (n == 1)
				printf "BEGIN\t\t{sp(1)}\n"
			else
				printf "BEGIN\t\t{sp(%d)}\n",\
				(r[2] - r[1]) + 1
			next
		}

		printf "NR==%s\t\t{", a[2]
		n = split(a[1], r, /,/);
		s = r[1];
		if (n == 1)
			printf "bl();printf \"\\n\"; next}\n"
		else {
			n = r[2] - r[1]
			printf "bl();sp(%d);next}\n",\
			(r[2] - r[1]) + 1
		}
		next
	}
	if (index($1, "a")) {
		n = split(a[2], r, /,/);
		n1 = r[1]
		n2 = r[2]
		if (n == 1)
			printf "NR==%s\t\t{new() ; next}\n" , n1
		else
			printf "NR==%s,NR==%s\t{new() ; next}\n" , n1, n2
		next
	}
	if (index($1, "c")) {
		n = split(a[2], r, /,/);
		n1 = r[1]
		n2 = r[2]
		final = n2
		d2 = 0;
		if (n == 1) {
			final = n1
			printf "NR==%s\t\t{changed();" , n1
		} else {
			d2 = n2 - n1
			printf "NR==%s,NR==%s\t{changed();" , n1, n2
		}
		m = split(a[1], r, /,/);
		n1 = r[1]
		n2 = r[2]
		if (m > 1) {
			d1  = n2 - n1
			if (d1 > d2) {
				if (n > 1) printf "if (NR==%d)", final
				printf "sp(%d);", d1 - d2
			}
		}
		printf "next}\n" ;
		next
	}
	}
	END	{ printf "{printf \"%%4d %%s\\n\", NR, $0 }\n" }
	' /tmp/$$.diffs > /tmp/$$.file2

	#
	# Post-process the HTML files by running them back through $AWK
	#
	html_quote < $1 | $AWK -f /tmp/$$.file1 > /tmp/$$.file1.html

	html_quote < $2 | $AWK -f /tmp/$$.file2 > /tmp/$$.file2.html

	#
	# Now combine into a valid HTML file and side-by-side into a table
	#
	print "$HTML<head>$STDHEAD"
	print "<title>$WNAME Sdiff $TPATH/$TNAME</title>"
	print "</head><body id=\"SUNWwebrev\">"
	print "<a class=\"print\" href=\"javascript:print()\">Print this page</a>"
	print "<pre>$COMMENT</pre>\n"
	print "<table><tr valign=\"top\">"
	print "<td><pre>"

	strip_unchanged /tmp/$$.file1.html

	print "</pre></td><td><pre>"

	strip_unchanged /tmp/$$.file2.html

	print "</pre></td>"
	print "</tr></table>"
	print "</body></html>"

	framed_sdiff $TNAME $TPATH /tmp/$$.file1.html /tmp/$$.file2.html \
	    "$COMMENT"
}


#
# framed_sdiff <filename> <filepath> <lhsfile> <rhsfile> <comment>
#
# Expects lefthand and righthand side html files created by sdiff_to_html.
# We use insert_anchors() to augment those with HTML navigation anchors,
# and then emit the main frame.  Content is placed into:
#
#    $WDIR/DIR/$TNAME.lhs.html
#    $WDIR/DIR/$TNAME.rhs.html
#    $WDIR/DIR/$TNAME.frames.html
#
# NOTE: We rely on standard usage of $WDIR and $DIR.
#
function framed_sdiff
{
	typeset TNAME=$1
	typeset TPATH=$2
	typeset lhsfile=$3
	typeset rhsfile=$4
	typeset comments=$5
	typeset RTOP

	# Enable html files to access WDIR via a relative path.
	RTOP=$(relative_dir $TPATH $WDIR)

	# Make the rhs/lhs files and output the frameset file.
	print "$HTML<head>$STDHEAD" > $WDIR/$DIR/$TNAME.lhs.html

	cat >> $WDIR/$DIR/$TNAME.lhs.html <<-EOF
	    <script type="text/javascript" src="${RTOP}ancnav.js"></script>
	    </head>
	    <body id="SUNWwebrev" onkeypress="keypress(event);">
	    <a name="0"></a>
	    <pre>$comments</pre><hr></hr>
	EOF

	cp $WDIR/$DIR/$TNAME.lhs.html $WDIR/$DIR/$TNAME.rhs.html

	insert_anchors $lhsfile >> $WDIR/$DIR/$TNAME.lhs.html
	insert_anchors $rhsfile >> $WDIR/$DIR/$TNAME.rhs.html

	close='</body></html>'

	print $close >> $WDIR/$DIR/$TNAME.lhs.html
	print $close >> $WDIR/$DIR/$TNAME.rhs.html

	print "$FRAMEHTML<head>$STDHEAD" > $WDIR/$DIR/$TNAME.frames.html
	print "<title>$WNAME Framed-Sdiff " \
	    "$TPATH/$TNAME</title> </head>" >> $WDIR/$DIR/$TNAME.frames.html
	cat >> $WDIR/$DIR/$TNAME.frames.html <<-EOF
	  <frameset rows="*,60">
	    <frameset cols="50%,50%">
	      <frame src="$TNAME.lhs.html" scrolling="auto" name="lhs"></frame>
	      <frame src="$TNAME.rhs.html" scrolling="auto" name="rhs"></frame>
	    </frameset>
	  <frame src="${RTOP}ancnav.html" scrolling="no" marginwidth="0"
	   marginheight="0" name="nav"></frame>
	  <noframes>
	    <body id="SUNWwebrev">
	      Alas 'frames' webrev requires that your browser supports frames
	      and has the feature enabled.
	    </body>
	  </noframes>
	  </frameset>
	</html>
	EOF
}


#
# input_cmd | insert_anchors | output_cmd
#
# Flag blocks of difference with sequentially numbered invisible
# anchors.  These are used to drive the frames version of the
# sdiffs output.
#
# NOTE: Anchor zero flags the top of the file irrespective of changes,
# an additional anchor is also appended to flag the bottom.
#
# The script detects changed lines as any line that has a "<span
# class=" string embedded (unchanged lines have no class set and are
# not part of a <span>.  Blank lines (without a sequence number)
# are also detected since they flag lines that have been inserted or
# deleted.
#
function insert_anchors
{
	$AWK '
	function ia() {
		printf "<a name=\"%d\" id=\"anc%d\"></a>", anc, anc++;
	}

	BEGIN {
		anc=1;
		inblock=1;
		printf "<pre>\n";
	}
	NF == 0 || /^<span class=/ {
		if (inblock == 0) {
			ia();
			inblock=1;
		}
		print;
		next;
	}
	{
		inblock=0;
		print;
	}
	END {
		ia();

		printf "<b style=\"font-size: large; color: red\">";
		printf "--- EOF ---</b>"
		for(i=0;i<8;i++) printf "\n\n\n\n\n\n\n\n\n\n";
		printf "</pre>"
		printf "<form name=\"eof\">";
		printf "<input name=\"value\" value=\"%d\" " \
		    "type=\"hidden\"></input>", anc - 1;
		printf "</form>";
	}
	' $1
}


#
# relative_dir
#
# Print a relative return path from $1 to $2.  For example if
# $1=/tmp/myreview/raw_files/usr/src/tools/scripts and $2=/tmp/myreview,
# this function would print "../../../../".
#
# In the event that $1 is not in $2 a warning is printed to stderr,
# and $2 is returned-- the result of this is that the resulting webrev
# is not relocatable.
#
function relative_dir
{
	typeset cur="${1##$2?(/)}"

	#
	# If the first path was specified absolutely, and it does
	# not start with the second path, it's an error.
	#
	if [[ "$cur" = "/${1#/}" ]]; then
		# Should never happen.
		print -u2 "\nWARNING: relative_dir: \"$1\" not relative "
		print -u2 "to \"$2\".  Check input paths.  Framed webrev "
		print -u2 "will not be relocatable!"
		print $2
		return
	fi

	#
	# This is kind of ugly.  The sed script will do the following:
	#
	# 1. Strip off a leading "." or "./": this is important to get
	#    the correct arcnav links for files in $WDIR.
	# 2. Strip off a trailing "/": this is not strictly necessary,
	#    but is kind of nice, since it doesn't end up in "//" at
	#    the end of a relative path.
	# 3. Replace all remaining sequences of non-"/" with "..": the
	#    assumption here is that each dirname represents another
	#    level of relative separation.
	# 4. Append a trailing "/" only for non-empty paths: this way
	#    the caller doesn't need to duplicate this logic, and does
	#    not end up using $RTOP/file for files in $WDIR.
	#
	print $cur | $SED -e '{
		s:^\./*::
		s:/$::
		s:[^/][^/]*:..:g
		s:^\(..*\)$:\1/:
	}'
}

#
# frame_nav_js
#
# Emit javascript for frame navigation
#
function frame_nav_js
{
cat << \EOF
var myInt;
var scrolling = 0;
var sfactor = 3;
var scount = 10;

function scrollByPix()
{
	if (scount <= 0) {
		sfactor *= 1.2;
		scount = 10;
	}
	parent.lhs.scrollBy(0, sfactor);
	parent.rhs.scrollBy(0, sfactor);
	scount--;
}

function scrollToAnc(num)
{
	// Update the value of the anchor in the form which we use as
	// storage for this value.  setAncValue() will take care of
	// correcting for overflow and underflow of the value and return
	// us the new value.
	num = setAncValue(num);

	// Set location and scroll back a little to expose previous
	// lines.
	//
	// Note that this could be improved: it is possible although
	// complex to compute the x and y position of an anchor, and to
	// scroll to that location directly.
	//
	parent.lhs.location.replace(parent.lhs.location.pathname + "#" + num);
	parent.rhs.location.replace(parent.rhs.location.pathname + "#" + num);

	parent.lhs.scrollBy(0, -30);
	parent.rhs.scrollBy(0, -30);
}

function getAncValue()
{
	return (parseInt(parent.nav.document.diff.real.value));
}

function setAncValue(val)
{
	if (val <= 0) {
		val = 0;
		parent.nav.document.diff.real.value = val;
		parent.nav.document.diff.display.value = "BOF";
		return (val);
	}

	//
	// The way we compute the max anchor value is to stash it
	// inline in the left and right hand side pages-- it's the same
	// on each side, so we pluck from the left.
	//
	maxval = parent.lhs.document.eof.value.value;
	if (val < maxval) {
		parent.nav.document.diff.real.value = val;
		parent.nav.document.diff.display.value = val.toString();
		return (val);
	}

	// this must be: val >= maxval
	val = maxval;
	parent.nav.document.diff.real.value = val;
	parent.nav.document.diff.display.value = "EOF";
	return (val);
}

function stopScroll()
{
	if (scrolling == 1) {
		clearInterval(myInt);
		scrolling = 0;
	}
}

function startScroll()
{
	stopScroll();
	scrolling = 1;
	myInt = setInterval("scrollByPix()", 10);
}

function handlePress(b)
{
	switch (b) {
	case 1:
		scrollToAnc(-1);
		break;
	case 2:
		scrollToAnc(getAncValue() - 1);
		break;
	case 3:
		sfactor = -3;
		startScroll();
		break;
	case 4:
		sfactor = 3;
		startScroll();
		break;
	case 5:
		scrollToAnc(getAncValue() + 1);
		break;
	case 6:
		scrollToAnc(999999);
		break;
	}
}

function handleRelease(b)
{
	stopScroll();
}

function keypress(ev)
{
	var keynum;
	var keychar;

	if (window.event) { // IE
		keynum = ev.keyCode;
	} else if (ev.which) { // non-IE
		keynum = ev.which;
	}

	keychar = String.fromCharCode(keynum);

	if (keychar == "k") {
		handlePress(2);
		return (0);
	} else if (keychar == "j" || keychar == " ") {
		handlePress(5);
		return (0);
	}

	return (1);
}

function ValidateDiffNum()
{
	var val;
	var i;

	val = parent.nav.document.diff.display.value;
	if (val == "EOF") {
		scrollToAnc(999999);
		return;
	}

	if (val == "BOF") {
		scrollToAnc(0);
		return;
	}

	i = parseInt(val);
	if (isNaN(i)) {
		parent.nav.document.diff.display.value = getAncValue();
	} else {
		scrollToAnc(i);
	}

	return (false);
}
EOF
}

#
# frame_navigation
#
# Output anchor navigation file for framed sdiffs.
#
function frame_navigation
{
	print "$HTML<head>$STDHEAD"

	cat << \EOF
<title>Anchor Navigation</title>
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Type" content="text/html">

<style type="text/css">
    div.button td { padding-left: 5px; padding-right: 5px;
		    background-color: #eee; text-align: center;
		    border: 1px #444 outset; cursor: pointer; }
    div.button a { font-weight: bold; color: black }
    div.button td:hover { background: #ffcc99; }
</style>
EOF

	print "<script type=\"text/javascript\" src=\"ancnav.js\"></script>"

	cat << \EOF
</head>
<body id="SUNWwebrev" bgcolor="#eeeeee" onload="document.diff.real.focus();"
	onkeypress="keypress(event);">
    <noscript lang="javascript">
      <center>
	<p><big>Framed Navigation controls require Javascript</big><br></br>
	Either this browser is incompatable or javascript is not enabled</p>
      </center>
    </noscript>
    <table width="100%" border="0" align="center">
	<tr>
          <td valign="middle" width="25%">Diff navigation:
          Use 'j' and 'k' for next and previous diffs; or use buttons
          at right</td>
	  <td align="center" valign="top" width="50%">
	    <div class="button">
	      <table border="0" align="center">
                  <tr>
		    <td>
		      <a onMouseDown="handlePress(1);return true;"
			 onMouseUp="handleRelease(1);return true;"
			 onMouseOut="handleRelease(1);return true;"
			 onClick="return false;"
			 title="Go to Beginning Of file">BOF</a></td>
		    <td>
		      <a onMouseDown="handlePress(3);return true;"
			 onMouseUp="handleRelease(3);return true;"
			 onMouseOut="handleRelease(3);return true;"
			 title="Scroll Up: Press and Hold to accelerate"
			 onClick="return false;">Scroll Up</a></td>
		    <td>
		      <a onMouseDown="handlePress(2);return true;"
			 onMouseUp="handleRelease(2);return true;"
			 onMouseOut="handleRelease(2);return true;"
			 title="Go to previous Diff"
			 onClick="return false;">Prev Diff</a>
		    </td></tr>

		  <tr>
		    <td>
		      <a onMouseDown="handlePress(6);return true;"
			 onMouseUp="handleRelease(6);return true;"
			 onMouseOut="handleRelease(6);return true;"
			 onClick="return false;"
			 title="Go to End Of File">EOF</a></td>
		    <td>
		      <a onMouseDown="handlePress(4);return true;"
			 onMouseUp="handleRelease(4);return true;"
			 onMouseOut="handleRelease(4);return true;"
			 title="Scroll Down: Press and Hold to accelerate"
			 onClick="return false;">Scroll Down</a></td>
		    <td>
		      <a onMouseDown="handlePress(5);return true;"
			 onMouseUp="handleRelease(5);return true;"
			 onMouseOut="handleRelease(5);return true;"
			 title="Go to next Diff"
			 onClick="return false;">Next Diff</a></td>
		  </tr>
              </table>
	    </div>
	  </td>
	  <th valign="middle" width="25%">
	    <form action="" name="diff" onsubmit="return ValidateDiffNum();">
		<input name="display" value="BOF" size="8" type="text"></input>
		<input name="real" value="0" size="8" type="hidden"></input>
	    </form>
	  </th>
	</tr>
    </table>
  </body>
</html>
EOF
}



#
# diff_to_html <filename> <filepath> { U | C } <comment>
#
# Processes the output of diff to produce an HTML file representing either
# context or unified diffs.
#
diff_to_html()
{
	TNAME=$1
	TPATH=$2
	DIFFTYPE=$3
	COMMENT=$4

	print "$HTML<head>$STDHEAD"
	print "<title>$WNAME ${DIFFTYPE}diff $TPATH</title>"

	if [[ $DIFFTYPE == "U" ]]; then
		print "$UDIFFCSS"
	fi

	cat <<-EOF
	</head>
	<body id="SUNWwebrev">
        <a class="print" href="javascript:print()">Print this page</a>
	<pre>$COMMENT</pre>
        <pre>
	EOF

	html_quote | $AWK '
	/^--- new/	{ next }
	/^\+\+\+ new/	{ next }
	/^--- old/	{ next }
	/^\*\*\* old/	{ next }
	/^\*\*\*\*/	{ next }
	/^-------/	{ printf "<center><h1>%s</h1></center>\n", $0; next }
	/^\@\@.*\@\@$/	{ printf "</pre><hr></hr><pre>\n";
			  printf "<span class=\"newmarker\">%s</span>\n", $0;
			  next}

	/^\*\*\*/	{ printf "<hr></hr><span class=\"oldmarker\">%s</span>\n", $0;
			  next}
	/^---/		{ printf "<span class=\"newmarker\">%s</span>\n", $0;
			  next}
	/^\+/		{printf "<span class=\"new\">%s</span>\n", $0; next}
	/^!/		{printf "<span class=\"changed\">%s</span>\n", $0; next}
	/^-/		{printf "<span class=\"removed\">%s</span>\n", $0; next}
			{printf "%s\n", $0; next}
	'

	print "</pre></body></html>\n"
}


#
# source_to_html { new | old } <filename>
#
# Process a plain vanilla source file to transform it into an HTML file.
#
source_to_html()
{
	WHICH=$1
	TNAME=$2

	print "$HTML<head>$STDHEAD"
	print "<title>$WNAME $WHICH $TNAME</title>"
	print "<body id=\"SUNWwebrev\">"
	print "<pre>"
	html_quote | $AWK '{line += 1 ; printf "%4d %s\n", line, $0 }'
	print "</pre></body></html>"
}

#
# comments_from_wx {text|html} filepath
#
# Given the pathname of a file, find its location in a "wx" active
# file list and print the following comment.  Output is either text or
# HTML; if the latter, embedded bugids (sequence of 5 or more digits)
# are turned into URLs.
#
comments_from_wx()
{
	typeset fmt=$1
	typeset p=$2

	comm=`$AWK '
	$1 == "'$p'" {
		do getline ; while (NF > 0)
		getline
		while (NF > 0) { print ; getline }
		exit
	}' < $wxfile`

	if [[ -z $comm ]]; then
		comm="*** NO COMMENTS ***"
	fi

	if [[ $fmt == "text" ]]; then
		print -- "$comm"
		return
	fi

	print -- "$comm" | html_quote | its2url

}

#
# getcomments {text|html} filepath parentpath
#
# Fetch the comments depending on what SCM mode we're in.
#
getcomments()
{
	typeset fmt=$1
	typeset p=$2
	typeset pp=$3

	if [[ -n $Nflag ]]; then
		return
	fi

	if [[ -n $wxfile ]]; then
		comments_from_wx $fmt $p
	fi
}

#
# printCI <total-changed> <inserted> <deleted> <modified> <unchanged>
#
# Print out Code Inspection figures similar to sccs-prt(1) format.
#
function printCI
{
	integer tot=$1 ins=$2 del=$3 mod=$4 unc=$5
	typeset str
	if (( tot == 1 )); then
		str="line"
	else
		str="lines"
	fi
	printf '%d %s changed: %d ins; %d del; %d mod; %d unchg\n' \
	    $tot $str $ins $del $mod $unc
}


#
# difflines <oldfile> <newfile>
#
# Calculate and emit number of added, removed, modified and unchanged lines,
# and total lines changed, the sum of added + removed + modified.
#
function difflines
{
	integer tot mod del ins unc err
	typeset filename

	eval $( diff -e $1 $2 | $AWK '
	# Change range of lines: N,Nc
	/^[0-9]*,[0-9]*c$/ {
		n=split(substr($1,1,length($1)-1), counts, ",");
		if (n != 2) {
			error=2
			exit;
		}
		#
		# 3,5c means lines 3 , 4 and 5 are changed, a total of 3 lines.
		# following would be 5 - 3 = 2! Hence +1 for correction.
		#
		r=(counts[2]-counts[1])+1;

		#
		# Now count replacement lines: each represents a change instead
		# of a delete, so increment c and decrement r.
		#
		while (getline != /^\.$/) {
			c++;
			r--;
		}
		#
		# If there were more replacement lines than original lines,
		# then r will be negative; in this case there are no deletions,
		# but there are r changes that should be counted as adds, and
		# since r is negative, subtract it from a and add it to c.
		#
		if (r < 0) {
			a-=r;
			c+=r;
		}

		#
		# If there were more original lines than replacement lines, then
		# r will be positive; in this case, increment d by that much.
		#
		if (r > 0) {
			d+=r;
		}
		next;
	}

	# Change lines: Nc
	/^[0-9].*c$/ {
		# The first line is a replacement; any more are additions.
		if (getline != /^\.$/) {
			c++;
			while (getline != /^\.$/) a++;
		}
		next;
	}

	# Add lines: both Na and N,Na
	/^[0-9].*a$/ {
		while (getline != /^\.$/) a++;
		next;
	}

	# Delete range of lines: N,Nd
	/^[0-9]*,[0-9]*d$/ {
		n=split(substr($1,1,length($1)-1), counts, ",");
		if (n != 2) {
			error=2
			exit;
		}
		#
		# 3,5d means lines 3 , 4 and 5 are deleted, a total of 3 lines.
		# following would be 5 - 3 = 2! Hence +1 for correction.
		#
		r=(counts[2]-counts[1])+1;
		d+=r;
		next;
	}

	# Delete line: Nd.   For example 10d says line 10 is deleted.
	/^[0-9]*d$/ {d++; next}

	# Should not get here!
	{
		error=1;
		exit;
	}

	# Finish off - print results
	END {
		printf("tot=%d;mod=%d;del=%d;ins=%d;err=%d\n",
		    (c+d+a), c, d, a, error);
	}' )

	# End of $AWK, Check to see if any trouble occurred.
	if (( $? > 0 || err > 0 )); then
		print "Unexpected Error occurred reading" \
		    "\`diff -e $1 $2\`: \$?=$?, err=" $err
		return
	fi

	# Accumulate totals
	(( TOTL += tot ))
	(( TMOD += mod ))
	(( TDEL += del ))
	(( TINS += ins ))
	# Calculate unchanged lines
	unc=`wc -l < $1`
	if (( unc > 0 )); then
		(( unc -= del + mod ))
		(( TUNC += unc ))
	fi
	# print summary
	print "<span class=\"lineschanged\">"
	printCI $tot $ins $del $mod $unc
	print "</span>"
}


#
# flist_from_wx
#
# Sets up webrev to source its information from a wx-formatted file.
# Sets the global 'wxfile' variable.
#
function flist_from_wx
{
	typeset argfile=$1
	if [[ -n ${argfile%%/*} ]]; then
		#
		# If the wx file pathname is relative then make it absolute
		# because the webrev does a "cd" later on.
		#
		wxfile=$PWD/$argfile
	else
		wxfile=$argfile
	fi

	$AWK '{ c = 1; print;
	  while (getline) {
		if (NF == 0) { c = -c; continue }
		if (c > 0) print
	  }
	}' $wxfile > $FLIST

	print " Done."
}

#
# Transform a specified 'git log' output format into a wx-like active list.
#
function git_wxfile
{
	typeset child="$1"
	typeset parent="$2"

	TMPFLIST=/tmp/$$.active
	$PERL -e 'my (%files, %realfiles, $msg);
	my $parent = $ARGV[0];
	my $child = $ARGV[1];

	open(F, "git diff -M --name-status $parent..$child |");
	while (<F>) {
	    chomp;
	    if (/^R(\d+)\s+([^ ]+)\s+([^ ]+)/) { # rename
		if ($1 >= 75) {		 # Probably worth treating as a rename
		    $realfiles{$3} = $2;
		} else {
		    $realfiles{$3} = $3;
		    $realfiles{$2} = $2;
		}
	    } else {
		my $f = (split /\s+/, $_)[1];
		$realfiles{$f} = $f;
	    }
	}
	close(F);

	my $state = 1;		    # 0|comments, 1|files
	open(F, "git whatchanged --pretty=format:%B $parent..$child |");
	while (<F>) {
	    chomp;
	    if (/^:[0-9]{6}/) {
		my ($unused, $fname, $fname2) = split(/\t/, $_);
		$fname = $fname2 if defined($fname2);
		next if !defined($realfiles{$fname}); # No real change
		$state = 1;
		chomp $msg;
		$files{$fname} .= $msg;
	    } else {
		if ($state == 1) {
		    $state = 0;
		    $msg = /^\n/ ? "" : "\n";
		}
		$msg .= "$_\n" if ($_);
	    }
	}
	close(F);

	for (sort keys %files) {
	    if ($realfiles{$_} ne $_) {
		print "$_ $realfiles{$_}\n$files{$_}\n\n";
	    } else {
		print "$_\n$files{$_}\n\n"
	    }
	}' ${parent} ${child} > $TMPFLIST

	wxfile=$TMPFLIST
}

#
# flist_from_git
# Build a wx-style active list, and hand it off to flist_from_wx
#
function flist_from_git
{
	typeset child=$1
	typeset parent=$2

	print " File list from: git ...\c"
	git_wxfile "$child" "$parent";

	# flist_from_wx prints the Done, so we don't have to.
	flist_from_wx $TMPFLIST
}

#
# flist_from_subversion
#
# Generate the file list by extracting file names from svn status.
#
function flist_from_subversion
{
	CWS=$1
	OLDPWD=$2

	cd $CWS
	print -u2 " File list from: svn status ... \c"
	svn status | $AWK '/^[ACDMR]/ { print $NF }' > $FLIST
	print -u2 " Done."
	cd $OLDPWD
}

function env_from_flist
{
	[[ -r $FLIST ]] || return

	#
	# Use "eval" to set env variables that are listed in the file
	# list.  Then copy those into our local versions of those
	# variables if they have not been set already.
	#
	eval `$SED -e "s/#.*$//" $FLIST | $GREP = `

	if [[ -z $codemgr_ws && -n $CODEMGR_WS ]]; then
		codemgr_ws=$CODEMGR_WS
		export CODEMGR_WS
	fi

	#
	# Check to see if CODEMGR_PARENT is set in the flist file.
	#
	if [[ -z $codemgr_parent && -n $CODEMGR_PARENT ]]; then
		codemgr_parent=$CODEMGR_PARENT
		export CODEMGR_PARENT
	fi
}

function look_for_prog
{
	typeset path
	typeset ppath
	typeset progname=$1

	ppath=$PATH
	ppath=$ppath:/usr/sfw/bin:/usr/bin:/usr/sbin
	ppath=$ppath:/opt/onbld/bin
	ppath=$ppath:/opt/onbld/bin/`uname -p`

	PATH=$ppath prog=`whence $progname`
	if [[ -n $prog ]]; then
		print $prog
	fi
}

function get_file_mode
{
	$PERL -e '
		if (@stat = stat($ARGV[0])) {
			$mode = $stat[2] & 0777;
			printf "%03o\n", $mode;
			exit 0;
		} else {
			exit 1;
		}
	    ' $1
}

function build_old_new_git
{
	typeset olddir="$1"
	typeset newdir="$2"
	typeset o_mode=
	typeset n_mode=
	typeset o_object=
	typeset n_object=
	typeset OWD=$PWD
	typeset file
	typeset type

	cd $CWS

	#
	# Get old file and its mode from the git object tree
	#
	if [[ "$PDIR" == "." ]]; then
		file="$PF"
	else
		file="$PDIR/$PF"
	fi

	if [[ -n $parent_webrev && -e $PWS/$PDIR/$PF ]]; then
		cp $PWS/$PDIR/$PF $olddir/$PDIR/$PF
	else
		$GIT ls-tree $GIT_PARENT $file | read o_mode type o_object junk
		$GIT cat-file $type $o_object > $olddir/$file 2>/dev/null

		if (( $? != 0 )); then
			rm -f $olddir/$file
		elif [[ -n $o_mode ]]; then
			# Strip the first 3 digits, to get a regular octal mode
			o_mode=${o_mode/???/}
			chmod $o_mode $olddir/$file
		else
			# should never happen
			print -u2 "ERROR: set mode of $olddir/$file"
		fi
	fi

	#
	# new version of the file.
	#
	if [[ "$DIR" == "." ]]; then
		file="$F"
	else
		file="$DIR/$F"
	fi
	rm -rf $newdir/$file

        if [[ -e $CWS/$DIR/$F ]]; then
		cp $CWS/$DIR/$F $newdir/$DIR/$F
		chmod $(get_file_mode $CWS/$DIR/$F) $newdir/$DIR/$F
        fi
	cd $OWD
}

function build_old_new_subversion
{
	typeset olddir="$1"
	typeset newdir="$2"

	# Snag new version of file.
	rm -f $newdir/$DIR/$F
	[[ -e $CWS/$DIR/$F ]] && cp $CWS/$DIR/$F $newdir/$DIR/$F

	if [[ -n $PWS && -e $PWS/$PDIR/$PF ]]; then
		cp $PWS/$PDIR/$PF $olddir/$PDIR/$PF
	else
		# Get the parent's version of the file.
		svn status $CWS/$DIR/$F | read stat file
		if [[ $stat != "A" ]]; then
			svn cat -r BASE $CWS/$DIR/$F > $olddir/$PDIR/$PF
		fi
	fi
}

function build_old_new_unknown
{
	typeset olddir="$1"
	typeset newdir="$2"

	#
	# Snag new version of file.
	#
	rm -f $newdir/$DIR/$F
	[[ -e $CWS/$DIR/$F ]] && cp $CWS/$DIR/$F $newdir/$DIR/$F

	#
	# Snag the parent's version of the file.
	#
	if [[ -f $PWS/$PDIR/$PF ]]; then
		rm -f $olddir/$PDIR/$PF
		cp $PWS/$PDIR/$PF $olddir/$PDIR/$PF
	fi
}

function build_old_new
{
	typeset WDIR=$1
	typeset PWS=$2
	typeset PDIR=$3
	typeset PF=$4
	typeset CWS=$5
	typeset DIR=$6
	typeset F=$7

	typeset olddir="$WDIR/raw_files/old"
	typeset newdir="$WDIR/raw_files/new"

	mkdir -p $olddir/$PDIR
	mkdir -p $newdir/$DIR

	if [[ $SCM_MODE == "git" ]]; then
		build_old_new_git "$olddir" "$newdir"
	elif [[ $SCM_MODE == "subversion" ]]; then
		build_old_new_subversion "$olddir" "$newdir"
	elif [[ $SCM_MODE == "unknown" ]]; then
		build_old_new_unknown "$olddir" "$newdir"
	fi

	if [[ ! -f $olddir/$PDIR/$PF && ! -f $newdir/$DIR/$F ]]; then
		print "*** Error: file not in parent or child"
		return 1
	fi
	return 0
}


#
# Usage message.
#
function usage
{
	print 'Usage:\twebrev [common-options]
	webrev [common-options] ( <file> | - )
	webrev [common-options] -w <wx file>

Options:
	-c <revision>: generate webrev for single revision (git only)
	-C <filename>: Use <filename> for the information tracking configuration.
	-D: delete remote webrev
	-h <revision>: specify "head" revision for comparison (git only)
	-i <filename>: Include <filename> in the index.html file.
	-I <filename>: Use <filename> for the information tracking registry.
	-n: do not generate the webrev (useful with -U)
	-O: Print bugids/arc cases suitable for OpenSolaris.
	-o <outdir>: Output webrev to specified directory.
	-p <compare-against>: Use specified parent wkspc or basis for comparison
	-t <remote_target>: Specify remote destination for webrev upload
	-U: upload the webrev to remote destination
	-w <wxfile>: Use specified wx active file.

Environment:
	WDIR: Control the output directory.
	WEBREV_TRASH_DIR: Set directory for webrev delete.

SCM Environment:
	CODEMGR_WS: Workspace location.
	CODEMGR_PARENT: Parent workspace location.
'

	exit 2
}

#
#
# Main program starts here
#
#

trap "rm -f /tmp/$$.* ; exit" 0 1 2 3 15

set +o noclobber

PATH=$(/bin/dirname "$(whence $0)"):$PATH

[[ -z $WDIFF ]] && WDIFF=`look_for_prog wdiff`
[[ -z $WX ]] && WX=`look_for_prog wx`
[[ -z $GIT ]] && GIT=`look_for_prog git`
[[ -z $WHICH_SCM ]] && WHICH_SCM=`look_for_prog which_scm`
[[ -z $PERL ]] && PERL=`look_for_prog perl`
[[ -z $RSYNC ]] && RSYNC=`look_for_prog rsync`
[[ -z $SCCS ]] && SCCS=`look_for_prog sccs`
[[ -z $AWK ]] && AWK=`look_for_prog nawk`
[[ -z $AWK ]] && AWK=`look_for_prog gawk`
[[ -z $AWK ]] && AWK=`look_for_prog awk`
[[ -z $SCP ]] && SCP=`look_for_prog scp`
[[ -z $SED ]] && SED=`look_for_prog sed`
[[ -z $SFTP ]] && SFTP=`look_for_prog sftp`
[[ -z $SORT ]] && SORT=`look_for_prog sort`
[[ -z $MKTEMP ]] && MKTEMP=`look_for_prog mktemp`
[[ -z $GREP ]] && GREP=`look_for_prog grep`
[[ -z $FIND ]] && FIND=`look_for_prog find`
[[ -z $MANDOC ]] && MANDOC=`look_for_prog mandoc`
[[ -z $COL ]] && COL=`look_for_prog col`

# set name of trash directory for remote webrev deletion
TRASH_DIR=".trash"
[[ -n $WEBREV_TRASH_DIR ]] && TRASH_DIR=$WEBREV_TRASH_DIR

if [[ ! -x $PERL ]]; then
	print -u2 "Error: No perl interpreter found.  Exiting."
	exit 1
fi

if [[ ! -x $WHICH_SCM ]]; then
	print -u2 "Error: Could not find which_scm.  Exiting."
	exit 1
fi

[[ ! -x $WDIFF ]] && print -u2 "WARNING: wdiff not found."

# Declare global total counters.
integer TOTL TINS TDEL TMOD TUNC

# default remote host for upload/delete
typeset -r DEFAULT_REMOTE_HOST="cr.opensolaris.org"
# prefixes for upload targets
typeset -r rsync_prefix="rsync://"
typeset -r ssh_prefix="ssh://"

cflag=
Cflag=
Dflag=
flist_mode=
flist_file=
hflag=
iflag=
Iflag=
lflag=
Nflag=
nflag=
Oflag=
oflag=
pflag=
tflag=
uflag=
Uflag=
wflag=
remote_target=

while getopts "c:C:Dh:i:I:lnNo:Op:t:Uw" opt
do
	case $opt in
	c)	cflag=1
		codemgr_head=$OPTARG
		codemgr_parent=$OPTARG~1;;

	C)	Cflag=1
		ITSCONF=$OPTARG;;

	D)	Dflag=1;;

	h)	hflag=1
		codemgr_head=$OPTARG;;

	i)	iflag=1
		INCLUDE_FILE=$OPTARG;;

	I)	Iflag=1
		ITSREG=$OPTARG;;

	N)	Nflag=1;;

	n)	nflag=1;;

	O)	Oflag=1;;

	o)	oflag=1
		# Strip the trailing slash to correctly form remote target.
		WDIR=${OPTARG%/};;

	p)	pflag=1
		codemgr_parent=$OPTARG;;

	t)	tflag=1
		remote_target=$OPTARG;;

	U)	Uflag=1;;

	w)	wflag=1;;

	?)	usage;;
	esac
done

FLIST=/tmp/$$.flist

if [[ -n $wflag && -n $lflag ]]; then
	usage
fi

# more sanity checking
if [[ -n $nflag && -z $Uflag ]]; then
	print "it does not make sense to skip webrev generation" \
	    "without -U"
	exit 1
fi

if [[ -n $tflag && -z $Uflag && -z $Dflag ]]; then
	echo "remote target has to be used only for upload or delete"
	exit 1
fi

#
# For the invocation "webrev -n -U" with no other options, webrev will assume
# that the webrev exists in ${CWS}/webrev, but will upload it using the name
# $(basename ${CWS}).  So we need to get CWS set before we skip any remaining
# logic.
#
$WHICH_SCM | read SCM_MODE junk || exit 1

if [[ $SCM_MODE == "git" ]]; then
	#
	# Git priorities:
	# 1. git rev-parse --git-dir from CODEMGR_WS environment variable
	# 2. git rev-parse --git-dir from directory of invocation
	#
	[[ -z $codemgr_ws && -n $CODEMGR_WS ]] && \
	    codemgr_ws=$($GIT --git-dir=$CODEMGR_WS/.git rev-parse --git-dir \
		2>/dev/null)
	[[ -z $codemgr_ws ]] && \
	    codemgr_ws=$($GIT rev-parse --git-dir 2>/dev/null)

	if [[ "$codemgr_ws" == ".git" ]]; then
		codemgr_ws="${PWD}/${codemgr_ws}"
	fi

	if [[ "$codemgr_ws" = *"/.git" ]]; then
		codemgr_ws=$(dirname $codemgr_ws) # Lose the '/.git'
	fi
	CWS="$codemgr_ws"
elif [[ $SCM_MODE == "subversion" ]]; then
	#
	# Subversion priorities:
	# 1. CODEMGR_WS from environment
	# 2. Relative path from current directory to SVN repository root
	#
	if [[ -n $CODEMGR_WS && -d $CODEMGR_WS/.svn ]]; then
		CWS=$CODEMGR_WS
	else
		svn info | while read line; do
			if [[ $line == "URL: "* ]]; then
				url=${line#URL: }
			elif [[ $line == "Repository Root: "* ]]; then
				repo=${line#Repository Root: }
			fi
		done

		rel=${url#$repo}
		CWS=${PWD%$rel}
	fi
fi

#
# If no SCM has been determined, take either the environment setting
# setting for CODEMGR_WS, or the current directory if that wasn't set.
#
if [[ -z ${CWS} ]]; then
	CWS=${CODEMGR_WS:-.}
fi

#
# If the command line options indicate no webrev generation, either
# explicitly (-n) or implicitly (-D but not -U), then there's a whole
# ton of logic we can skip.
#
# Instead of increasing indentation, we intentionally leave this loop
# body open here, and exit via break from multiple points within.
# Search for DO_EVERYTHING below to find the break points and closure.
#
for do_everything in 1; do

# DO_EVERYTHING: break point
if [[ -n $nflag || ( -z $Uflag && -n $Dflag ) ]]; then
	break
fi

#
# If this manually set as the parent, and it appears to be an earlier webrev,
# then note that fact and set the parent to the raw_files/new subdirectory.
#
if [[ -n $pflag && -d $codemgr_parent/raw_files/new ]]; then
	parent_webrev=$(readlink -f "$codemgr_parent")
	codemgr_parent=$(readlink -f "$codemgr_parent/raw_files/new")
fi

if [[ -z $wflag && -z $lflag ]]; then
	shift $(($OPTIND - 1))

	if [[ $1 == "-" ]]; then
		cat > $FLIST
		flist_mode="stdin"
		flist_done=1
		shift
	elif [[ -n $1 ]]; then
		if [[ ! -r $1 ]]; then
			print -u2 "$1: no such file or not readable"
			usage
		fi
		cat $1 > $FLIST
		flist_mode="file"
		flist_file=$1
		flist_done=1
		shift
	else
		flist_mode="auto"
	fi
fi

#
# Before we go on to further consider -l and -w, work out which SCM we think
# is in use.
#
case "$SCM_MODE" in
git|subversion)
	;;
unknown)
	if [[ $flist_mode == "auto" ]]; then
		print -u2 "Unable to determine SCM in use and file list not specified"
		print -u2 "See which_scm(1) for SCM detection information."
		exit 1
	fi
	;;
*)
	if [[ $flist_mode == "auto" ]]; then
		print -u2 "Unsupported SCM in use ($SCM_MODE) and file list not specified"
		exit 1
	fi
	;;
esac

print -u2 "   SCM detected: $SCM_MODE"

if [[ -n $wflag ]]; then
	#
	# If the -w is given then assume the file list is in Bonwick's "wx"
	# command format, i.e.  pathname lines alternating with SCCS comment
	# lines with blank lines as separators.  Use the SCCS comments later
	# in building the index.html file.
	#
	shift $(($OPTIND - 1))
	wxfile=$1
	if [[ -z $wxfile && -n $CODEMGR_WS ]]; then
		if [[ -r $CODEMGR_WS/wx/active ]]; then
			wxfile=$CODEMGR_WS/wx/active
		fi
	fi

	[[ -z $wxfile ]] && print -u2 "wx file not specified, and could not " \
	    "be auto-detected (check \$CODEMGR_WS)" && exit 1

	if [[ ! -r $wxfile ]]; then
		print -u2 "$wxfile: no such file or not readable"
		usage
	fi

	print -u2 " File list from: wx 'active' file '$wxfile' ... \c"
	flist_from_wx $wxfile
	flist_done=1
	if [[ -n "$*" ]]; then
		shift
	fi
elif [[ $flist_mode == "stdin" ]]; then
	print -u2 " File list from: standard input"
elif [[ $flist_mode == "file" ]]; then
	print -u2 " File list from: $flist_file"
fi

if [[ $# -gt 0 ]]; then
	print -u2 "WARNING: unused arguments: $*"
fi


if [[ $SCM_MODE == "git" ]]; then
	# Check that "head" revision specified with -c or -h is sane
	if [[ -n $cflag || -n $hflag ]]; then
		head_rev=$($GIT rev-parse --verify --quiet "$codemgr_head")
		if [[ -z $head_rev ]]; then
			print -u2 "Error: bad revision ${codemgr_head}"
			exit 1
		fi
	fi

	if [[ -z $codemgr_head ]]; then
		codemgr_head="HEAD";
	fi

	# Parent can either be specified with -p, or specified with
	# CODEMGR_PARENT in the environment.
	if [[ -z $codemgr_parent && -n $CODEMGR_PARENT ]]; then
		codemgr_parent=$CODEMGR_PARENT
	fi

	# Try to figure out the parent based on the branch the current
	# branch is tracking, if we fail, use origin/master
	this_branch=$($GIT branch | nawk '$1 == "*" { print $2 }')
	par_branch="origin/master"

	# If we're not on a branch there's nothing we can do
	if [[ $this_branch != "(no branch)" ]]; then
		$GIT for-each-ref					\
		    --format='%(refname:short) %(upstream:short)'	\
		    refs/heads/ |					\
		    while read local remote; do
			if [[ "$local" == "$this_branch" ]]; then
				par_branch="$remote"
			fi
		done
	fi

	if [[ -z $codemgr_parent ]]; then
		codemgr_parent=$par_branch
	fi
	PWS=$codemgr_parent

	#
	# If the parent is a webrev, we want to do some things against
	# the natural workspace parent (file list, comments, etc)
	#
	if [[ -n $parent_webrev ]]; then
		real_parent=$par_branch
	else
		real_parent=$PWS
	fi

	if [[ -z $flist_done ]]; then
		flist_from_git "$codemgr_head" "$real_parent"
		flist_done=1
	fi

	#
	# If we have a file list now, pull out any variables set
	# therein.
	#
	if [[ -n $flist_done ]]; then
		env_from_flist
	fi

	#
	# If we don't have a wx-format file list, build one we can pull change
	# comments from.
	#
	if [[ -z $wxfile ]]; then
		print "  Comments from: git...\c"
		git_wxfile "$codemgr_head" "$real_parent"
		print " Done."
	fi

	if [[ -z $GIT_PARENT ]]; then
		GIT_PARENT=$($GIT merge-base "$real_parent" "$codemgr_head")
	fi
	if [[ -z $GIT_PARENT ]]; then
		print -u2 "Error: Cannot discover parent revision"
		exit 1
	fi

	pnode=$(trim_digest $GIT_PARENT)

	if [[ -n $cflag ]]; then
		PRETTY_PWS="previous revision (at ${pnode})"
	elif [[ $real_parent == */* ]]; then
		origin=$(echo $real_parent | cut -d/ -f1)
		origin=$($GIT remote -v | \
		    $AWK '$1 == "'$origin'" { print $2; exit }')
		PRETTY_PWS="${PWS} (${origin} at ${pnode})"
	elif [[ -n $pflag && -z $parent_webrev ]]; then
		PRETTY_PWS="${CWS} (explicit revision ${pnode})"
	else
		PRETTY_PWS="${PWS} (at ${pnode})"
	fi

	cnode=$($GIT --git-dir=${codemgr_ws}/.git rev-parse --short=12 \
	    ${codemgr_head} 2>/dev/null)

	if [[ -n $cflag || -n $hflag ]]; then
		PRETTY_CWS="${CWS} (explicit head at ${cnode})"
	else
		PRETTY_CWS="${CWS} (at ${cnode})"
	fi
elif [[ $SCM_MODE == "subversion" ]]; then

	#
	# We only will have a real parent workspace in the case one
	# was specified (be it an older webrev, or another checkout).
	#
	[[ -n $codemgr_parent ]] && PWS=$codemgr_parent

	if [[ -z $flist_done && $flist_mode == "auto" ]]; then
		flist_from_subversion $CWS $OLDPWD
	fi
else
	if [[ $SCM_MODE == "unknown" ]]; then
		print -u2 "    Unknown type of SCM in use"
	else
		print -u2 "    Unsupported SCM in use: $SCM_MODE"
	fi

	env_from_flist

	if [[ -z $CODEMGR_WS ]]; then
		print -u2 "SCM not detected/supported and " \
		    "CODEMGR_WS not specified"
		exit 1
		fi

	if [[ -z $CODEMGR_PARENT ]]; then
		print -u2 "SCM not detected/supported and " \
		    "CODEMGR_PARENT not specified"
		exit 1
	fi

	CWS=$CODEMGR_WS
	PWS=$CODEMGR_PARENT
fi

#
# If the user didn't specify a -i option, check to see if there is a
# webrev-info file in the workspace directory.
#
if [[ -z $iflag && -r "$CWS/webrev-info" ]]; then
	iflag=1
	INCLUDE_FILE="$CWS/webrev-info"
fi

if [[ -n $iflag ]]; then
	if [[ ! -r $INCLUDE_FILE ]]; then
		print -u2 "include file '$INCLUDE_FILE' does not exist or is" \
		    "not readable."
		exit 1
	else
		#
		# $INCLUDE_FILE may be a relative path, and the script alters
		# PWD, so we just stash a copy in /tmp.
		#
		cp $INCLUDE_FILE /tmp/$$.include
	fi
fi

# DO_EVERYTHING: break point
if [[ -n $Nflag ]]; then
	break
fi

typeset -A itsinfo
typeset -r its_sed_script=/tmp/$$.its_sed
valid_prefixes=
if [[ -z $nflag ]]; then
	DEFREGFILE="$(/bin/dirname "$(whence $0)")/../etc/its.reg"
	if [[ -n $Iflag ]]; then
		REGFILE=$ITSREG
	elif [[ -r $HOME/.its.reg ]]; then
		REGFILE=$HOME/.its.reg
	else
		REGFILE=$DEFREGFILE
	fi
	if [[ ! -r $REGFILE ]]; then
		print "ERROR: Unable to read database registry file $REGFILE"
		exit 1
	elif [[ $REGFILE != $DEFREGFILE ]]; then
		print "   its.reg from: $REGFILE"
	fi

	$SED -e '/^#/d' -e '/^[ 	]*$/d' $REGFILE | while read LINE; do

		name=${LINE%%=*}
		value="${LINE#*=}"

		if [[ $name == PREFIX ]]; then
			p=${value}
			valid_prefixes="${p} ${valid_prefixes}"
		else
			itsinfo["${p}_${name}"]="${value}"
		fi
	done


	DEFCONFFILE="$(/bin/dirname "$(whence $0)")/../etc/its.conf"
	CONFFILES=$DEFCONFFILE
	if [[ -r $HOME/.its.conf ]]; then
		CONFFILES="${CONFFILES} $HOME/.its.conf"
	fi
	if [[ -n $Cflag ]]; then
		CONFFILES="${CONFFILES} ${ITSCONF}"
	fi
	its_domain=
	its_priority=
	for cf in ${CONFFILES}; do
		if [[ ! -r $cf ]]; then
			print "ERROR: Unable to read database configuration file $cf"
			exit 1
		elif [[ $cf != $DEFCONFFILE ]]; then
			print "       its.conf: reading $cf"
		fi
		$SED -e '/^#/d' -e '/^[ 	]*$/d' $cf | while read LINE; do
		    eval "${LINE}"
		done
	done

	#
	# If an information tracking system is explicitly identified by prefix,
	# we want to disregard the specified priorities and resolve it accordingly.
	#
	# To that end, we'll build a sed script to do each valid prefix in turn.
	#
	for p in ${valid_prefixes}; do
		#
		# When an informational URL was provided, translate it to a
		# hyperlink.  When omitted, simply use the prefix text.
		#
		if [[ -z ${itsinfo["${p}_INFO"]} ]]; then
			itsinfo["${p}_INFO"]=${p}
		else
			itsinfo["${p}_INFO"]="<a href=\\\"${itsinfo["${p}_INFO"]}\\\">${p}</a>"
		fi

		#
		# Assume that, for this invocation of webrev, all references
		# to this information tracking system should resolve through
		# the same URL.
		#
		# If the caller specified -O, then always use EXTERNAL_URL.
		#
		# Otherwise, look in the list of domains for a matching
		# INTERNAL_URL.
		#
		[[ -z $Oflag ]] && for d in ${its_domain}; do
			if [[ -n ${itsinfo["${p}_INTERNAL_URL_${d}"]} ]]; then
				itsinfo["${p}_URL"]="${itsinfo[${p}_INTERNAL_URL_${d}]}"
				break
			fi
		done
		if [[ -z ${itsinfo["${p}_URL"]} ]]; then
			itsinfo["${p}_URL"]="${itsinfo[${p}_EXTERNAL_URL]}"
		fi

		#
		# Turn the destination URL into a hyperlink
		#
		itsinfo["${p}_URL"]="<a href=\\\"${itsinfo[${p}_URL]}\\\">&</a>"

		# The character class below contains a literal tab
		print "/^${p}[: 	]/ {
				s;${itsinfo[${p}_REGEX]};${itsinfo[${p}_URL]};g
				s;^${p};${itsinfo[${p}_INFO]};
			}" >> ${its_sed_script}
	done

	#
	# The previous loop took care of explicit specification.  Now use
	# the configured priorities to attempt implicit translations.
	#
	for p in ${its_priority}; do
		print "/^${itsinfo[${p}_REGEX]}[ 	]/ {
				s;^${itsinfo[${p}_REGEX]};${itsinfo[${p}_URL]};g
			}" >> ${its_sed_script}
	done
fi

#
# Search for DO_EVERYTHING above for matching "for" statement
# and explanation of this terminator.
#
done

#
# Output directory.
#
WDIR=${WDIR:-$CWS/webrev}

#
# Name of the webrev, derived from the workspace name or output directory;
# in the future this could potentially be an option.
#
if [[ -n $oflag ]]; then
	WNAME=${WDIR##*/}
else
	WNAME=${CWS##*/}
fi

# Make sure remote target is well formed for remote upload/delete.
if [[ -n $Dflag || -n $Uflag ]]; then
	#
	# If remote target is not specified, build it from scratch using
	# the default values.
	#
	if [[ -z $tflag ]]; then
		remote_target=${DEFAULT_REMOTE_HOST}:${WNAME}
	else
		#
		# Check upload target prefix first.
		#
		if [[ "${remote_target}" != ${rsync_prefix}* &&
		    "${remote_target}" != ${ssh_prefix}* ]]; then
			print "ERROR: invalid prefix of upload URI" \
			    "($remote_target)"
			exit 1
		fi
		#
		# If destination specification is not in the form of
		# host_spec:remote_dir then assume it is just remote hostname
		# and append a colon and destination directory formed from
		# local webrev directory name.
		#
		typeset target_no_prefix=${remote_target##*://}
		if [[ ${target_no_prefix} == *:* ]]; then
			if [[ "${remote_target}" == *: ]]; then
				remote_target=${remote_target}${WNAME}
			fi
		else
			if [[ ${target_no_prefix} == */* ]]; then
				print "ERROR: badly formed upload URI" \
					"($remote_target)"
				exit 1
			else
				remote_target=${remote_target}:${WNAME}
			fi
		fi
	fi

	#
	# Strip trailing slash. Each upload method will deal with directory
	# specification separately.
	#
	remote_target=${remote_target%/}
fi

#
# Option -D by itself (option -U not present) implies no webrev generation.
#
if [[ -z $Uflag && -n $Dflag ]]; then
	delete_webrev 1 1
	exit $?
fi

#
# Do not generate the webrev, just upload it or delete it.
#
if [[ -n $nflag ]]; then
	if [[ -n $Dflag ]]; then
		delete_webrev 1 1
		(( $? == 0 )) || exit $?
	fi
	if [[ -n $Uflag ]]; then
		upload_webrev
		exit $?
	fi
fi

if [ "${WDIR%%/*}" ]; then
	WDIR=$PWD/$WDIR
fi

if [[ ! -d $WDIR ]]; then
	mkdir -p $WDIR
	(( $? != 0 )) && exit 1
fi

#
# Summarize what we're going to do.
#
print "      Workspace: ${PRETTY_CWS:-$CWS}"
if [[ -n $parent_webrev ]]; then
	print "Compare against: webrev at $parent_webrev"
else
	print "Compare against: ${PRETTY_PWS:-$PWS}"
fi

[[ -n $INCLUDE_FILE ]] && print "      Including: $INCLUDE_FILE"
print "      Output to: $WDIR"

#
# Save the file list in the webrev dir
#
[[ ! $FLIST -ef $WDIR/file.list ]] && cp $FLIST $WDIR/file.list

rm -f $WDIR/$WNAME.patch

touch $WDIR/$WNAME.patch

print "   Output Files:"

#
# Clean up the file list: Remove comments, blank lines and env variables.
#
$SED -e "s/#.*$//" -e "/=/d" -e "/^[   ]*$/d" $FLIST > /tmp/$$.flist.clean
FLIST=/tmp/$$.flist.clean

#
# First pass through the files: generate the per-file webrev HTML-files.
#
cat $FLIST | while read LINE
do
	set - $LINE
	P=$1

	#
	# Normally, each line in the file list is just a pathname of a
	# file that has been modified or created in the child.  A file
	# that is renamed in the child workspace has two names on the
	# line: new name followed by the old name.
	#
	oldname=""
	oldpath=""
	rename=
	if [[ $# -eq 2 ]]; then
		PP=$2			# old filename
		if [[ -f $PP ]]; then
			oldname=" (copied from $PP)"
		else
			oldname=" (renamed from $PP)"
		fi
		oldpath="$PP"
		rename=1
		PDIR=${PP%/*}
		if [[ $PDIR == $PP ]]; then
			PDIR="."   # File at root of workspace
		fi

		PF=${PP##*/}

		DIR=${P%/*}
		if [[ $DIR == $P ]]; then
			DIR="."   # File at root of workspace
		fi

		F=${P##*/}

	else
		DIR=${P%/*}
		if [[ "$DIR" == "$P" ]]; then
			DIR="."   # File at root of workspace
		fi

		F=${P##*/}

		PP=$P
		PDIR=$DIR
		PF=$F
	fi

	COMM=`getcomments html $P $PP`

	print "\t$P$oldname\n\t\t\c"

	# Make the webrev mirror directory if necessary
	mkdir -p $WDIR/$DIR

	#
	# We stash old and new files into parallel directories in $WDIR
	# and do our diffs there.  This makes it possible to generate
	# clean looking diffs which don't have absolute paths present.
	#

	build_old_new "$WDIR" "$PWS" "$PDIR" "$PF" "$CWS" "$DIR" "$F" || \
	    continue

	#
	# Keep the old PWD around, so we can safely switch back after
	# diff generation, such that build_old_new runs in a
	# consistent environment.
	#
	OWD=$PWD
	cd $WDIR/raw_files

	#
	# The "git apply" command does not tolerate the spurious
	# "./" that we otherwise insert; be careful not to include
	# it in the paths that we pass to diff(1).
	#
	if [[ $PDIR == "." ]]; then
		ofile=old/$PF
	else
		ofile=old/$PDIR/$PF
	fi
	if [[ $DIR == "." ]]; then
		nfile=new/$F
	else
		nfile=new/$DIR/$F
	fi

	mv_but_nodiff=
	cmp $ofile $nfile > /dev/null 2>&1
	if [[ $? == 0 && $rename == 1 ]]; then
		mv_but_nodiff=1
	fi

	#
	# If we have old and new versions of the file then run the appropriate
	# diffs.  This is complicated by a couple of factors:
	#
	#	- renames must be handled specially: we emit a 'remove'
	#	  diff and an 'add' diff
	#	- new files and deleted files must be handled specially
	#	- GNU patch doesn't interpret the output of illumos diff
	#	  properly when it comes to adds and deletes.  We need to
	#	  do some "cleansing" transformations:
	#	    [to add a file] @@ -1,0 +X,Y @@  -->  @@ -0,0 +X,Y @@
	#	    [to del a file] @@ -X,Y +1,0 @@  -->  @@ -X,Y +0,0 @@
	#
	cleanse_rmfile="$SED 's/^\(@@ [0-9+,-]*\) [0-9+,-]* @@$/\1 +0,0 @@/'"
	cleanse_newfile="$SED 's/^@@ [0-9+,-]* \([0-9+,-]* @@\)$/@@ -0,0 \1/'"

	rm -f $WDIR/$DIR/$F.patch
	if [[ -z $rename ]]; then
		if [ ! -f "$ofile" ]; then
			diff -u /dev/null $nfile | sh -c "$cleanse_newfile" \
			    > $WDIR/$DIR/$F.patch
		elif [ ! -f "$nfile" ]; then
			diff -u $ofile /dev/null | sh -c "$cleanse_rmfile" \
			    > $WDIR/$DIR/$F.patch
		else
			diff -u $ofile $nfile > $WDIR/$DIR/$F.patch
		fi
	else
		diff -u $ofile /dev/null | sh -c "$cleanse_rmfile" \
		    > $WDIR/$DIR/$F.patch

		diff -u /dev/null $nfile | sh -c "$cleanse_newfile" \
		    >> $WDIR/$DIR/$F.patch
	fi

	#
	# Tack the patch we just made onto the accumulated patch for the
	# whole wad.
	#
	cat $WDIR/$DIR/$F.patch >> $WDIR/$WNAME.patch
	print " patch\c"

	if [[ -f $ofile && -f $nfile && -z $mv_but_nodiff ]]; then
		${CDIFFCMD:-diff -bt -C 5} $ofile $nfile > $WDIR/$DIR/$F.cdiff
		diff_to_html $F $DIR/$F "C" "$COMM" < $WDIR/$DIR/$F.cdiff \
		    > $WDIR/$DIR/$F.cdiff.html
		print " cdiffs\c"

		${UDIFFCMD:-diff -bt -U 5} $ofile $nfile > $WDIR/$DIR/$F.udiff
		diff_to_html $F $DIR/$F "U" "$COMM" < $WDIR/$DIR/$F.udiff \
		    > $WDIR/$DIR/$F.udiff.html
		print " udiffs\c"

		if [[ -x $WDIFF ]]; then
			$WDIFF -c "$COMM" \
			    -t "$WNAME Wdiff $DIR/$F" $ofile $nfile > \
			    $WDIR/$DIR/$F.wdiff.html 2>/dev/null
			if [[ $? -eq 0 ]]; then
				print " wdiffs\c"
			else
				print " wdiffs[fail]\c"
			fi
		fi

		sdiff_to_html $ofile $nfile $F $DIR "$COMM" \
		    > $WDIR/$DIR/$F.sdiff.html
		print " sdiffs\c"
		print " frames\c"

		rm -f $WDIR/$DIR/$F.cdiff $WDIR/$DIR/$F.udiff
		difflines $ofile $nfile > $WDIR/$DIR/$F.count
	elif [[ -f $ofile && -f $nfile && -n $mv_but_nodiff ]]; then
		# renamed file: may also have differences
		difflines $ofile $nfile > $WDIR/$DIR/$F.count
	elif [[ -f $nfile ]]; then
		# new file: count added lines
		difflines /dev/null $nfile > $WDIR/$DIR/$F.count
	elif [[ -f $ofile ]]; then
		# old file: count deleted lines
		difflines $ofile /dev/null > $WDIR/$DIR/$F.count
	fi

	#
	# Check if it's man page, and create plain text, html and raw (ascii)
	# output for the new version, as well as diffs against old version.
	#
	if [[ -f "$nfile" && "$nfile" = *.+([0-9])*([a-zA-Z]) && \
	    -x $MANDOC && -x $COL ]]; then
		$MANDOC -Tascii $nfile | $COL -b > $nfile.man.txt
		source_to_html txt < $nfile.man.txt > $nfile.man.txt.html
		print " man-txt\c"
		print "$MANCSS" > $WDIR/raw_files/new/$DIR/man.css
		$MANDOC -Thtml -Ostyle=man.css $nfile > $nfile.man.html
		print " man-html\c"
		$MANDOC -Tascii $nfile > $nfile.man.raw
		print " man-raw\c"
		if [[ -f "$ofile" && -z $mv_but_nodiff ]]; then
			$MANDOC -Tascii $ofile | $COL -b > $ofile.man.txt
			${CDIFFCMD:-diff -bt -C 5} $ofile.man.txt \
			    $nfile.man.txt > $WDIR/$DIR/$F.man.cdiff
			diff_to_html $F $DIR/$F "C" "$COMM" < \
			    $WDIR/$DIR/$F.man.cdiff > \
			    $WDIR/$DIR/$F.man.cdiff.html
			print " man-cdiffs\c"
			${UDIFFCMD:-diff -bt -U 5} $ofile.man.txt \
			    $nfile.man.txt > $WDIR/$DIR/$F.man.udiff
			diff_to_html $F $DIR/$F "U" "$COMM" < \
			    $WDIR/$DIR/$F.man.udiff > \
			    $WDIR/$DIR/$F.man.udiff.html
			print " man-udiffs\c"
			if [[ -x $WDIFF ]]; then
				$WDIFF -c "$COMM" -t "$WNAME Wdiff $DIR/$F" \
				    $ofile.man.txt $nfile.man.txt > \
				    $WDIR/$DIR/$F.man.wdiff.html 2>/dev/null
				if [[ $? -eq 0 ]]; then
					print " man-wdiffs\c"
				else
					print " man-wdiffs[fail]\c"
				fi
			fi
			sdiff_to_html $ofile.man.txt $nfile.man.txt $F.man $DIR \
			    "$COMM" > $WDIR/$DIR/$F.man.sdiff.html
			print " man-sdiffs\c"
			print " man-frames\c"
		fi
		rm -f $ofile.man.txt $nfile.man.txt
		rm -f $WDIR/$DIR/$F.man.cdiff $WDIR/$DIR/$F.man.udiff
	fi

	if [[ -f $ofile ]]; then
		source_to_html Old $PP < $ofile > $WDIR/$DIR/$F-.html
		print " old\c"
	fi

	if [[ -f $nfile ]]; then
		source_to_html New $P < $nfile > $WDIR/$DIR/$F.html
		print " new\c"
	fi

	cd $OWD

	print
done

frame_nav_js > $WDIR/ancnav.js
frame_navigation > $WDIR/ancnav.html

# If we're in OpenSolaris mode and there's a closed dir under $WDIR,
# delete it - prevent accidental publishing of closed source

if [[ -n "$Oflag" ]]; then
	$FIND $WDIR -type d -name closed -exec /bin/rm -rf {} \;
fi

# Now build the index.html file that contains
# links to the source files and their diffs.

cd $CWS

# Save total changed lines for Code Inspection.
print "$TOTL" > $WDIR/TotalChangedLines

print "     index.html: \c"
INDEXFILE=$WDIR/index.html
exec 3<&1			# duplicate stdout to FD3.
exec 1<&-			# Close stdout.
exec > $INDEXFILE		# Open stdout to index file.

print "$HTML<head>$STDHEAD"
print "<title>$WNAME</title>"
print "</head>"
print "<body id=\"SUNWwebrev\">"
print "<div class=\"summary\">"
print "<h2>Code Review for $WNAME</h2>"

print "<table>"

#
# Get the preparer's name:
#
# If the SCM detected is Git, and the configuration property user.name is
# available, use that, but be careful to properly escape angle brackets (HTML
# syntax characters) in the email address.
#
# Otherwise, use the current userid in the form "John Doe (jdoe)", but
# to maintain compatibility with passwd(4), we must support '&' substitutions.
#
preparer=
if [[ "$SCM_MODE" == git ]]; then
	preparer=$(git config user.name 2>/dev/null)
	if [[ -n "$preparer" ]]; then
		preparer="$(echo "$preparer" | html_quote)"
	fi
fi
if [[ -z "$preparer" ]]; then
	preparer=$(
	    $PERL -e '
	        ($login, $pw, $uid, $gid, $quota, $cmt, $gcos) = getpwuid($<);
	        if ($login) {
	            $gcos =~ s/\&/ucfirst($login)/e;
	            printf "%s (%s)\n", $gcos, $login;
	        } else {
	            printf "(unknown)\n";
	        }
	')
fi

PREPDATE=$(LC_ALL=C /usr/bin/date +%Y-%b-%d\ %R\ %z\ %Z)
print "<tr><th>Prepared by:</th><td>$preparer on $PREPDATE</td></tr>"
print "<tr><th>Workspace:</th><td>${PRETTY_CWS:-$CWS}"
print "</td></tr>"
print "<tr><th>Compare against:</th><td>"
if [[ -n $parent_webrev ]]; then
	print "webrev at $parent_webrev"
else
	print "${PRETTY_PWS:-$PWS}"
fi
print "</td></tr>"
print "<tr><th>Summary of changes:</th><td>"
printCI $TOTL $TINS $TDEL $TMOD $TUNC
print "</td></tr>"

if [[ -f $WDIR/$WNAME.patch ]]; then
	wpatch_url="$(print $WNAME.patch | url_encode)"
	print "<tr><th>Patch of changes:</th><td>"
	print "<a href=\"$wpatch_url\">$WNAME.patch</a></td></tr>"
fi

if [[ -n "$iflag" ]]; then
	print "<tr><th>Author comments:</th><td><div>"
	cat /tmp/$$.include
	print "</div></td></tr>"
fi
print "</table>"
print "</div>"

#
# Second pass through the files: generate the rest of the index file
#
cat $FLIST | while read LINE
do
	set - $LINE
	P=$1

	if [[ $# == 2 ]]; then
		PP=$2
		oldname="$PP"
	else
		PP=$P
		oldname=""
	fi

	mv_but_nodiff=
	cmp $WDIR/raw_files/old/$PP $WDIR/raw_files/new/$P > /dev/null 2>&1
	if [[ $? == 0 && -n "$oldname" ]]; then
		mv_but_nodiff=1
	fi

	DIR=${P%/*}
	if [[ $DIR == $P ]]; then
		DIR="."   # File at root of workspace
	fi

	# Avoid processing the same file twice.
	# It's possible for renamed files to
	# appear twice in the file list

	F=$WDIR/$P

	print "<p>"

	# If there's a diffs file, make diffs links

	if [[ -f $F.cdiff.html ]]; then
		cdiff_url="$(print $P.cdiff.html | url_encode)"
		udiff_url="$(print $P.udiff.html | url_encode)"
		sdiff_url="$(print $P.sdiff.html | url_encode)"
		frames_url="$(print $P.frames.html | url_encode)"
		print "<a href=\"$cdiff_url\">Cdiffs</a>"
		print "<a href=\"$udiff_url\">Udiffs</a>"
		if [[ -f $F.wdiff.html && -x $WDIFF ]]; then
			wdiff_url="$(print $P.wdiff.html | url_encode)"
			print "<a href=\"$wdiff_url\">Wdiffs</a>"
		fi
		print "<a href=\"$sdiff_url\">Sdiffs</a>"
		print "<a href=\"$frames_url\">Frames</a>"
	else
		print " ------ ------"
		if [[ -x $WDIFF ]]; then
			print " ------"
		fi
		print " ------ ------"
	fi

	# If there's an old file, make the link

	if [[ -f $F-.html ]]; then
		oldfile_url="$(print $P-.html | url_encode)"
		print "<a href=\"$oldfile_url\">Old</a>"
	else
		print " ---"
	fi

	# If there's an new file, make the link

	if [[ -f $F.html ]]; then
		newfile_url="$(print $P.html | url_encode)"
		print "<a href=\"$newfile_url\">New</a>"
	else
		print " ---"
	fi

	if [[ -f $F.patch ]]; then
		patch_url="$(print $P.patch | url_encode)"
		print "<a href=\"$patch_url\">Patch</a>"
	else
		print " -----"
	fi

	if [[ -f $WDIR/raw_files/new/$P ]]; then
		rawfiles_url="$(print raw_files/new/$P | url_encode)"
		print "<a href=\"$rawfiles_url\">Raw</a>"
	else
		print " ---"
	fi

	print "<b>$P</b>"

	# For renamed files, clearly state whether or not they are modified
	if [[ -f "$oldname" ]]; then
		if [[ -n "$mv_but_nodiff" ]]; then
			print "<i>(copied from $oldname)</i>"
		else
			print "<i>(copied and modified from $oldname)</i>"
		fi
	elif [[ -n "$oldname" ]]; then
		if [[ -n "$mv_but_nodiff" ]]; then
			print "<i>(renamed from $oldname)</i>"
		else
			print "<i>(renamed and modified from $oldname)</i>"
		fi
	fi

	# If there's an old file, but no new file, the file was deleted
	if [[ -f $F-.html && ! -f $F.html ]]; then
		print " <i>(deleted)</i>"
	fi

	# Check for usr/closed and deleted_files/usr/closed
	if [ ! -z "$Oflag" ]; then
		if [[ $P == usr/closed/* || \
		    $P == deleted_files/usr/closed/* ]]; then
			print "&nbsp;&nbsp;<i>Closed source: omitted from" \
			    "this review</i>"
		fi
	fi

	manpage=
	if [[ -f $F.man.cdiff.html || \
	    -f $WDIR/raw_files/new/$P.man.txt.html ]]; then
		manpage=1
		print "<br/>man:"
	fi

	if [[ -f $F.man.cdiff.html ]]; then
		mancdiff_url="$(print $P.man.cdiff.html | url_encode)"
		manudiff_url="$(print $P.man.udiff.html | url_encode)"
		mansdiff_url="$(print $P.man.sdiff.html | url_encode)"
		manframes_url="$(print $P.man.frames.html | url_encode)"
		print "<a href=\"$mancdiff_url\">Cdiffs</a>"
		print "<a href=\"$manudiff_url\">Udiffs</a>"
		if [[ -f $F.man.wdiff.html && -x $WDIFF ]]; then
			manwdiff_url="$(print $P.man.wdiff.html | url_encode)"
			print "<a href=\"$manwdiff_url\">Wdiffs</a>"
		fi
		print "<a href=\"$mansdiff_url\">Sdiffs</a>"
		print "<a href=\"$manframes_url\">Frames</a>"
	elif [[ -n $manpage ]]; then
		print " ------ ------"
		if [[ -x $WDIFF ]]; then
			print " ------"
		fi
		print " ------ ------"
	fi

	if [[ -f $WDIR/raw_files/new/$P.man.txt.html ]]; then
		mantxt_url="$(print raw_files/new/$P.man.txt.html | url_encode)"
		print "<a href=\"$mantxt_url\">TXT</a>"
		manhtml_url="$(print raw_files/new/$P.man.html | url_encode)"
		print "<a href=\"$manhtml_url\">HTML</a>"
		manraw_url="$(print raw_files/new/$P.man.raw | url_encode)"
		print "<a href=\"$manraw_url\">Raw</a>"
	elif [[ -n $manpage ]]; then
		print " --- ---- ---"
	fi

	print "</p>"

	# Insert delta comments
	print "<blockquote><pre>"
	getcomments html $P $PP
	print "</pre>"

	# Add additional comments comment
	print "<!-- Add comments to explain changes in $P here -->"

	# Add count of changes.
	if [[ -f $F.count ]]; then
	    cat $F.count
	    rm $F.count
	fi

	if [[ $SCM_MODE == "unknown" ]]; then
		# Include warnings for important file mode situations:
		# 1) New executable files
		# 2) Permission changes of any kind
		# 3) Existing executable files
		old_mode=
		if [[ -f $WDIR/raw_files/old/$PP ]]; then
			old_mode=`get_file_mode $WDIR/raw_files/old/$PP`
		fi

		new_mode=
		if [[ -f $WDIR/raw_files/new/$P ]]; then
			new_mode=`get_file_mode $WDIR/raw_files/new/$P`
		fi

		if [[ -z "$old_mode" && "$new_mode" = *[1357]* ]]; then
			print "<span class=\"chmod\">"
			print "<p>new executable file: mode $new_mode</p>"
			print "</span>"
		elif [[ -n "$old_mode" && -n "$new_mode" &&
		    "$old_mode" != "$new_mode" ]]; then
			print "<span class=\"chmod\">"
			print "<p>mode change: $old_mode to $new_mode</p>"
			print "</span>"
		elif [[ "$new_mode" = *[1357]* ]]; then
			print "<span class=\"chmod\">"
			print "<p>executable file: mode $new_mode</p>"
			print "</span>"
		fi
	fi

	print "</blockquote>"
done

print
print
print "<hr></hr>"
print "<p style=\"font-size: small\">"
print "This code review page was prepared using <b>$0</b>."
print "Webrev is maintained by the <a href=\"http://www.illumos.org\">"
print "illumos</a> project.  The latest version may be obtained"
print "<a href=\"http://src.illumos.org/source/xref/illumos-gate/usr/src/tools/scripts/webrev.sh\">here</a>.</p>"
print "</body>"
print "</html>"

exec 1<&-			# Close FD 1.
exec 1<&3			# dup FD 3 to restore stdout.
exec 3<&-			# close FD 3.

print "Done."

#
# If remote deletion was specified and fails do not continue.
#
if [[ -n $Dflag ]]; then
	delete_webrev 1 1
	(( $? == 0 )) || exit $?
fi

if [[ -n $Uflag ]]; then
	upload_webrev
	exit $?
fi