This file is indexed.

/usr/bin/xen-create-image is in xen-tools 4.4-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
#!/usr/bin/perl -w

=encoding utf8

=head1 NAME

xen-create-image - Easily create new Xen instances with networking and OpenSSH.

=head1 SYNOPSIS

xen-create-image --hostname=<hostname> <further options>


=head1 EXAMPLES

xen-create-image --hostname=some-domu --dist=wheezy --lvm=vg0

xen-create-image --hostname=some-domu --dist=precise --dir=/srv/xen

See below for more specific examples: LOOPBACK EXAMPLES, LVM EXAMPLE
and EVMS EXAMPLE.


=head1 OPTIONS

  Help Options:

   --help        Show the help information for this script.

   --manual      Read the manual, and examples, for this script.

   --(no)verbose (Don't) show more of what xen-create-image is
                 currently doing.

   --dumpconfig  Show current configuration.

   --version     Show the version number and exit.



  Size / General options:

   --(no)accounts
                (Don't) copy all non-system accounts to the guest
                image

   --admins     Specify that some administrators should be created for
                this image, using xen-shell.

   --(no)boot   (Don't) boot the new instance after creating it.

   --cache=bool Cache .deb files on the host when installing the new
                guest with the debootstrap tool. Accepted values:
                "yes" (default) and "no".

   --cachedir=/path/to/cache/directory
                Override the default .deb cache directory. Defaults to
                /var/cache/apt/archives/ if it exists (i.e. on Debian
                and Ubuntu) and /var/cache/xen-tools/archives/ else
                (i.e. on Fedora and CentOS).

   --config=file
                Read the specified file in addition to the global
                configuration file.

   --(no)copyhosts
                (Don't) copy entries from the dom0's /etc/hosts file
                to the guest

   --copy-cmd   NOP:  Ignored.

   --debootstrap-cmd=/path/to/command
                Specify which debootstrap command is used. Defaults to
                debootstrap if both, debootstrap and cdebootstrap are
                installed. Specifying the path is optional.

   --disk_device=diskname
                Use specified device name for virtual devices instead
                of the default value "xvda".

   --extension=ext
                Specify the suffix to give the Xen configuration
                file. (Default value: ".cfg")

   --(no)force  (Don't) force overwriting existing images. This will
                remove existing images or LVM volumes which match
                those which are liable to be used by the new
                invocation.

   --fs=fs      Specify the filesystem type to use for the new guest.
                Valid choices are 'ext2', 'ext3', 'ext4', 'reiserfs',
                'xfs' or 'btrfs'. (Note: pygrub *DOES NOT* support
                xfs)

   --genpass=1  Generate a random root password (default, set to 0 to
                turn off)

   --genpass_len=N
                Override the default password length of 8 and generate
                a random password of length N. Note: this only works
                in conjunction with --genpass

   --hash_method=algorithm
                Override the default hashing method of sha256 and use
                the provided algorithm. Can be : md5, sha256 or sha512

   --hooks=1    Specify whether to run hooks after the image is created.

   --ide        Use IDE names for virtual devices (i.e. hda not xvda)

   --image=str  Specify whether to create "sparse" or "full" disk
                images.  Full images are mandatory when using LVM, so
                this setting is ignored in that case.

   --image-dev=/path/to/device
                Specify a physical/logical volume for the disk image.

   --initrd=/path/to/initrd
                Specify the initial ramdisk. If an image is specified
                it must exist.

   --install=1  Specify whether to install the guest system or not.

   --(no)keep   (Don't) keep our images if installation fails. It
                maybe unmounted, though.

   --kernel=/path/to/kernel
                Set the path to the kernel to use for domU. If a
                kernel is specified it must exist.

   --memory=size
                Setup the amount of memory allocated to the new
                instance.  As suffix recognized size units are "M",
                "MB", "G" and "GB" (case does not matter). If there's
                no unit given, megabytes are assumed.

   --maxmem=size
                Setup the maximum amount of memory that can be allocated
                to the new instance. As suffix recognized size units are "M",
                "MB", "G" and "GB" (case does not matter). If there's
                no unit given, megabytes are assumed.
                Required for dynamic memory ballooning.

   --modules=/path/to/modules
                Set the path to the kernel modules to use for domU.
                If modules are specified they must exist.

   --nohosts    Don't touch /etc/hosts on the dom0.

   --noswap     Do not create a swap partition. When this option is
                used the system will not have a swap entry added to
                its /etc/fstab file either.

   --no-xen-ok  Don't complain if xen seems not installed or xend is
                not running. (Needed for the testsuite.)

   --output=dir Specify the output directory to create the xen
                configuration file within.

   --partitions=file
                Use a specific partition layout configuration file.
                See /etc/xen-tools/partitions.d/sample-server for an
                example partitioning configuration.  Not supported
                with the image-dev and swap-dev options.  Parameters
                fs, size, swap and noswap are ignored when using this
                option.

   --password=passphrase
                Set the root password for the new guest.

   --(no)passwd (Don't) ask for a root password interactively during
                setup.  NOTE: This overrides --genpass --password.

   --(no)pygrub DomU should (not) be booted using pygrub.

   --role=role  Run the specified role script(s) post-install.  Role
                scripts are discussed later in this manpage.  Can be
                an absolute path. Otherwise it's relative to the value
                of --roledir.

   --role-args="--arg1 --arg2"
                Pass the named string literally to any role script.
                This is useful for site-specific roles.

   --finalrole=role
                Similar to role scripts. Run the specified role
                script(s) after cfg file creation.

   --roledir=/path/to/directory
                Specify the directory which contains the role scripts.
                This defaults to /etc/xen-tools/role.d/

   --scsi       Use SCSI names for virtual devices (i.e. sda not xvda)

   --serial_device=serialname
                Install a getty on the specified serial device instead
                of the default device.

   --size=size  Set the size of the primary disk image.

   --swap=size  Set the size of the swap partition.

   --swap-dev=/path/to/device
                Specify a physical/logical volume for swap usage.

   --tar-cmd    NOP: Ignored.

   --dontformat Do not format the devices specified for installation.
                Useful if you want tighter control over the filesystem
                creation. Requires the filesystems to be created
                beforehand.

   --vcpus=num
                Set the number of vcpus that the new instance will
                have instead of the default value of "1".



  Installation options:

   --arch=arch  Pass the given architecture to debootstrap, rinse, or
                rpmstrap when installing the system.  This argument is
                ignored for other install methods.

   --dist=dist  Specify the distribution you wish to install.

   --install-method=method
                Specify the installation method to use. Valid methods
                are:

                * debootstrap
                * cdebootstrap
                * rinse
                * rpmstrap (deprecated)
                * tar (needs --install-source=tarball.tar)
                * copy (needs --install-source=/path/to/copy/from)

                (Default value for Debian and Ubuntu: debootstrap)

   --install-source=/path/to/tarball
                Specify the source path to use when installing via
                a copy or tarball installation.

   --mirror=url Setup the mirror to use when installing via
                debootstrap. (Default value: mirror used in
                /etc/apt/sources.list or for Debian
                "http://http.debian.net/debian/" and for Ubuntu
                "http://archive.ubuntu.com/ubuntu/")

                The above mentioned Debian mirror hostname
                automatically tries to choose a more or less close
                Debian mirror. See http://http.debian.net/ for
                details.

   --apt_proxy=protocol://hostname:port/
                Specify a proxy to be used by debootstrap, and within
                the guest. Needs the same syntax as APT's
                Acquire::http::Proxy. See apt.conf(5).

   --template=tmpl
                Specify which template file to use when creating the
                Xen configuration file.



  Networking options:

   --bridge=brname
                Optionally, set a specific bridge for the new
                instance.  This can be especially useful when running
                multiple bridges on a dom0.

   --broadcast=123.456.789.ABC
                Setup the broadcast address for the new instance.

   --(no)dhcp   The guest will (not) be configured to fetch its
                networking details via DHCP.

   --gateway=gw Setup the network gateway for the new instance.

   --ip=123.456.789.ABC
                Setup the IP address of the machine, multiple IPs are
                allowed.  When specifying more than one IP the first
                one is setup as the "system" IP, and the additional
                ones are added as aliases.

                Note that Xen 3.x supports a maximum of three vif
                statements per guest. This option conflicts with
                --dhcp.

   --mac=AA:BB:CC:DD:EE:FF
                Specify the MAC address to use for a given interface.
                This is only valid for the first IP address specified,
                or for DHCP usage.  (ie. you can add multiple --ip
                flags, but the specific MAC address will only be used
                for the first interface.)

   --netmask=123.456.789.ABC
                Setup the netmask for the new instance.

   --nameserver="123.456.789.ABC 123.456.789.DEF"
                Setup the nameserver of the machine, multiple space
                separated nameservers are allowed.  If not provided,
                Dom0's /etc/resolv.conf will be copied to guest.

   --vifname=vifname
                Optionally, set a specific vif name for the new
                instance.



  Mandatory options:

   --dir=/path/to/directory

                Specify where the output images should go.
                Subdirectories will be created for each guest.

                If you do not wish to use loopback images specify
                --lvm or --evms.  (These three options are mutually
                exclusive.)

   --evms=lvm2/container
                Specify the container to save images within,
                i.e. '--evms lvm2/mycontainer'.  If you do not wish to
                use EVMS specify --dir or --lvm.  (These three options
                are mutually exclusive.)

   --hostname=host.example.org
                Set the hostname of the new guest system.  Ideally
                this will be fully-qualified since several of the hook
                scripts will expect to be able to parse a domain name
                out of it for various purposes.

   --lvm=vg     Specify the volume group to save images within.
                If you do not wish to use LVM specify --dir or --evms.
                (These three options are mutually exclusive.)


=head1 NOTES

  This script is a wrapper around three distinct external tools which
 complete various aspects of the new system installation.

=over 8

=item B<xt-install-image>
Install a new distribution.

=item B<xt-customize-image>
Run a collection of hook scripts to customise the freshly installed system.

=item B<xt-create-xen-config>
Create a Xen configuration file in so that xm/xl can start the new domain.

=back

  The result of invoking these three scripts, and some minor glue between
 them, is a simple means of creating new Xen guest domains.


=head1 DESCRIPTION

  xen-create-image is a simple script which allows you to create new
 Xen instances easily.  The new image will be given two volumes.  These
 volumes will be stored upon the host as either loopback files, or
 LVM logical volumes:

   1.  An image for the systems root disk.
   2.  An image for the systems swap device.

  The new virtual installations will be configured with networking,
 have OpenSSH installed upon it, and have most of its basic files
 setup correctly.

  If you wish you can configure arbitrary partitioning schemes, rather
 than being restricted to just the two standard volumes.  For more
 details on this please see the later section in this manual "PARTITIONING".

  If you wish to install additional packages or do any additional
 configuration of your new guests, please read the section on "ROLES".


=head1 CONFIGURATION

  To reduce the length of the command line each of the supported options
 may be specified inside a configuration file.

  The global configuration file read for options is:

     /etc/xen-tools/xen-tools.conf

  The configuration file may contain comments which begin with the
 hash '#' character.  Otherwise the format is 'key = value'.

  A sample configuration file would look like this:

=for example begin

  #
  #  Output directory.  Images are stored beneath this directory, one
  # subdirectory per hostname.
  #
  dir = /home/xen

  #
  #  LVM users should disable the 'dir' setting above, and instead
  # specify the name of the volume group to use.
  #
  # lvm = myvolume

  #
  #  EVMS users should disable the dir setting above and instead specify
  # a container.  For example, if you have an lvm2 container named box,
  # put lvm2/box.  This is how it is named in the evms interface.
  #
  #  Warning... this has not been tested with anything but lvm2 but should
  # be generalizable.
  #
  # evms= lvm2/myvolume

  #
  #  Disk and Sizing options.
  #
  size       = 2Gb      # Disk image size.
  image      = full     # Allocate the full disk size immediately.
  memory     = 128Mb    # Memory size
  maxmem     = 512Mb    # Memory size
  swap       = 128Mb    # Swap size
  fs         = ext3     # use EXT3 filesystems
  dist       = stable   # Default distribution to install.

  #
  # Kernel options.
  #
  kernel      = /boot/vmlinuz-`uname -r`
  initrd      = /boot/initrd.img-`uname -r`

  #
  # Networking options.
  #
  gateway    = 192.168.1.1
  broadcast  = 192.168.1.255
  netmask    = 255.255.255.0


  #
  # Installation method:
  # One of "copy", "debootstrap", "cdebootstrap", "rinse", "rpmstrap", or "tar".
  #
  install-method = debootstrap

=for example end

  Using this configuration file a new image may be created with the
 following command:

      xen-create-image --hostname=vm03.my.flat --ip=192.168.1.201

  This makes use of loopback images stored beneath /home/xen and
 will be installed via the debootstrap command.


=head1 NETWORKING AUTO-SETUP

  We've already seen how the "gateway" and "netmask" options can
 be used to specify the networking options of the freshly created
 Xen guests.

  One other useful shortcut is the use of an automatic IP address.
 You can specify '--ip=auto' and the system will choose and use
 an IP address from those listed in /etc/xen-tools/ips.txt.

  For example if you wished to have Xen guests automatically
 take an address from the range 192.168.1.100-192.168.1.200 you
 would first prepare the system by running this:

=for example start

  rm /etc/xen-tools/ips.txt
  for i in $(seq 100 200) ; do echo 192.168.1.$i >> /etc/xen-tools/ips.txt ; done

=for example end

  Now you can create a guest with the command:

=for example start

  xen-create-image --ip=auto --hostname=blah [--dist=...]

=for example end

  The first time this ran the machine would receive an IP address
 from the pool which we've created.  This IP would be marked as used,
 and would no longer be available.  If all the IP addresses are taken
 then the system will fail.


=head1 PARTITIONING

  By default all new guests are created with two "volumes", one
 for the root filesystem and one for the new system's swap.

  If you wish you may specify an alternative partitioning scheme.
 Simply create a file inside the directory /etc/xen-tools/partitions.d/
 specifying your partition layout.  (Use the existing file "sample-server"
 as a template).

  Now when you create a new image specify the name of this file with as
 an argument to the --partition option.


=head1 XEN CONFIGURATION FILE

  Once a new image has been created an appropriate configuration file
 for Xen will be saved in the directory /etc/xen by default.  However
 you may change the output directory with the --output flag.

  The configuration file is built up using the template file
 /etc/xen-tools/xm.tmpl - which is a file processed via
 the Text::Template perl module.

  If you wish to modify the files which are generated please make your
 changes to that input file.

  Alternatively you can create multiple configuration files and
 specify the one to use with the --template option.


=head1 LOOPBACK EXAMPLES

  The following will create a 2Gb disk image, along with a 128Mb
 swap file with Debian Stable setup and running via DHCP.

     xen-create-image --size=2Gb --swap=128Mb --dhcp --dist=stable \
          --dir=/home/xen --hostname=vm01.my.flat

  This next example sets up a host which has the name 'vm02.my.flat' and
 IP address 192.168.1.200, with the gateway address of 192.168.1.1

     xen-create-image --size=2Gb --swap=128Mb \
          --ip=192.168.1.200 \
          --netmask=255.255.255.0
          --gateway=192.168.1.1 \
          --nameserver=192.168.1.1 \
          --dir=/home/xen --hostname=vm02.my.flat

  The directory specified for the output will be used to store the volumes
 which are produced.  To avoid clutter each host will have its images
 stored beneath the specified directory, named after the hostname.

  For example the images created above will be stored as:

   $dir/domains/vm01.my.flat/
   $dir/domains/vm01.my.flat/disk.img
   $dir/domains/vm01.my.flat/swap.img

   $dir/domains/vm02.my.flat/
   $dir/domains/vm02.my.flat/disk.img
   $dir/domains/vm02.my.flat/swap.img

  The '/domains/' subdirectory will be created if necessary.


=head1 LVM EXAMPLE

  If you wish to use an LVM volume group instead of a pair of loopback
 images as shown above you can instead use the --lvm argument to
 specify one.

     xen-create-image --size=2Gb --swap=128Mb --dhcp \
          --lvm=myvolumegroup --hostname=vm01.my.flat

  The given volume group will have two new logical volumes created within it:

   ${hostname}-swap
   ${hostname}-disk

  The disk image may be mounted, as you would expect, with the following
 command:

    mkdir -p /mnt/foo
    mount /dev/myvolumegroup/vm01.my.flat-disk /mnt/foo


=head1 EVMS EXAMPLE

  If you wish to use an EVMS storage container instead of a pair of loopback
 images as shown above you can instead use the --evms argument to
 specify one.  The below example assumes an lvm2 container.

     xen-create-image --size=2Gb --swap=128Mb --dhcp \
          --evms=lvm2/myvolumegroup --hostname=vm01.my.flat

  The given storage container will have two new EVMS volumes created within it:

   ${hostname}-swap
   ${hostname}-disk

  The disk image may be mounted, as you would expect, with the following
 command:

    mkdir -p /mnt/foo
    mount /dev/evms/vm01.my.flat-disk /mnt/foo


=head1 INSTALLATION METHODS

  The new guest images may be installed in several different ways:

  1.  Using the [c]debootstrap command, which must be installed and present.
  2.  Using the rpmstrap command, which must be installed and present.
  3.  using the rinse command, which must be installed and present.
  4.  By copying an existing installation.
  5.  By untarring a file containing a previous installation.

  These different methods can be selected by either the command line
 arguments, or settings in the configuration file.  Only one installation
 method may be specified at a time; they are mutually-exclusive.


=head1 INSTALLATION SPEEDUPS

  After performing your first installation you can customize it, or
 use it untouched, as a new installation source.  By doing this you'll
 achieve a significant speedup, even above using the debootstrap caching
 support.

  There are two different ways you can use the initial image as source
 for a new image:

  1.  By tarring it up and using the tar-file as an installation source.
  2.  By mounting the disk image of the first system and doing a literal copy.

  Tarring up a pristine, or customised, image will allow you to install
 with a command such as:

     xen-create-image --size=2Gb --swap=128Mb --dhcp \
          --lvm=myvolumegroup --hostname=vm01.my.flat \
          --install-method=tar --install-source=/path/to/tar.file.tar

  The advantage of the tarfile approach is that you'll not need to
 keep a disk image mounted if you were to use the --copy argument
 to create a new image using the old one as source:

     xen-create-image --size=2Gb --swap=128Mb --dhcp \
          --lvm=myvolumegroup --hostname=vm01.my.flat \
          --install-method=copy --install-source=/path/to/copy/from


=head1 DEBOOTSTRAP CACHING

  When installing new systems with the debootstrap tool there is
 a fair amount of network overhead.

  To minimize this the .deb files which are downloaded into the
 new instance are cached by default upon the host, in the directory
 /var/cache/apt/archives or, if this does not exist, in
 /var/cache/xen-tools/archives. This can be overridden with the
 --cache-dir command-line and configuration option.

  This feature can be disabled with the command line flag --cache=no,
 or by the matching setting in the configuration file.

  When a new image is created these packages are copied into the new
 image - before the debootstrap process runs - this should help avoid
 expensive network reading.

  If you wish to clean the host's apt cache (/var/cache/apt/archivees)
 you may do so with apt-get, namely:

  apt-get clean

  If you set your cache directory to anything else, simply rm the
 contents of the directory.


=head1 ROLES

  Currently there are some roles scripts included which work for
 the Debian and Ubuntu distrubtions only. They are included
 primarily as examples of the kind of things you could accomplish.

  The supplied scripts are:

=over 8

=item builder
Setup the new virtual images with commonly used packages for rebuilding
Debian packages from their source.

=item cfengine
Install cfengine2 on the virtual image and copy the cfengine
configuration from Dom0.

=item editor
Allows generalised editing of files for guests.

This script works via a skeleton directory containing small sed files
which will contain edits to be applied to an arbitrary tree of files
upon the new domU.

For example if we have the following sed file:

  /etc/xen-tools/sed.d/etc/ssh/sshd_config.sed

this will be applied to /etc/ssh/sshd_config upon the new guest *if*
it exists.  If the file encoded in the name doesn't exist then it will
be ignored.

=item gdm
Install an X11 server, using VNC and GDM

=item minimal
Customise the generated images to remove some packages.

=item puppet
Install puppet on the virtual image and copy the cfengine
configuration from Dom0.

=item tmpfs
Sets up /tmp, /var/run and /var/lock as tmpfs in the DomU.

=item udev
Install udev in the DomU. Most distributions install udev by default
nowadays, so this role is probably only interesting for legacy systems
which need udev anyway.

=item xdm
Install an X11 server, using VNC and XDM

=back

  If you'd like to include your own role scripts you'll need to
 create a file in /etc/xen-tools/role.d, and then specify the
 name of that file with "--role=filename".  Additionally you
 may pass options to your role-script with the --role-args
 flag.

  For example the script /etc/xen-tools/role.d/gdm would be used
 by executing with "--role=gdm".

  Role scripts are invoked with the directory containing the
 installed system as their first argument, and anything passed
 as a role-arg will be passed allong as additional arguments.

  NOTE: Role scripts are invoked before the config file generation.
        If you need access to the config file from within your role,
        use --finalrole.
  NOTE: Multiple role scripts may be invoked if you separate their
 names with commas.


=head1 THE SKELETON DIRECTORY

  Any files present in the directory /etc/xen-tools/skel will be copied
 across to each new guest image.  The role of this directory is analogous
 to the /etc/skel directory.

  A typical use for this would be to copy a public key across to each
 new system.  You could do this by running:

=for example start

    mkdir -p /etc/xen-tools/skel/root/.ssh
    chmod -R 700 /etc/xen-tools/skel/root
    cp /root/.ssh/id_rsa.pub /etc/xen-tools/skel/root/.ssh/authorized_keys2
    chmod 644 /etc/xen-tools/skel/root/.ssh/authorized_keys2

=for example cut


=head1 AUTHORS

 Steve Kemp, http://www.steve.org.uk/
 Axel Beckert, http://noone.org/abe/
 Dmitry Nedospasov, http://nedos.net/
 Stéphane Jourdois


=head1 LICENSE

Copyright (c) 2005-2009 by Steve Kemp, (c) 2010-2013 by The Xen-Tools
Development Team. All rights reserved.

This module is free software;
you can redistribute it and/or modify it under
the same terms as Perl itself.
The LICENSE file contains the full text of the license.

=cut

$SIG{INT} = \&clean_up;

use strict;
use English;
use Digest::MD5 qw/ md5_hex /;
use Env;
use File::Path qw/ mkpath /;
use File::Temp qw/ tempdir /;
use File::Copy qw/ mv cp /;
use File::Which;
use Getopt::Long;
use Pod::Usage;
use Data::Dumper;
use Data::Validate::URI qw/ is_uri /;
use Data::Validate::IP qw/ is_ipv4 /;
use Data::Validate::Domain qw/ is_hostname /;
use Term::UI;
use Term::ReadLine;
use Xen::Tools::Common;


#
#  Configuration values read initially from the global configuration
# file, then optionally overridden by the command line.
#
my %CONFIG;


#
#  Partition layout information values read from the partitions file,
# or constructed automatically if no partitions file is specified.
#
my @PARTITIONS = undef;


#
#  Global variable containing the temporary file where our image
# is mounted for installation purposes.
#
#  Why is this here?
#
#  Well it makes sure that the magic "END" section can unmount it
# if there are errors.
#
#
my $MOUNT_POINT = undef;


#
# Release number.
#
my $RELEASE = '4.4';


#
# Variable for ip addresses for output
#
my $IP_ADDRESSES = '';


#
# Variable for generated password
#
my $PASSWORD = '';



# Minor helpers for reducing code duplication
sub fail     ($) { fail_with_config($_[0], \%CONFIG); }
sub logprint ($) { logprint_with_config($_[0], \%CONFIG); }

#
#  Setup default options.
#
setupDefaultOptions();


#
#  Read the global configuration file.
#
readConfigurationFile("/etc/xen-tools/xen-tools.conf", \%CONFIG);


#
#  Parse the command line arguments.
#
parseCommandLineArguments();


#
#  If we received an additional configuration file then read it.
#
if ( $CONFIG{ 'config' } )
{
    my $path = $CONFIG{ 'config' };

    # If not fully-qualified then read from /etc/xen-tools.
    if ( $path !~ /^[\/]/ )
    {
        $path = "/etc/xen-tools/" . $path;
    }

    # Read the file, if it exists.
    if ( -e $path )
    {
        readConfigurationFile($path, \%CONFIG);
    }
    else
    {
        logprint( "The specified configuration file does not exist: '$path'\n".
                  "Aborting\n\n" );
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }
}


#
#  Process --debug
#
if ( $CONFIG{ 'debug' } )
{
    foreach my $key ( sort keys %CONFIG )
    {
        print $key;
        print " : " . $CONFIG{ $key } if ( $CONFIG{ $key } );
        print "\n";
    }
    $CONFIG{'FAIL'} = 1;
    exit 127;
}



#
#  Check the environment - after parsing arguments.
#
#  This is required so that the "--help" flag will work even if our support
# scripts are not installed, etc.
#
checkSystem();


#
#  Ensure we're started by root at this point.  This is required
# to make sure we can create new LVM volumes, mount loopback images, or
# carry out other privileged actions.
#
testRootUser();


#
#  Check our arguments were sane and complete.
#
checkArguments();


#
#  Make sure we have a log directory
#
setupLogFile();


#
#  Check we have binaries installed which we expect to use.
#
checkBinariesPresent();


#
#  Setup default partitioning scheme if we don't have one.
#
#  NOTE:  This must be done before we call "showSummary".
#
if ( !$#PARTITIONS )
{
    populatePartitionsData()
      if ( ( $CONFIG{ 'dir' } ) ||
           ( $CONFIG{ 'evms' } ) ||
           ( $CONFIG{ 'lvm' } ) );
}


#
#  Show a summary of what we're going to do.
#
showSummary();



#
#  Create and format the images if we're using loopback filesystems.
#
if ( $CONFIG{ 'dir' } )
{

    #
    #  Test to see if "loop" module is loaded.  This is probably
    # not required, except for paranoia.
    #
    testLoopbackModule();

    #
    #  Create disk + swap images.
    #
    createLoopbackImages();
}
elsif ( $CONFIG{ 'lvm' } )
{

    #
    #  Create our LVM partitions.
    #
    createLVMBits();
}
elsif ( $CONFIG{ 'evms' } )
{

    #
    #  Create our EVMS partitions.
    #
    createEVMSBits();
}
elsif ( $CONFIG{ 'image-dev' } )
{

    #
    #  Use physical disc
    #
    usePhysicalDevice();
}
else
{

    # Can't happen we didn't get an installation type.
    logprint( "Error:  No recognised installation type.\n".
              "Please specify a directory, lvm, or evms volume to use.\n" );
    $CONFIG{'FAIL'} = 1;
    exit 127;
}


#
#  Mount the image.
#
mountImage();


#
#  Export our environment for the hooks/role script we might be
# running later.
#
#  Do this unconditionally now, so that we're all setup to run
# a hook even if we're not installing a system.
#
exportEnvironment();


#
#  If we're installing then do so, and test that it worked with
# a binary name that is reasonably likely to exist under any
# distribution of GNU/Linux.
#
if ( $CONFIG{ 'install' } )
{

    #
    #  Install the system.
    #
    installSystem();

    #
    #  Did that work?
    #
    if ( !-x $MOUNT_POINT . "/bin/ls" )
    {
        logprint("System installation failed: /bin/ls missing.  Aborting.\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    #
    #  Now customize the installation - setting up networking, etc.
    #
    if ( $CONFIG{ 'hooks' } )
    {
        runCustomisationHooks();
    }
}



#
#  Run any specified role scripts.
#
runRoleScripts( $CONFIG{ 'role' } );


#
#  Create the Xen configuration file.
#
runXenConfigCreation();


#
#  Run any specified role scripts.
#
runRoleScripts( $CONFIG{ 'finalrole' } );


#
#  Setup the password if the user wanted that.
#
setupRootPassword() if ( $CONFIG{ 'passwd' } or $CONFIG{ 'genpass' } or $CONFIG{ 'password' });


#
#  Report success.
#
logprint("All done\n");


#
#  Finished.
#
exit 0;



=begin doc

  Test that this system is fully setup for the new xen-create-image
 script.

  This means that the the companion scripts xt-* are present on the
 host and executable.

=end doc

=cut

sub checkSystem
{
    #
    #  Make sure that we have Text::Template installed - this
    # will be used by `xt-create-xen-config` and if that fails then
    # running is pointless.
    #
    my $test = "use Text::Template";
    eval($test);
    if ( ($@) && ( !$CONFIG{ 'force' } ) )
    {
        print <<E_O_ERROR;

  Aborting:  The Text::Template perl module isn\'t installed or available.

  Specify '--force' to skip this check and continue regardless.

E_O_ERROR
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }



    #
    #  Check that all the binaries have been installed properly
    #
    my @required =
      qw(xt-customize-image xt-install-image xt-create-xen-config);

    foreach my $bin (@required)
    {
        if ( !defined( which($bin) ) )
        {
            logprint( "The script '$bin' was not found.\nAborting\n\n" );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }

    #
    #  Make sure that xen-shell is installed if we've got an --admin
    # flag specified
    #
    if ( $CONFIG{ 'admins' } )
    {
        my $shell = undef;
        $shell = "/usr/bin/xen-login-shell"
          if ( -x "/usr/bin/xen-login-shell" );
        $shell = "/usr/local/bin/xen-login-shell"
          if ( -x "/usr/bin/local/xen-login-shell" );

        if ( !defined($shell) )
        {
            print <<EOF;

  You've specified administrator accounts for use with the xen-shell,
 however the xen-shell doesn't appear to be installed.

  Aborting.
EOF
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }


    #
    #  Test the system has a valid (network-script) + (vif-script) setup.
    #
    testXenConfig();

}



=begin doc

  Test that the current Xen host has a valid network configuration,
 this is designed to help newcomers to Xen.

=end doc

=cut

sub testXenConfig
{

    # wierdness.
    return if ( !-d "/etc/xen" );

    #
    #  Temporary hash.
    #
    my %cfg;

    #
    # Read the configuration file.
    #
    open( CONFIG, "<", "/etc/xen/xend-config.sxp" ) or
      fail("Failed to read /etc/xen/xend-config.sxp: $!");
    while (<CONFIG>)
    {
        next if ( !$_ || !length($_) );

        # vif
        if ( $_ =~ /^\(vif-script ([^)]+)/ )
        {
            $cfg{ 'vif-script' } = $1;
        }

        # network
        if ( $_ =~ /^\(network-script ([^)]+)/ )
        {
            $cfg{ 'network-script' } = $1;
        }
    }
    close(CONFIG);

    if ( !defined( $cfg{ 'network-script' } ) ||
         !defined( $cfg{ 'vif-script' } ) )
    {
        print <<EOF;

WARNING
-------

  You appear to have a missing vif-script, or network-script, in the
 Xen configuration file /etc/xen/xend-config.sxp.

  Please fix this and restart Xend, or your guests will not be able
 to use any networking!

EOF
    }
    else
    {
        if ( ( $cfg{ 'network-script' } =~ /dummy/i ) ||
             ( $cfg{ 'vif-script' } =~ /dummy/i ) )
        {

            print <<EOF;
WARNING
-------

  You appear to have a "dummy" vif-script, or network-script, setting
 in the Xen configuration file /etc/xen/xend-config.sxp.

  Please fix this and restart Xend, or your guests will not be able to
 use any networking!

EOF
        }
    }
}



=begin doc

  Setup the default options we'd expect into our global configuration hash.

=end doc

=cut

sub setupDefaultOptions
{
    #
    #  This flag is set upon failure, after images have been created.
    #
    #  It is used so that we can automatically "rollback" upon failure.
    #
    $CONFIG{'FAIL'} = 0;

    #
    # Paths and files.
    #
    $CONFIG{ 'dir' }     = '';
    $CONFIG{ 'xm' }      = findXenToolstack();
    $CONFIG{ 'kernel' }  = '';
    $CONFIG{ 'modules' } = '';
    $CONFIG{ 'initrd' }  = '';
    $CONFIG{ 'serial_device' } = 'hvc0';
    $CONFIG{ 'disk_device' }   = 'xvda';

    #
    # Sizing options.
    #
    $CONFIG{ 'memory' } = '96Mb';
    $CONFIG{ 'size' }   = '2000Mb';
    $CONFIG{ 'swap' }   = '128M';
    $CONFIG{ 'cache' }  = 'yes';
    $CONFIG{ 'cachedir' }  = '/var/cache/apt/archives/';
    $CONFIG{ 'image' }  = 'sparse';
    $CONFIG{ 'vcpus' } = '1';

    #
    # Misc. options.
    #

    # Default distribution is Debian Stable
    $CONFIG{ 'dist' }          = 'stable';
    $CONFIG{ 'mirror' }        = '';

    # Initialize per distribution mirror defaults: Debian
    foreach my $debdist (qw(squeeze wheezy jessie sid testing oldstable stable unstable)) {
        $CONFIG{ 'mirror_'.$debdist } = 'http://http.debian.net/debian';
    }
    foreach my $debdist (qw(sarge etch lenny)) {
        $CONFIG{ 'mirror_'.$debdist } = 'http://http.debian.net/debian-archive/debian';
    }
    # Initialize per distribution mirror defaults: Ubuntu
    foreach my $ubuntudist (qw(lucid precise quantal raring saucy trusty)) {
        $CONFIG{ 'mirror_'.$ubuntudist } = 'http://archive.ubuntu.com/ubuntu';
    }
    foreach my $ubuntudist (qw(dapper edgy feisty gutsy hardy intrepid jaunty karmic maverick natty oneiric)) {
        $CONFIG{ 'mirror_'.$ubuntudist } = 'http://old-releases.ubuntu.com/ubuntu';
    }
    $CONFIG{ 'apt_proxy' }     = '';
    $CONFIG{ 'arch' }          =
        which('dpkg') ? `dpkg --print-architecture` : '';
    chomp($CONFIG{ 'arch' });
    $CONFIG{ 'fs' }            = 'ext3';
    $CONFIG{ 'force' }         = 0;
    $CONFIG{ 'no_xen_ok' }     = 0;
    $CONFIG{ 'install' }       = 1;
    $CONFIG{ 'hooks' }         = 1;
    $CONFIG{ 'partitions' }    = '';
    $CONFIG{ 'pid' }           = 0;
    $CONFIG{ 'template' }      = '';
    $CONFIG{ 'roledir' }       = '/etc/xen-tools/role.d';
    $CONFIG{ 'partitionsdir' } = '/etc/xen-tools/partitions.d';
    $CONFIG{ 'ipfile' }        = '/etc/xen-tools/ips.txt';
    $CONFIG{ 'output' }        = '/etc/xen';
    $CONFIG{ 'extension' }     = '.cfg';

    #
    #  Installation method defaults to "debootstrap" using
    #  "debootstrap" (instead of cdebootstrap).
    #
    $CONFIG{ 'install-method' } = 'debootstrap';
    $CONFIG{ 'debootstrap-cmd' } = '';

    #
    #  Default values for passwords
    #
    $CONFIG{ 'genpass' }     = 1;
    $CONFIG{ 'genpass_len' } = 8;
    $CONFIG{ 'password' }    = '';
    $CONFIG{ 'hash_method' } = 'sha256';

    #
    #  The program to run to create a filesystem.
    #
    # NOTE: These commands end in a trailing slash.  The last parameter is
    #       added as the loopback file/LVM volume to create the fs on....
    #
    # NOTE 2:  Each of these scripts will "force" the creation of a new
    #         filesystem, even if it exists.  This script must detect
    #         prior existance itself.
    #
    $CONFIG{ 'make_fs_ext2' }     = 'mkfs.ext2 -F';
    $CONFIG{ 'make_fs_ext3' }     = 'mkfs.ext3 -F';
    $CONFIG{ 'make_fs_ext4' }     = 'mkfs.ext4 -F';
    $CONFIG{ 'make_fs_xfs' }      = 'mkfs.xfs -f';
    $CONFIG{ 'make_fs_reiserfs' } = 'mkfs.reiserfs -f -q';
    $CONFIG{ 'make_fs_btrfs' }    = 'mkfs.btrfs';

    #
    #  Flags to pass to "mount" to mount our image.
    #
    #  NOTE: Kinda redundent and may go away since '-t auto' should do
    #        the right thing.
    #
    $CONFIG{ 'mount_fs_ext2' }     = '-t ext2';
    $CONFIG{ 'mount_fs_ext3' }     = '-t ext3';
    $CONFIG{ 'mount_fs_ext4' }     = '-t ext4';
    $CONFIG{ 'mount_fs_xfs' }      = '-t xfs';
    $CONFIG{ 'mount_fs_reiserfs' } = '-t reiserfs';
    $CONFIG{ 'mount_fs_btrfs' }    = '-t btrfs';

    #
    #  Network options.
    #
    $CONFIG{ 'nameserver' } = '';

}



=begin doc

  Validate options and do what is necessary with them.

=end doc

=cut

sub checkOption
{
    my ($option, $value) = @_;

    # Define argument types
    my %types = (
        integerWithSuffix => {
            check   => qr/^[0-9.]+[GM]B?$/i,
            message => "takes a suffixed (mb, MB, G, etc.) integer.\n",
        },
        distribution => {
            check   => sub { -d "/usr/share/xen-tools/$_[0].d" },
            message => "takes a distribution name " .
                       "(see /usr/share/xen-tools for valid values).\n",
        },
        imageType => {
            check   => qr/^sparse|full$/,
            message => "must be 'sparse' or 'full'.\n",
        },
        existingFile => {
            check   => sub { -e $_[0] },
            message => "must be an existing file.\n",
        },
        existingDir => {
            check   => sub { -d $_[0] },
            message => "must be an existing directory.\n",
        },
        serialDev => {
            check   => qr/^(?:\/dev\/)?(?:tty|[xh]vc)[0-9]+$/,
            message => "must be a serial device (tty[0-9]+, hvc[0-9]+ or xvc[0-9]+).\n",
        },
        diskDev => {
            check   => qr/^(?:\/dev\/)?(?:xvd|sd)[a-z]+$/,
            message => "must be a disk device (xvd[a-z]+, sd[a-z]+).\n",
        },
        ipv4 => {
            check   => sub { is_ipv4($_[0]) },
            message => "must be valid IPv4.\n",
        },
        ipv4_or_auto => {
            check   => sub { is_ipv4($_[0]) or $_[0] eq 'auto' },
            message => "must be valid IPv4 or the keyword 'auto'.\n",
        },
        hostname => {
            check   => sub { is_hostname($_[0]) },
            message => "must be a valid hostname.\n",
        },
        supportedFs => {
            check   => qr/^(ext[234]|xfs|reiserfs|btrfs)$/,
            message => "must be a supported filesystem (ext2, ext3, ext4, xfs, reiserfs or btrfs).\n",
        },
        yesNo => {
            check   => qr/^yes|no$/i,
            message => "must be 'yes' or 'no'.\n",
        },
        zeroOne => {
            check   => qr/^0|1$/i,
            message => "must be '0' or '1'.\n",
        },
        configFile => {
            check   => sub { -e $_[0] or -e "/etc/xen-tools/" . $_[0] },
            message => "must be an existing file.\n",
        },
        filename => {
            check   => qr/^[a-z0-9_.-]*$/,
            message => "must be a valid filename.\n",
        },
        mac => {
            check   => qr/^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/i,
            message => "must be a valid ethernet mac address.\n",
        },
        hashMethod => {
            check   => qr/^md5|sha256|sha512$/i,
            message => "must be md5, sha256 or sha512.\n",
        },
        uri => {
            check   => sub { is_uri($_[0]) },
            message => "must be an URI including the protocol\n",
        },
    );

    # Define what argument each option accepts.
    # Arguments for options not listed here will always be accepted.
    my %optionsTypes = (
        size          => 'integerWithSuffix',
        dist          => 'distribution',
        swap          => 'integerWithSuffix',
        image         => 'imageType',
        memory        => 'integerWithSuffix',
        maxmem        => 'integerWithSuffix',
        kernel        => 'existingFile',
        initrd        => 'existingFile',
        modules       => 'existingDir',
        serial_device => 'serialDev',
        disk_device   => 'diskDev',
        gateway       => 'ipv4',
        netmask       => 'ipv4', # This is dubious.
        broadcast     => 'ipv4',
        hostname      => 'hostname',
        nameserver    => 'ipv4',
        pointopoint   => 'ipv4',
        fs            => 'supportedFs',
        cache         => 'yesNo',
        cachedir      => 'existingDir',
        config        => 'configFile',
        install       => 'zeroOne',
        hooks         => 'zeroOne',
        roledir       => 'existingDir',
        template      => 'configFile',
        output        => 'existingDir',
        extension     => 'filename',
        mac           => 'mac',
        ip            => 'ipv4_or_auto',
        hash_method   => 'hashMethod',
        apt_proxy     => 'uri',
    );

    # If given option does not exists in optionsTypes,
    # we just copy it to %CONFIG.
    unless ( exists $optionsTypes{ $option } ) {
        $CONFIG{ $option } = $value;
    } else { # we validate it before copying
        my $type = $optionsTypes{ $option };

        # First, check if type exists
        fail("Type $type does not exist") unless exists $types{ $type };
        my $check = $types{ $type }{ 'check' };

        if (
            (ref $check eq 'Regexp' and $value =~ $check) or
            (ref $check eq 'CODE' and &$check( $value ) )
        ) {
            # Option did validate, copy it
            if ( $option eq "ip" )
            {
              push @{ $CONFIG{ $option } }, $value;
            } else {
              $CONFIG{ $option } = $value;
            }
        } else {
            # Option did _not_ validate
            fail("ERROR: '$option' argument " . $types{ $type }{ 'message' });
        }
    }
}

=begin doc

  Parse the command line arguments this script was given.

=end doc

=cut

my $HELP       = 0;
my $MANUAL     = 0;
my $DUMPCONFIG = 0;
my $VERSION    = 0;

sub parseCommandLineArguments
{
    #
    #  We record the installation method here because we want
    # to ensure that we allow the method supplied upon the command line
    # to overwrite the one we might have ready read from the configuration
    # file.
    #
    my %install;
    $install{ 'evms' }      = undef;
    $install{ 'dir' }       = undef;
    $install{ 'lvm' }       = undef;
    $install{ 'image-dev' } = undef;

    #
    #  Parse options.
    #
    if (
        !GetOptions(

            # Mandatory
            "dist=s", \&checkOption,

            # Size options.
            "size=s",   \&checkOption,
            "swap=s",   \&checkOption,
            "noswap",   \&checkOption,
            "image=s",  \&checkOption,
            "memory=s", \&checkOption,
            "maxmem=s", \&checkOption,
            "vcpus=i",  \&checkOption,

            # Locations
            "dir=s",       \$install{ 'dir' },
            "evms=s",      \$install{ 'evms' },
            "kernel=s",    \&checkOption,
            "initrd=s",    \&checkOption,
            "mirror=s",    \&checkOption,
            "apt_proxy=s", \&checkOption,
            "modules=s",   \&checkOption,
            "lvm=s",       \$install{ 'lvm' },
            "image-dev=s", \$install{ 'image-dev' },
            "swap-dev=s",  \$install{ 'swap-dev' },
            "serial_device=s", \&checkOption,
            "disk_device=s", \&checkOption,

            # Hosts options
            "nohosts",     \$CONFIG{ 'nohosts' },
            "copyhosts!",  \$CONFIG{ 'copyhosts' },
            # Deprecated legacy options for backwards compatibility
            "no-hosts",    \$CONFIG{ 'nohosts' },
            "copy-hosts!", \$CONFIG{ 'copyhosts' },

            # Networking options
            "dhcp!",        \$CONFIG{ 'dhcp' },
            "bridge=s",     \&checkOption,
            "gateway=s",    \&checkOption,
            "hostname=s",   \&checkOption,
            "ip=s@",        \&checkOption,
            "mac=s",        \&checkOption,
            "netmask=s",    \&checkOption,
            "broadcast=s",  \&checkOption,
            "nameserver=s", \&checkOption,
            "vifname=s",    \&checkOption,
            "p2p=s",        \&checkOption,

            # Exclusive
            #
            #  NOTE:  We set the local variable here, not the global.
            #
            "install-method=s",  \$CONFIG{ 'install-method' },
            "install-source=s",  \$CONFIG{ 'install-source' },
            "debootstrap-cmd=s", \$CONFIG{ 'debootstrap-cmd' },

            # Misc. options
            "accounts!",    \$CONFIG{ 'accounts' },
            "admins=s",     \&checkOption,
            "arch=s",       \&checkOption,
            "fs=s",         \&checkOption,
            "boot!",        \$CONFIG{ 'boot' },
            "cache=s",      \&checkOption,
            "cachedir=s",   \&checkOption,
            "config=s",     \&checkOption,
            "ide",          \$CONFIG{ 'ide' },
            "scsi",         \$CONFIG{ 'scsi' },
            "install=i",    \&checkOption,
            "hooks=i",      \&checkOption,
            "pygrub!",      \$CONFIG{ 'pygrub' },
            "passwd!",      \$CONFIG{ 'passwd' },
            "genpass=i",    \&checkOption,
            "genpass-len=i", \&checkOption,
            "genpass_len=i", \&checkOption,
            "password=s",   \&checkOption,
            "hash_method=s",\&checkOption,
            "partitions=s", \&checkOption,
            "role=s",       \&checkOption,
            "role-args=s",  \&checkOption,
            "finalrole=s",       \&checkOption,
            "roledir=s",    \&checkOption,
            "force!",       \$CONFIG{ 'force' },
            "no-xen-ok",    \$CONFIG{ 'no_xen_ok' },
            "keep!",        \$CONFIG{ 'keep' },
            "template=s",   \&checkOption,
            "output=s",     \&checkOption,
            "extension:s",  \&checkOption,
            "dontformat",   \&checkOption,

            # Help options
            "debug!",     \$CONFIG{ 'debug' },
            "help",       \$HELP,
            "manual",     \$MANUAL,
            "dumpconfig", \$DUMPCONFIG,
            "verbose!",   \$CONFIG{ 'verbose' },
            "version",    \$VERSION
        ) )
    {
        $CONFIG{'FAIL'} = 2;
        exit;
    }

    if ( $HELP ) {
        $CONFIG{'FAIL'}=-1;
        pod2usage(1);
    }

    if ( $MANUAL ) {
        $CONFIG{'FAIL'}=-1;
        pod2usage( -verbose => 2 );
    }

    if ($VERSION)
    {
        logprint("xen-create-image release $RELEASE\n");
        exit 0;
    }


    #
    #  Now make ensure that the command line setting of '--lvm', '--evms'
    # and '--dir=x' override anything specified in the configuration file.
    #
    if ( $install{ 'dir' } )
    {
        $CONFIG{ 'dir' }       = $install{ 'dir' };
        $CONFIG{ 'evms' }      = undef;
        $CONFIG{ 'lvm' }       = undef;
        $CONFIG{ 'image-dev' } = undef;
    }
    if ( $install{ 'evms' } )
    {
        $CONFIG{ 'dir' }       = undef;
        $CONFIG{ 'evms' }      = $install{ 'evms' };
        $CONFIG{ 'lvm' }       = undef;
        $CONFIG{ 'image-dev' } = undef;
    }
    if ( $install{ 'lvm' } )
    {
        $CONFIG{ 'dir' }       = undef;
        $CONFIG{ 'evms' }      = undef;
        $CONFIG{ 'lvm' }       = $install{ 'lvm' };
        $CONFIG{ 'image-dev' } = undef;
    }
    if ( $install{ 'image-dev' } )
    {
        $CONFIG{ 'dir' }       = undef;
        $CONFIG{ 'evms' }      = undef;
        $CONFIG{ 'lvm' }       = undef;
        $CONFIG{ 'image-dev' } = $install{ 'image-dev' };
        $CONFIG{ 'size' }      = undef;
        $CONFIG{ 'swap' }      = undef;

        $CONFIG{ 'swap-dev' } = $install{ 'swap-dev' }
          if ( defined( $install{ 'swap-dev' } ) );
    }

    if ($DUMPCONFIG)
    {
        print Dumper \%CONFIG;
        exit 0;
    }
}



=begin doc

  Make sure this script is being run by a user with UID 0.

=end doc

=cut

sub testRootUser
{
    if ( $EFFECTIVE_USER_ID != 0 )
    {
        my $err = <<E_O_ROOT;

  In order to use this script you must be running with root privileges.

  (This is necessary to mount the disk images which are created.)

E_O_ROOT

        logprint($err);
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }
}



=begin doc

  Test that the command line arguments we were given make sense.

  Here we make sure that mutually exclusive options are not selected
 for the installation method, etc.

  We also warn when some variables are not set.

=end doc

=cut

sub checkArguments
{

    #
    #  We require a distribution name.
    #
    if ( !defined( $CONFIG{ 'dist' } ) )
    {
        logprint("The '--dist' argument is mandatory\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    #
    #  We require a hostname.
    #
    if ( !defined( $CONFIG{ 'hostname' } ) )
    {
        logprint("The '--hostname' argument is mandatory.\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    #
    #  Lucid and probably all later Ubuntus, too, don't work without pygrub
    #
    if ( $CONFIG{ 'dist' } =~ /lucid|maverick|natty|oneiric|precise|quantal|raring|saucy/ )
    {
        $CONFIG{ 'pygrub' } = 1;
    }

    #
    #  Sarge amd64 needs different default mirror
    #
    if ( $CONFIG{ 'dist' } =~ /sarge/ and
         $CONFIG{ 'arch' } =~ /amd64/ and
         $CONFIG{ 'mirror_sarge' } =~ m(/debian-archive/debian/?$))
    {
        $CONFIG{ 'mirror_sarge' } =~
            s(/debian-archive/debian/?)(/debian-archive/debian-amd64);
    }

    #
    #  If no mirror is set, use the default per-distro mirror
    #
    my $distMirror = "mirror_" . $CONFIG{ 'dist' };
    if ( !$CONFIG{ 'mirror' } and
         $CONFIG{ $distMirror } and
         length( $CONFIG{ $distMirror } ) )
    {
        $CONFIG{ 'mirror' } = $CONFIG{ $distMirror };
    }

    #
    #  NOTE: FAKE!
    #
    if ( $CONFIG{ 'dist' } eq 'fedora-core4' )
    {
        $CONFIG{ 'dist' } = 'stentz';
    }

    #
    #  If using LVM or EVMS then the images may not be sparse
    #
    $CONFIG{ 'image' } = "full"
      if ( $CONFIG{ 'lvm' } ||
           $CONFIG{ 'evms' } ||
           $CONFIG{ 'image-dev' } );



    #
    #  Make sure that our installation method is specified.
    #
    my $valid = 0;
    if ( defined( $CONFIG{ 'install-method' } ) )
    {
        foreach my $recognised (
                        qw/ copy debootstrap cdebootstrap rinse rpmstrap tar /)
        {
            $valid = 1
              if ( lc( $CONFIG{ 'install-method' } ) eq lc($recognised) );
        }

        #
        #  If we have "cdebootstrap", set it to "debootstrap" and set
        #  debootstrap-cmd to cdebootstrap instead.
        #
        if ( lc( $CONFIG{ 'install-method' } ) eq 'cdebootstrap' )
        {
            $CONFIG{ 'install-method' } = 'debootstrap';
            $CONFIG{ 'debootstrap-cmd' } = 'cdebootstrap';
        }

        #
        #  If we have "copy", or "tar" method then make sure we have a source.
        #
        if ( ( lc( $CONFIG{ 'install-method' } ) eq "copy" ) ||
             ( lc( $CONFIG{ 'install-method' } ) eq "tar" ) )
        {

            # not defined.
            $valid = 0 if ( !defined( $CONFIG{ 'install-source' } ) );
        }
    }
    else
    {
        $valid = 1;
    }

    if ( !$valid )
    {
        print <<EOF;
  Please specify the installation method to use, along with a source
 if that is required.

  For example:

     --install-method=copy        --install-source=/some/path
     --install-method=debootstrap
     --install-method=rinse
     --install-method=rpmstrap
     --install-method=tar         --install-source=/some/file.tar

EOF
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }


    #
    #  Make sure that any specified template file exists.
    #
    if ( defined( $CONFIG{ 'template' } ) &&
         length( $CONFIG{ 'template' } ) )
    {
        if ( -e $CONFIG{ 'template' } )
        {

            # nop
        }
        elsif ( -e "/etc/xen-tools/$CONFIG{'template'}" )
        {
            $CONFIG{ 'template' } = "/etc/xen-tools/$CONFIG{'template'}";
        }
        else
        {

            # failed to find either by fully qualified path,
            # or inside /etc/xen-tools.
            logprint(
                "The specified template file, $CONFIG{'template'}, does not exist.\n"
            );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }


    #
    #  If we've got a role directory specified then it must exist.
    #
    if ( defined( $CONFIG{ 'roledir' } ) && length( $CONFIG{ 'roledir' } ) )
    {
        if ( !-d $CONFIG{ 'roledir' } )
        {
            logprint(
                "The specified role directory '$CONFIG{'roledir'}' does not exist\n"
            );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }


    #
    #  If we've got a partitions directory specified then it must exist.
    #
    if ( defined( $CONFIG{ 'partitionsdir' } ) &&
         length( $CONFIG{ 'partitionsdir' } ) )
    {
        if ( !-d $CONFIG{ 'partitionsdir' } )
        {
            logprint(
                "The specified partitions directory '$CONFIG{'partitionsdir'}' does not exist\n"
            );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }


    #
    #  Make sure that any specified partitions file exists.
    #
    if ( ( defined( $CONFIG{ 'partitions' } ) ) &&
         ( length( $CONFIG{ 'partitions' } ) ) )
    {
        if ( !( $CONFIG{ 'partitions' } =~ /\// ) )
        {
            $CONFIG{ 'partitions' } =
              $CONFIG{ 'partitionsdir' } . '/' . $CONFIG{ 'partitions' };
        }

        if ( !-e $CONFIG{ 'partitions' } )
        {
            logprint(
                "The specified partitions file, $CONFIG{'partitions'}, does not exist.\n"
            );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }

        loadAndCheckPartitionsFile();
    }

    if ( $CONFIG{ 'swap-dev' } && $CONFIG{ 'noswap' } )
    {
        logprint("Please choose either swap-dev or noswap, not both!\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    if ( $CONFIG{ 'swap-dev' } && $CONFIG{ 'partitions' } )
    {
        logprint("Please choose either swap-dev or partitions, not both!\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    if ( $CONFIG{ 'image-dev' } )
    {
        if ( $CONFIG{ 'partitions' } )
        {
            logprint("Please choose either image-dev or partitions, not both!\n");
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }

        if ( !$CONFIG{ 'swap-dev' } && !$CONFIG{ 'noswap' } )
        {
            logprint("Please choose swap-dev or noswap with image-dev!\n");
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }


    #
    #  The user must choose either DHCP *or* Static IP.  not both
    #
    if ( $CONFIG{ 'dhcp' } && $CONFIG{ 'ip' } )
    {

        #
        #  However we will allow the DHCP setting to override a *partially*
        # specified IP address.
        #
        if ( $CONFIG{ 'ip' } =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)\.*$/ )
        {
            delete $CONFIG{ 'ip' };
        }
        else
        {
            logprint("Please choose either DHCP or static usage, not both!\n");
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }

    #
    #  The user must specify one or the other.
    #
    if ( ( !$CONFIG{ 'dhcp' } ) && ( !$CONFIG{ 'ip' } ) )
    {
        logprint("Please choose one of:\n");
        logprint(" --dhcp\n");
        logprint(" --ip xx.xx.xx.xx\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    #
    #  If we're using static addresses warn if there are variables
    # missing
    #
    if ( $CONFIG{ 'ip' } )
    {
        logprint("WARNING:  No gateway address specified!\n")
          unless ( defined( $CONFIG{ 'gateway' } ) );

        logprint("WARNING:  No netmask address specified!\n")
          unless ( defined( $CONFIG{ 'netmask' } ) );
    }

    #
    #  If we don't have a MAC address specified then generate one.
    #
    if ( !$CONFIG{ 'mac' } )
    {
        $CONFIG{ 'mac' } = generateMACAddress();
    }

    #
    #  Make sure our output directory exists.
    #
    if ( !-d $CONFIG{ 'output' } )
    {
        print <<EOF;
  The output directory for creating the xen configuration file within
 doesn\'t exist:

           $CONFIG{ 'output' }

  Aborting.

EOF
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    #
    #  Already present?
    #
    my $cfg =
      $CONFIG{ 'output' } . "/" . $CONFIG{ 'hostname' } .
      $CONFIG{ 'extension' };
    if ( -e $cfg )
    {
        if ( $CONFIG{ 'force' } )
        {
            $CONFIG{ 'verbose' } && print "Removing existing file: $cfg\n";
            unlink($cfg);
        }
        else
        {
            print "Configuration file already exists; $cfg\n";
            print "Aborting\n";
            $CONFIG{'FAIL'} = 2;
            exit 127;
        }
    }

}



=begin doc

  Generate a 'random' MAC address.

  The MAC address is constructed based upon :

   1.  The standard Xen prefix.

   2.  The hostname + IP address of the new guest.

   3.  The distribution which is to be installed.

=end doc

=cut

sub generateMACAddress
{

    #
    #  Start with the xen prefix
    #
    my $mac = '00:16:3E';

    #
    #  Build up ( hostname + ip + dhcp + dist );
    #
    my $hash = '';
    foreach my $key (qw/ hostname ip dhcp dist /)
    {
        if ( $CONFIG{ $key } ) {
            if (ref($CONFIG{ $key }) eq 'ARRAY') {
                $hash .= join(',',@{$CONFIG{ $key }});
            } elsif (ref($CONFIG{ $key }) eq 'HASH') {
                $hash .= join(',',values %{$CONFIG{ $key }});
            } else {
                $hash .= $CONFIG{ $key };
            }
        }
    }

    #
    #  Generate an MD5 hash of this data.
    #
    $hash = md5_hex($hash);

    #
    #  Now build up a MAC address
    #
    while ( length($mac) < 17 )
    {
        $mac .= ":" . substr( $hash, 0, 2 );
        $hash = substr( $hash, 2 );
    }

    return ( uc($mac) );
}



=begin doc

  Make sure we have a log directory, and create an empty logfile
 for this run.

=end doc

=cut

sub setupLogFile
{

    mkdir( "/var/log/xen-tools", 0750 ) if ( !-d "/var/log/xen-tools" );

    #
    #  Move any existing for this run logfile.
    #  (Hint: read from the end to understand how this works).
    #
    my $logname = "/var/log/xen-tools/$CONFIG{'hostname'}.log";
    map {
        (my $new = $_) =~ s/(?<=\.)\d+(?=\.log$)/$& + 1/e;
        mv $_, $new; # increment file number
    } sort {
        $a =~ /\.(\d+)\.log$/;
        my $aa = $1;
        $b =~ /\.(\d+)\.log$/;
        my $bb = $1;
        $bb <=> $aa; # sort in reverse order
    } grep /\.\d+\.log$/, # we only care in numeric filenames
    glob( "/var/log/xen-tools/$CONFIG{'hostname'}.*.log" );

    # Move the non-numeric filename also
    mv $logname, "/var/log/xen-tools/$CONFIG{'hostname'}.0.log"
        if -f $logname;

    #
    #  Now create an empty file.
    #
    open STUB, '>', $logname;
    close STUB;

    #
    #  Make sure the logfile is 0640 - avoid leaking root passwords.
    #
    chmod( oct("0640"), $logname );
}



=begin doc

  Check that we have some required binaries present.

=end doc

=cut

sub checkBinariesPresent
{

    #
    #  Files we demand are present in all cases.
    #
    my @required = qw ( mount mkswap );

    foreach my $file (@required)
    {
        if ( !defined( which($file) ) )
        {
            logprint("The following binary is required to run this tool\n");
            logprint("\t$file\n");
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }

    #
    # Image type specific binaries
    #
    if ( defined( $CONFIG{ 'dir' } ) )
    {

        # loopback image
        if ( !defined( which("dd") ) )
        {
            logprint("The following binary is required to run this tool\n");
            logprint("\tdd\n");
            logprint(
                "(This only required for loopback images, which you've selected)\n"
            );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }
    elsif ( defined( $CONFIG{ 'evms' } ) )
    {

        #
        # EVMS-specific binaries.
        #
        my @evms = qw ( evms echo );

        foreach my $file (@evms)
        {
            if ( !defined( which($file) ) )
            {
                logprint("The following binary is required to run this tool\n");
                logprint("\t$file\n");
                logprint(
                    "(This is only required for EVMS volumes, which you've selected)\n"
                );
                $CONFIG{'FAIL'} = 1;
                exit 127;
            }
        }
    }
    elsif (defined( $CONFIG{ 'lvm' } ) )
    {

        # LVM-specific binaries.
        my @lvm = qw ( lvcreate lvremove );

        foreach my $file (@lvm)
        {
            if ( !defined( which($file) ) )
            {
                logprint("The following binary is required to run this tool\n");
                logprint("\t$file\n");
                logprint(
                    "(This is only required for LVM volumes, which you've selected)\n"
                );
                $CONFIG{'FAIL'} = 1;
                exit 127;
            }
        }
    }
}



=begin doc

  Loads a partitions file, checks the syntax and updates the configuration
 variables with it

=end doc

=cut

sub loadAndCheckPartitionsFile
{
    my %partitions;

    #
    #  Here we'll test for the required Perl module.
    #
    #  This allows us to:
    #
    #  a) Degrade usefully if the module isn't available.
    #
    #  b) Not require the module unless the user specifies a custom
    #     partitioning scheme.
    #
    my $test = "use Config::IniFiles";
    eval($test);
    if ($@)
    {
        print <<EOF;

 Aborting - To use the custom partitioning code you need to have the
 following Perl module installed:

   Config::IniFiles

 On a Debian system you can get this with:

   apt-get install libconfig-inifiles-perl

 Otherwise fetch it from CPAN.
EOF
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    tie %partitions, 'Config::IniFiles', ( -file => $CONFIG{ 'partitions' } );

    @PARTITIONS = ();

    my $name;
    my $details;
    my $foundroot = 0;
    while ( ( $name, $details ) = each %partitions )
    {
        if ( !( $name =~ /^[a-zA-Z0-9-]+$/ ) )
        {
            logprint("The partition name $name contains invalid characters.\n");
            logprint(
                   "Only alphanumeric characters and the hyphen are allowed\n");
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }

        if ( !( $details->{ 'size' } =~ /^[0-9.]+[GgMmKk]b?$/ ) )
        {
            logprint(
                "The size $details->{'size'} of partition $name contains is not recognized.\n"
            );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }

        if ( $details->{ 'type' } eq 'swap' )
        {
            push( @PARTITIONS,
                  {  'name'       => $name,
                     'size'       => $details->{ 'size' },
                     'type'       => 'swap',
                     'mountpoint' => '',
                     'options'    => ''
                  } );
        }
        else
        {
            if ( !$CONFIG{ 'make_fs_' . $details->{ 'type' } } )
            {
                logprint(
                    "The type $details->{'type'} of partition $name is not recognized.\n"
                );
                $CONFIG{'FAIL'} = 1;
                exit 127;
            }

            if ( !( $details->{ 'mountpoint' } =~ /^\/[^: \t\r\n]*$/ ) )
            {
                logprint(
                    "The mount point $details->{'mountpoint'} of partition $name is invalid.\n"
                );
                $CONFIG{'FAIL'} = 1;
                exit 127;
            }

            if ( !( $details->{ 'options' } =~ /^[^: \t\r\n]*$/ ) )
            {
                logprint(
                    "The mount options $details->{'options'} of partition $name are invalid.\n"
                );
                $CONFIG{'FAIL'} = 1;
                exit 127;
            }

            if ( !$details->{ 'options' } )
            {
                $details->{ 'options' } = 'defaults';
            }

            if ( $details->{ 'mountpoint' } eq '/' )
            {
                $foundroot = 1;
            }

            push( @PARTITIONS,
                  {  'name'       => $name,
                     'size'       => $details->{ 'size' },
                     'type'       => $details->{ 'type' },
                     'mountpoint' => $details->{ 'mountpoint' },
                     'options'    => $details->{ 'options' } } );
        }
    }

    if ( !$foundroot )
    {
        logprint("The root partition was not specified.\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    #
    # Sort by length of the mountpoint.
    #
    #  This makes it easy to mount parent folders first
    # (e.g. /var before /var/tmp)
    #
    @PARTITIONS =
      sort {length $a->{ 'mountpoint' } <=> length $b->{ 'mountpoint' }}
      @PARTITIONS;
}



=begin doc

  Populates the partition information using the supplied configuration
 arguments when not using the partitions file

=end doc

=cut

sub populatePartitionsData
{
    @PARTITIONS = ();

    #
    #  [swap]
    #
    push( @PARTITIONS,
          {  'name'       => 'swap',
             'size'       => $CONFIG{ 'swap' },
             'type'       => 'swap',
             'mountpoint' => '',
             'options'    => ''
          } ) unless ( $CONFIG{ 'noswap' } );

    #
    #  read the default filesystem options from the configuration file.
    #
    my $options = $CONFIG{ $CONFIG{ 'fs' } . "_options" } || undef;

    #
    #  If there weren't any options in the configuration file then
    # revert to our defaults.
    #
    if ( !defined($options) )
    {

        #
        #  XFS has different default options.
        #
        $options = "errors=remount-ro";
        $options = "defaults" if ( $CONFIG{ 'fs' } eq "xfs" );
    }


    #
    #  [root]
    #
    push( @PARTITIONS,
          {  'name'       => 'disk',
             'size'       => $CONFIG{ 'size' },
             'type'       => $CONFIG{ 'fs' },
             'mountpoint' => '/',
             'options'    => $options
          } );

}



=begin doc

  Converts the internal partitions array into a text representation
 suitable for passing to other scripts.

=end doc

=cut

sub exportPartitionsToConfig
{
    $CONFIG{ 'NUMPARTITIONS' } = $#PARTITIONS + 1;

    my $i;
    for ( $i = 0 ; $i < $CONFIG{ 'NUMPARTITIONS' } ; $i++ )
    {
        $CONFIG{ 'PARTITION' . ( $i + 1 ) } =
          $PARTITIONS[$i]{ 'name' } . ':' . $PARTITIONS[$i]{ 'size' } . ':' .
          $PARTITIONS[$i]{ 'type' } . ':' . $PARTITIONS[$i]{ 'mountpoint' } .
          ':' . $PARTITIONS[$i]{ 'options' } . ':' .
          $PARTITIONS[$i]{ 'imagetype' } . ':' . $PARTITIONS[$i]{ 'image' };
    }
}



=begin doc

  Show the user a summary of what is going to be created for them

=end doc

=cut

sub showSummary
{

    #
    # Show the user what to expect.
    #
    logprint("\nGeneral Information\n");
    logprint("--------------------\n");
    logprint("Hostname       :  $CONFIG{'hostname'}\n");
    logprint("Distribution   :  $CONFIG{'dist'}\n");
    logprint("Mirror         :  $CONFIG{'mirror'}\n");

    if ( defined $CONFIG{ 'image-dev' } )
    {
        logprint("Root Device    :  $CONFIG{'image-dev'}\n");
    }
    if ( defined $CONFIG{ 'swap-dev' } )
    {
        logprint("Swap Device    :  $CONFIG{'swap-dev'}\n");
    }

    my $info;
    my $partcount = 0;

    logprint("Partitions     :  ");
    foreach my $partition (@PARTITIONS)
    {
        next if ( !$partition );
        $info = sprintf( '%-15s %-5s (%s)',
                         ( $partition->{ 'type' } ne 'swap' ) ?
                           $partition->{ 'mountpoint' } :
                           'swap',
                         $partition->{ 'size' },
                         $partition->{ 'type' } );

        if ( $partcount++ )
        {
            logprint("                  $info\n");
        }
        else
        {
            logprint("$info\n");
        }
    }

    logprint("Image type     :  $CONFIG{'image'}\n");
    logprint("Memory size    :  $CONFIG{'memory'}\n");

    if ( defined( $CONFIG{ 'maxmem' } ) )
    {
        logprint("Max mem size   : $CONFIG{'maxmem'}\n");
    }

    if ( defined( $CONFIG{ 'kernel' } ) && length( $CONFIG{ 'kernel' } ) )
    {
        logprint("Kernel path    :  $CONFIG{'kernel'}\n");
    }

    if ( defined( $CONFIG{ 'modules' } ) && length( $CONFIG{ 'modules' } ) )
    {
        logprint("Module path    :  $CONFIG{'modules'}\n");
    }

    if ( defined( $CONFIG{ 'initrd' } ) && length( $CONFIG{ 'initrd' } ) )
    {
        logprint("Initrd path    :  $CONFIG{'initrd'}\n");
    }

    logprint("\nNetworking Information\n");
    logprint("----------------------\n");

    #
    # Show each IP address added.
    #
    # Note we only allow the first IP address to have a MAC address specified.
    #
    my $ips   = $CONFIG{ 'ip' };
    my $mac   = $CONFIG{ 'mac' };
    my $count = 1;

    if ( defined $ips )
    {

        #
        #  Scary magic.
        #
        if ( !UNIVERSAL::isa( $ips, "ARRAY" ) )
        {

            #
            #  If we're reading the value of "ip = xxx" from the configuration
            # file we'll have a single (scalar) value in $CONFIG{'ip'}.
            #
            #  BUT we actually assume this hash element contains a reference
            # to an array - since that is what the command-line parsing code
            # sets up for us.
            #
            #  So here we fake it - that was what the test above as for,
            # if we didn't have an array already, then fake one up.
            #
            #  We reset the $ips reference to undef, then coerce it to be an
            # (empty) array and push on our single IP.
            #
            #  It works.   Even if it's nasty, (or if it is a clever hack!)
            #
            $ips = undef;
            push( @$ips, $CONFIG{ 'ip' } );
            $CONFIG{ 'ip' } = $ips;
        }
    }


    if ( defined $ips )
    {

        #
        #  Print out each network address, and if there is a mac address
        # associated with it then use it too.
        #
        foreach my $i (@$ips)
        {
            my $m = undef;

            if ( ( $count == 1 ) && ( defined($mac) ) )
            {
                $m = $mac;
            }


            #
            #  Here we have special handling for the case where
            # IP addresses to be generated automatically.
            #
            #
            if ( $i =~ /auto/i )
            {
                $CONFIG{ 'verbose' } &&
                  logprint("Automatically determining an IP.");

                $i = findIP($i);
                if ( defined($i) )
                {
                    $CONFIG{ 'verbose' } && logprint("Claimed $i\n");
                }
                else
                {
                    print <<EOF;

ERROR:  You specified the automatic choosing of an IP address and
        none are left in $CONFIG{'ipfile'}.

EOF
                    $CONFIG{'FAIL'} = 1;
                    exit 127;
                }
            }

            #
            #  Show the IP address.
            #
            logprint("IP Address $count   : $i");

            #
            #  Log the ip addresses for later output
            #
            $IP_ADDRESSES .= "$i ";

            #  Option MAC address.
            if ( defined($m) )
            {
                logprint(" [MAC: $m]");
            }
            logprint("\n");

            $count += 1;
        }
    }

    #
    # mac address setting still works even for DHCP, but in that
    # case only the first one works.
    #
    if ( $CONFIG{ 'dhcp' } )
    {
        if ( defined( $CONFIG{ 'mac' } ) )
        {
            logprint("IP Address     : DHCP [MAC: $CONFIG{'mac'}]\n");
        }
        else
        {
            logprint("IP Address     : DHCP\n");
        }
    }

    $CONFIG{ 'netmask' } && logprint("Netmask        : $CONFIG{'netmask'}\n");
    $CONFIG{ 'broadcast' } &&
      logprint("Broadcast      : $CONFIG{'broadcast'}\n");
    $CONFIG{ 'gateway' } && logprint("Gateway        : $CONFIG{'gateway'}\n");
    $CONFIG{ 'nameserver' } && logprint("Nameserver     : $CONFIG{'nameserver'}\n");
    $CONFIG{ 'p2p' }     && logprint("Point to Point : $CONFIG{'p2p'}\n");
    print "\n";

}



=begin doc

  Test that the user has the "loop" module loaded and present,
 this is just a warning useful to newcomers.

=end doc

=cut

sub testLoopbackModule
{
    if ( -e "/proc/modules" )
    {
        my $modules = `cat /proc/modules`;

        if ( $modules !~ m/loop/ )
        {
            logprint("WARNING\n");
            logprint("-------\n");
            logprint(
                 "Loopback module not loaded and you're using loopback images\n"
            );
            logprint("Run the following to load the module:\n\n");
            logprint("modprobe loop max_loop=255\n\n");
        }
    }
}



=begin doc

  Create the two images "swap.img" and "disk.img" in the directory
 we've been given.

  We also will call the filesystem creation routine to make sure we
 have a valid filesystem.

=end doc

=cut

sub createLoopbackImages
{

    #
    #  Make sure we have the relevant output directory.
    #
    my $output = $CONFIG{ 'dir' } . "/domains/" . $CONFIG{ 'hostname' };

    if ( !-d $output )
    {

        #
        #  Catch errors with eval.
        #
        eval {mkpath( $output, 0, 0755 );};
        if ($@)
        {
            fail("Cannot create directory tree $output - $@");
        }
    }


    #
    # Only proceed overwritting if we have --force specified.
    #
    if ( !$CONFIG{ 'force' } )
    {
        foreach my $partition (@PARTITIONS)
        {
            my $disk =
              $CONFIG{ 'dir' } . '/domains/' . $CONFIG{ 'hostname' } . '/' .
              $partition->{ 'name' } . '.img';

            if ( -e $disk )
            {
                logprint("The partition image already exists.  Aborting.\n");
                logprint(
                    "Specify '--force' to overwrite, or remove the following file\n"
                );
                logprint( $disk . "\n" );
                $CONFIG{'FAIL'} = 2;
                exit 127;
            }
        }
    }


    foreach my $partition (@PARTITIONS)
    {
        my $disk =
          $CONFIG{ 'dir' } . '/domains/' . $CONFIG{ 'hostname' } . '/' .
          $partition->{ 'name' } . '.img';

        #
        # Save the image path to the partitions array
        #
        $partition->{ 'imagetype' } = 'file:';
        $partition->{ 'image' }     = $disk;

        #
        # Modify the size to something reasonable
        #
        my $size = $partition->{ 'size' };

        #
        # Convert Gb -> Mb for the partition image size.
        #
        if ( $size =~ /^([0-9.]+)Gb*$/i )
        {
            $size = $1 * 1024 . "M";
        }

        #
        #  Final adjustments to sizing.
        #
        $size =~ s/Mb*$/k/i;

        #
        #  Use dd to create the partition image.
        #
        logprint("\nCreating partition image: $disk\n");
        my $image_cmd;
        if ( $CONFIG{ 'image' } eq "sparse" )
        {
            $CONFIG{ 'verbose' } && logprint("Creating sparse image\n");
            $image_cmd = "dd if=/dev/zero of=$disk bs=$size count=0 seek=1024";
        }
        else
        {
            $CONFIG{ 'verbose' } && logprint("Creating full-sized image\n");
            $image_cmd = "dd if=/dev/zero of=$disk bs=$size count=1024";
        }

        # Set the umask so that the images are not world readable.
        my $oldumask = umask;
        umask(0077);

        # run the image creation command
        runCommand($image_cmd, \%CONFIG);
        logprint("Done\n");

        # Reset the umask to the previous value
        umask($oldumask);

        if ( !-e $disk )
        {
            logprint("The partition image creation failed to create $disk.\n");
            logprint("aborting\n");
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }

        #
        #  Finally create the filesystem / swap
        #
        if ( $partition->{ 'type' } eq 'swap' )
        {
            createSwap($disk);
        }
        else
        {
            createFilesystem( $disk, $partition->{ 'type' } );
        }
    }
}



=begin doc

  This function is used if you want your new system be installed to a
 physical drive (e.g. partition /dev/hda4) or to an already existing
 logical volume (e.g. /dev/root_vg/xen_root_lv).

 Walter Reiner

=end doc

=cut

sub usePhysicalDevice
{
    my $phys_img;
    my $swap_img;

    @PARTITIONS = ();

    if ( defined $CONFIG{ 'swap-dev' } )
    {
        $swap_img = $CONFIG{ 'swap-dev' };

        if ( !-e $swap_img )
        {
            logprint(
                "The physical device or logical volume for swap-dev $swap_img doesn't exist.  Aborting.\n"
            );
            logprint(
                "NOTE: Please provide full path to your physical device or logical volume.\n"
            );
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }

        push( @PARTITIONS,
              {  'name'       => 'swap',
                 'size'       => '',
                 'type'       => 'swap',
                 'mountpoint' => '',
                 'options'    => '',
                 'imagetype'  => 'phy:',
                 'image'      => $swap_img
              } ) unless ( $CONFIG{ 'noswap' } );
    }

    my $options = 'errors=remount-ro';
    if ( $CONFIG{ 'fs' } eq 'xfs' )
    {
        $options = 'defaults';
    }

    if ( defined $CONFIG{ 'image-dev' } )
    {
        $phys_img = $CONFIG{ 'image-dev' };

        push( @PARTITIONS,
              {  'name'       => 'disk',
                 'size'       => '',
                 'type'       => $CONFIG{ 'fs' },
                 'mountpoint' => '/',
                 'options'    => $options,
                 'imagetype'  => 'phy:',
                 'image'      => $phys_img
              } );
    }
    else
    {
        logprint("No image-dev parameter given.  Aborting.\n");
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    createFilesystem( $phys_img, $CONFIG{ 'fs' } );
    createSwap($swap_img) unless ( $CONFIG{ 'noswap' } );
}



=begin doc

  This function is responsible for creating two new logical volumes within
 a given LVM volume group.

=end doc

=cut

sub createLVMBits
{

    #
    #  Check whether the disk volume exists already, and if so abort
    #  unless '--force' is specified.
    #
    foreach my $partition (@PARTITIONS)
    {
        my $disk     = $CONFIG{ 'hostname' } . '-' . $partition->{ 'name' };
        my $lvm_disk = "/dev/$CONFIG{'lvm'}/$disk";

        if ( -e $lvm_disk )
        {

            # Delete if forcing
            if ( $CONFIG{ 'force' } )
            {
                if ( $CONFIG{ 'no_xen_ok' } or
                     !xenRunning($CONFIG{ 'hostname' }, \%CONFIG)) {
                    logprint(
                        "Removing $lvm_disk - since we're forcing the install\n");
                    runCommand("lvremove --force $lvm_disk", \%CONFIG);
                } else {
                    fail("ERROR: Xen guest $CONFIG{'hostname'} appears to be running.\nAborting.\n");
                }
            }
            else
            {
                logprint("The LVM disk image already exists.  Aborting.\n");
                logprint("Specify '--force' to delete and recreate\n");
                $CONFIG{'FAIL'} = 2;
                exit 127;
            }
        }
    }

    foreach my $partition (@PARTITIONS)
    {
        my $disk     = $CONFIG{ 'hostname' } . '-' . $partition->{ 'name' };
        my $lvm_disk = "/dev/$CONFIG{'lvm'}/$disk";

        #
        # Save the image path to the partitions array
        #
        $partition->{ 'imagetype' } = 'phy:';
        $partition->{ 'image' }     = $lvm_disk;

        #
        # The commands to create the volume.
        #
        my $disk_cmd =
          "lvcreate $CONFIG{'lvm'} -L $partition->{'size'} -n $disk";

        #
        # Create the volume
        #
        runCommand($disk_cmd, \%CONFIG);

        #
        # Make sure that worked.
        #
        if ( !-e $lvm_disk )
        {
            logprint(
                "The LVM partition image creation failed to create $lvm_disk.\n"
            );
            logprint("aborting\n");
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }

        #
        #  Finally create the filesystem / swap
        #
        if ( $partition->{ 'type' } eq 'swap' )
        {
            createSwap($lvm_disk);
        }
        else
        {
            createFilesystem( $lvm_disk, $partition->{ 'type' } );
        }
    }

}



=begin doc

  This function is responsible for creating two new logical volumes within
 a given EVMS container group (which at the moment is either LVM or LVM2), but
 should be compatible with any further extentions of evms.

=end doc

=cut

sub createEVMSBits
{

    #
    #  Check whether the disk volume exists already, and if so abort
    #  unless '--force' is specified.  This is two steps with evms,
    #  because two things need to be checked, the volume and the object.
    #

    foreach my $partition (@PARTITIONS)
    {

        # Check whether the EVMS volume already exists, abort unless '--force' is specified.
        my $evms_volume_disk =
          "/dev/evms/$CONFIG{'hostname'}-$partition->{'name'}";
        if ( -e $evms_volume_disk )
        {

            # Delete if forcing
            if ( $CONFIG{ 'force' } )
            {
                logprint(
                    "Removing $evms_volume_disk - since we're forcing the install\n"
                );
                runCommand("echo Delete : $evms_volume_disk | evms", \%CONFIG);
            }
            else
            {
                logprint(
                    "The EVMS volume $evms_volume_disk already exists.  Aborting.\n"
                );
                logprint("Specify '--force' to delete and recreate\n");
                $CONFIG{'FAIL'} = 2;
                exit 127;
            }
        }

        #
        # Check whether the EVMS object exists, abort unless '--force'
        # is specified.
        #
        # Note: $evms_object_disk is not specified directly as a device
        #
        my $evms_object_disk =
          "$CONFIG{'evms'}/$CONFIG{'hostname'}-$partition->{'name'}";
        if ( -e $evms_object_disk )
        {

            # Delete if forcing
            if ( $CONFIG{ 'force' } )
            {
                logprint(
                    "Removing $evms_object_disk - since we're forcing the install\n"
                );
                runCommand("echo Delete : $evms_object_disk | evms", \%CONFIG);
            }
            else
            {
                logprint(
                    "The EVMS object $evms_object_disk already exists.  Aborting.\n"
                );
                logprint("Specify '--force' to delete and recreate\n");
                $CONFIG{'FAIL'} = 2;
                exit 127;
            }
        }
    }

    foreach my $partition (@PARTITIONS)
    {
        my $disk      = $CONFIG{ 'hostname' } . '-' . $partition->{ 'name' };
        my $evms_disk = "/dev/evms/$disk";

        #
        # Save the image path to the partitions array
        #
        $partition->{ 'imagetype' } = 'phy:';
        $partition->{ 'image' }     = $evms_disk;

        #
        #  Modify the size to something reasonable
        #
        my $size = $partition->{ 'size' };

        #
        # Convert Gb -> Mb for the partition image size.
        #
        if ( $size =~ /^([0-9.]+)Gb*$/i )
        {
            $size = $1 * 1024 . "M";
        }

        #
        #  Final adjustments to sizing.
        #
        $size =~ s/Mb*$/k/i;

        #
        # The commands to create the objects and volumes.
        #
        # create the object
        #
        my $disk_cmd_object =
          "echo allocate : $CONFIG{'evms'}/Freespace, size=$CONFIG{'size'}, name=$disk | evms";

        #
        # these will be piped to evms, but gotta check it first
        #
        my $disk_cmd_volume =
          "echo create : Volume, $CONFIG{'evms'}/$disk, name=$disk | evms";

        #
        # Create the volumes
        #
        runCommand($disk_cmd_object, \%CONFIG);
        runCommand($disk_cmd_volume, \%CONFIG);

        #
        #  Initialise the partition with the relevant filesystem.
        #
        if ( $partition->{ 'type' } eq 'swap' )
        {
            createSwap($disk_cmd_volume);
        }
        else
        {
            createFilesystem( $disk_cmd_volume, $partition->{ 'type' } );
        }
    }

}



=begin doc

  Format the given image in the users choice of filesystem.

=end doc

=cut

sub createFilesystem
{
    my ( $image, $fs ) = (@_);

    #
    #  We have the filesystem the user wanted, make sure that the
    # binary exists.
    #
    my $command = $CONFIG{ "make_fs_" . $fs };

    #
    #  Split the command into "binary" + "args".  Make sure that
    # the binary exists and is executable.
    #
    my ($binary, $args) = split(/ /, $command, 2);

    if ( !defined( which($binary) ) )
    {
        logprint(
            "The binary '$binary' required to create the filesystem $fs is missing\n"
        );
        $CONFIG{'FAIL'} = 1;
        exit 127;
    }

    unless ( $CONFIG{ 'dontformat' } ) {
        #
        #  OK we have the command and the filesystem.  Create it.
        #
        logprint("\nCreating $fs filesystem on $image\n");

        $command .= " " . $image;

        runCommand($command, \%CONFIG);
        logprint("Done\n");
    }
}



=begin doc

  Create the swap filesystem on the given device.

=end doc

=cut

sub createSwap
{
    my ($path) = (@_);

    logprint("\nCreating swap on $path\n");

    runCommand("mkswap $path", \%CONFIG);
    logprint("Done\n");
}


=begin doc

  Mount the loopback disk image into a temporary directory.

  Alternatively mount the relevant LVM volume instead.

=end doc

=cut

sub mountImage
{

    #
    #  Create a temporary mount-point to use for the image/volume.
    #
    $MOUNT_POINT = tempdir( CLEANUP => 1 );

    foreach my $partition (sort { length($a->{'mountpoint'}) <=> length($b->{'mountpoint'}) } @PARTITIONS)
    {
        if ( $partition->{ 'type' } ne 'swap' )
        {
            my $image      = $partition->{ 'image' };
            my $mountpoint = $MOUNT_POINT . $partition->{ 'mountpoint' };

            mkpath( $mountpoint, 0, 0755 );

            #
            #  Lookup the correct arguments to pass to mount.
            #
            my $mount_cmd;
            my $mount_type = $CONFIG{ 'mount_fs_' . $partition->{ 'type' } };

            #
            #  LVM partition
            #
            if ( $CONFIG{ 'lvm' } )
            {
                $mount_cmd = "mount $mount_type $image $mountpoint";
            }
            elsif ( $CONFIG{ 'evms' } )
            {
                $mount_cmd = "mount $mount_type $image $mountpoint";
            }
            elsif ( $CONFIG{ 'image-dev' } )
            {
                $mount_cmd = "mount $mount_type $image $mountpoint";
            }
            else
            {
                $mount_cmd = "mount $mount_type -o loop $image $mountpoint";
            }
            runCommand($mount_cmd, \%CONFIG);
        }
    }

}



=begin doc

  Install the system, by invoking the xt-install-image script.

  The script will be given the appropriate arguments from our environment.

=end doc

=cut

sub installSystem
{

    #
    #
    #  Basic command
    #
    my $cmd =
      "xt-install-image --hostname=$CONFIG{'hostname'} --location=$MOUNT_POINT --dist=$CONFIG{'dist'} --install-method=$CONFIG{'install-method'}";

    #
    #  Add on the install source if required.
    #
    $cmd .= " --install-source=$CONFIG{'install-source'}"
      if ( defined( $CONFIG{ 'install-source' } ) );

    #
    #  Do we have a per-image configuration file?
    #
    $cmd .= " --config=$CONFIG{'config'}" if ( defined( $CONFIG{ 'config' } ) );

    #
    #  Add on the mirror, if defined
    #
    $cmd .= " --mirror=$CONFIG{'mirror'}" if ( defined( $CONFIG{ 'mirror' } ) );

    #
    #  Add on the current cache setting
    #
    $cmd .= " --cache=$CONFIG{'cache'}" if length( $CONFIG{ 'cache' } );

    #
    #  Add on the current cachedir setting
    #
    $cmd .= " --cachedir=$CONFIG{'cachedir'}" if length( $CONFIG{ 'cachedir' } );

    #
    #  Propagate --verbose
    #
    if ( $CONFIG{ 'verbose' } )
    {
        $cmd .= " --verbose";
    }

    #
    #  Propagate --arch
    #
    if ( $CONFIG{ 'arch' } )
    {
        $cmd .= " --arch=$CONFIG{'arch'}";
    }


    #
    #  Propagate --debootstrap-cmd if install-method is debootstrap
    #
    if ( $CONFIG{ 'install-method' } eq 'debootstrap' and
         $CONFIG{ 'debootstrap-cmd' } )
    {
        $cmd .= " --debootstrap-cmd=$CONFIG{'debootstrap-cmd'}";
    }


    #
    #  Propagate --apt_proxy
    #
    if ( $CONFIG{ 'apt_proxy' } )
    {
        $cmd .= " --apt_proxy=$CONFIG{'apt_proxy'}";
    }


    #
    #  Show the user what they are installing
    #
    logprint("Installation method: $CONFIG{'install-method'}\n");

    #
    #  And where from, if relevant.
    #
    if ( ( lc( $CONFIG{ 'install-method' } ) eq "copy" ) ||
         ( lc( $CONFIG{ 'install-method' } ) eq "tar" ) )
    {
        logprint("(Source: $CONFIG{'install-source'})\n");
    }


    #
    #  Run the command.
    #
    runCommand($cmd, \%CONFIG);
    logprint("Done\n");
}



=begin doc

  Export our configuratione variables as a series of environmental
 variables.

  This is required so that our hook and role scripts can easily
 read the settings without access to the command line / configuration
 file we were invoked with.

=end doc

=cut

sub exportEnvironment
{

    #
    # Export partitions array to configuration
    #
    exportPartitionsToConfig();

    foreach my $key ( keys %CONFIG )
    {
        if ( defined( $CONFIG{ $key } ) )
        {
            my $envkey = $key;
            $envkey =~ s/-/_/g;
            $ENV{ $envkey } = $CONFIG{ $key };
        }
    }
}



=begin doc

  Run the xt-customise-system script to customize our fresh installation.

  Before we do this we must pass all the relevant options into our
 environment and mount /proc and /dev/pts.

=end doc

=cut

sub runCustomisationHooks
{

    #
    #  Before running any scripts we'll mount /proc in the guest.
    #
    #  1.  Make sure there is a directory.
    mkdir( $MOUNT_POINT . "/proc", 0755 ) if ( !-d $MOUNT_POINT . "/proc" );

    #  2.  Mount
    runCommand("mount -o bind /proc $MOUNT_POINT/proc", \%CONFIG);

    #
    #  Before running any scripts we'll mount /dev/pts in the guest, too.
    #
    #  1.  Make sure there is a directory.
    mkdir( $MOUNT_POINT . "/dev", 0755 ) if ( !-d $MOUNT_POINT . "/dev" );
    mkdir( $MOUNT_POINT . "/dev/pts", 0755 )
        if ( !-d $MOUNT_POINT . "/dev/pts" );

    #  2.  Mount
    runCommand("mount -t devpts devpts $MOUNT_POINT/dev/pts", \%CONFIG);

    #
    # Now update the environment for each defined IP address.
    # these are handled specially since we use arrays.
    #
    # Remove the value we set above.
    delete $ENV{ 'ip' };

    #
    # Setup a seperate ip$count value for each IP address.
    #
    my $ips   = $CONFIG{ 'ip' };
    my $count = 1;

    foreach my $i (@$ips)
    {
        $ENV{ 'ip' . $count } = $i;
        $count += 1;
    }

    $ENV{ 'ip_count' } = ( $count - 1 );


    #
    #  Now show the environment the children get
    #
    if ( $CONFIG{ 'verbose' } )
    {
        logprint("Customization Script Environment:\n");
        logprint("---------------------------------\n");
        foreach my $key ( sort keys %ENV )
        {
            logprint( "\t'" . $key . "' = '" . $ENV{ $key } . "'\n" );
        }
    }

    #
    #  Copy dom0's resolv.conf to domU
    #
    mv("$MOUNT_POINT/etc/resolv.conf", "$MOUNT_POINT/etc/resolv.conf.old") if -f "$MOUNT_POINT/etc/resolv.conf";
    cp("/etc/resolv.conf", "$MOUNT_POINT/etc/resolv.conf");

    #
    #  Actually run the appropriate hooks
    #
    my $customize =
      "xt-customize-image --dist=$CONFIG{'dist'} --location=$MOUNT_POINT";
    if ( $CONFIG{ 'verbose' } )
    {
        $customize .= " --verbose";
    }
    logprint("\nRunning hooks\n");
    runCommand($customize, \%CONFIG);
    logprint("Done\n");

    #
    #  Restore domU's resolv.conf if needed
    #
    if (-f "$MOUNT_POINT/etc/resolv.conf") {
        mv("$MOUNT_POINT/etc/resolv.conf.old", "$MOUNT_POINT/etc/resolv.conf");
    } else {
        unlink "$MOUNT_POINT/etc/resolv.conf";
    }
}



=begin doc

  Find a useable IP address from the file /etc/xen-tools/ips.txt.

=end doc

=cut

sub findIP
{

    # Abort if we don't have the IP file.
    return undef if ( !-e $CONFIG{ 'ipfile' } );

    #
    # Open and read the file.
    #
    open( RANGE, "<", $CONFIG{ 'ipfile' } ) or
      fail("Failed to read $CONFIG{'ipfile'} - $!");
    my @lines = <RANGE>;
    my @updated;
    close(RANGE);

    #
    #  Find an unclaimed line.
    #
    my $ip = undef;
    foreach my $line (@lines)
    {

        # skip empty lines.
        next if ( !defined($line) );
        next if ( !length($line) );
        chomp($line);

        # find an IP.
        if ( ( !defined($ip) ) && ( $line =~ /^([0-9\.]+)$/ ) )
        {
            $ip   = $line;
            $line = $ip . ": used";
        }

        push( @updated, $line );
    }

    #
    #  Now write out the new entries.
    #
    open( RANGE, ">", $CONFIG{ 'ipfile' } ) or
      fail("Failed to write to $CONFIG{'ipfile'} - $!");
    print RANGE join( "\n", @updated );
    close(RANGE);

    #
    #  Sanity check - handle the old case where the format of the file
    # was different.
    #
    if ( defined($ip) )
    {
        my @tmp = split( /\./, $ip );
        if ( scalar(@tmp) < 3 )
        {
            print <<EOF;
ERROR
-----

  The $CONFIG{'ipfile'} file must contain full IP addresses, for example:

192.168.1.100
192.168.1.101
192.168.1.102
..
192.168.1.200

  Aborting.  Please update the file or specify an IP address manually.

EOF
            $CONFIG{'FAIL'} = 1;
            exit 127;
        }
    }

    #
    #  Return
    #
    return ($ip);
}



=begin doc

  Run *all* specified role scripts.

=end doc

=cut

sub runRoleScripts
{
    my ($scripts) = (@_);

    if ( !defined($scripts) )
    {
        logprint("\nNo role scripts were specified.  Skipping\n");
        return;
    }

    #
    #  OK we have at least one script specified.  Split it up
    # and try it out.
    #
    foreach my $name ( split( /,/, $scripts ) )
    {

        # ignore empty ones.
        next if ( ( !defined($name) ) || ( !length($name) ) );

        # strip leading + triling space.
        $name =~ s/^\s+//;
        $name =~ s/\s+$//;

        # run the script
        runRoleScript($name);
    }
}



=begin doc

  Run the specified role script.

=end doc

=cut

sub runRoleScript
{
    my ($role) = (@_);

    my $roleDir = $CONFIG{ 'roledir' };

    #
    #  Role-script arguments are optional.  If present prepare to
    # append.
    #
    my $args = '';
    $args = " " . $CONFIG{ 'role-args' } if ( $CONFIG{ 'role-args' } );

    #
    #  The complete path to the role script
    #
    my $file = $role;
    $file = $roleDir . "/" . $file unless $file =~ /\//;

    if ( -x $file )
    {
        logprint("\nRole: $role\n");
        logprint("\tFile: $file\n");
        logprint("\tArgs: $args\n") if ( length($args) );
    }
    else
    {
        logprint("\nRole script not executable : $file for role '$role'\n");
        logprint("Ignoring\n");
        return;
    }


    #
    #  Our environment is already setup because of the call to
    # runCustomisationHooks.
    #
    #  We just need to run the script with two arguments:
    #
    #   - The mountpoint to the new system.
    #   - Any, optional, supplied arguments.
    #
    # NOTE:  Space added to $args as prefix ..
    #
    runCommand( $file . " " . $MOUNT_POINT . $args, \%CONFIG );

    logprint("Role script completed.\n");
}



=begin doc

  Create the Xen configuration file.

  Note that we don't need to do any setup for the environment since
 we did this already before running the hook scripts.

=end doc

=cut

sub runXenConfigCreation
{

    #
    #  Configuration file we'll create
    #
    my $dir  = $CONFIG{ 'output' };
    my $ext  = $CONFIG{ 'extension' };
    my $file = $dir . "/" . $CONFIG{ 'hostname' } . $ext;


    #
    #  Abort if it exists.
    #
    if ( -e $file )
    {
        unless ( $CONFIG{ 'force' } )
        {
            logprint("The Xen configuration file $file exists\n");
            logprint("Specify --force to force overwriting it.\n");
            logprint("Aborting\n");
            # FAIL = 2 will keep existing config file
            $CONFIG{'FAIL'} = 2;
            exit 127;
        }
    }

    #
    #  Create the config.
    #
    my $command = "xt-create-xen-config --output=$dir --extension=$ext";

    #
    #  Add the template if specified
    #
    if ( ( defined( $CONFIG{ 'template' } ) ) &&
         ( -e $CONFIG{ 'template' } ) )
    {
        $command .= " --template=" . $CONFIG{ 'template' };
    }

    #
    #  Add the admins, if any.
    #
    if ( defined( $CONFIG{ 'admins' } ) )
    {
        $command .= " --admins=$CONFIG{'admins'}";
    }

    #
    #  Make sure the template gets a list of all IPs
    #
    $ENV{ 'ips' } = $IP_ADDRESSES;


    logprint("\nCreating Xen configuration file\n");
    runCommand($command, \%CONFIG);
    logprint("Done\n");
}



=begin doc

  chroot() into the new system and setup the password.

=end doc

=cut

sub setupRootPassword
{
    logprint("Setting up root password\n");

    if ( $CONFIG{ 'passwd' } )
    {
        if ( -x $MOUNT_POINT . "/usr/bin/passwd" )
        {
            my $tryagain = 1;
            my $term = Term::ReadLine->new('Password change failed');
            while ($tryagain) {
                my $rc = system("chroot $MOUNT_POINT /usr/bin/passwd");
                if ($rc >> 8) {
                    $tryagain = $term->ask_yn(
                        prompt => 'Do you want to try to change the password again??',
                        default => 'y',
                    );
                } else {
                    $tryagain=0;
                }
            }
        }
        else
        {
            logprint("'passwd' command not found in the new install.\n");
        }
    }
    else
    {
        logprint("Generating a password for the new guest.\n");
        #
        #  Replace the password in the /etc/shadow file
        #
        my $shadow_path = $MOUNT_POINT . '/etc/shadow';
        if ( -e $shadow_path )
        {
            #
            #  Generate a password, salt and use that to generating a hash
            #
            if ( $CONFIG{ 'genpass' } )
            {
                $PASSWORD = generatePassword( $CONFIG{ 'genpass_len' } );
            }
            else
            {
                $PASSWORD = $CONFIG { 'password' };
            }

            my $salt = generatePassword(8);

            my $hash_method;
            if ($CONFIG{ 'hash_method' } eq 'md5')
            {
                $hash_method = '$1$';
            }
            elsif ($CONFIG{ 'hash_method' } eq 'sha256')
            {
                $hash_method = '$5$';
            }
            elsif ($CONFIG{ 'hash_method' } eq 'sha512')
            {
                $hash_method = '$6$';
            }
            else
            {
                fail("oops... unknown hashing method, should not happen!");
            }

            my $hash = crypt($PASSWORD, $hash_method . $salt);

            #
            #  Copy the file to ensure the original retains the correct
            #  permissions set by the System
            #
            my $tmp_shadow_path = "$shadow_path.tmp";
            cp("$shadow_path","$tmp_shadow_path");
            open(TMP, "<", $tmp_shadow_path) or fail($!);
            open(SHADOW, ">", $shadow_path) or fail($!);
            my $line;
            while(defined($line = <TMP>))
            {
                $line =~ s#^root:[^:]*:#root:$hash:#;
                print SHADOW $line;
            }

            #
            #  Close the files and delete the temporary file
            #
            close(SHADOW);
            close(TMP);
            unlink($tmp_shadow_path);
        }
        else
        {
            logprint("Failed to find /etc/passwd in the install.\n");
        }
    }
}

=begin doc

  create a random "string"

=end doc

=cut

sub generatePassword {
    my $length = $_[0];
    my $possible = 'abcdefghijkmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
    my $password = '';
    while (length($password) < $length) {
        $password .= substr($possible, (int(rand(length($possible)))), 1);
    }
    return $password;
}


=begin doc

  Unmount any mount-points which are below the given path.

  The mountpoints are chosen by looking at /proc/mounts which
 might not be portable, but works for me.  (tm).

=end doc

=cut

sub unMountImage
{
    my ($point, $fail_ok) = (@_);

    #
    #  First we unmount /proc and /dev/pts in the guest install.
    #
    runCommand("umount $point/proc", \%CONFIG, $fail_ok);
    #runCommand("umount $point/dev/pts", \%CONFIG, $fail_ok);

    #
    #  Open /proc/mount and get a list of currently mounted paths
    # which begin with our mount point.
    #
    my @points;

    open( MOUNTED, "<", "/proc/mounts" ) or
      fail("Failed to open mount list");
    foreach my $line (<MOUNTED>)
    {

        #
        #  Split into the device and mountpoint.
        #
        my ( $device, $path ) = split( / /, $line );

        if ( $path =~ /\Q$point\E/ )
        {
            push @points, $path;
        }
    }
    close(MOUNTED);

    #
    #  Now we have a list of mounts.  We need to move the
    # longest first, we can do this by sorting and reversing.
    #
    #  (ie. We unmount the children, then the parent.)
    #
    @points = sort @points;
    @points = reverse @points;

    foreach my $path (@points)
    {
        $CONFIG{ 'verbose' } && print "Unmounting : $path\n";
        runCommand("umount $path", \%CONFIG, $fail_ok);
    }

    $MOUNT_POINT = undef;
}


=begin doc

  If we still have the temporary image mounted then make sure
 it is unmounted before we terminate.

=end doc

=cut

sub clean_up () {
    if ( defined($MOUNT_POINT) )
    {
        unMountImage($MOUNT_POINT, 1);
    }
}

END
{
    # Capture exit code
    my $exitcode = $?;

    exit $exitcode if $VERSION || $HELP || $MANUAL || $DUMPCONFIG;

    my $host_rsa_key = '';
    #
    #  Unmount the image if it is still mounted.
    #
    if ( defined($MOUNT_POINT) )
    {
        #
        #  Before we unmount get the host's RSA key
        #
        my $key_path .= $MOUNT_POINT;
        $key_path .= '/etc/ssh/ssh_host_rsa_key.pub';
        if ( `ssh-keygen -lf $key_path` =~ /^(\S+)\s+(\S+)/ ) {
            $host_rsa_key = $2;
        } else {
            $host_rsa_key = "N/A";
        }
        unMountImage($MOUNT_POINT, $CONFIG{'FAIL'});
    }

    #
    #  If we're supposed to start the new instance do so - note here we
    # have to unmount the image first.
    #
    if ( $CONFIG{ 'boot' } and !$CONFIG{'FAIL'} )
    {
        #
        #  If there is an /etc/xen/auto directory then link in the
        # domain so that it will automatically restart, if it isn't
        # already present.
        #
        #  (Will be present if this is overwriting a previous image,
        # for example.)
        #
        if ( -d "/etc/xen/auto" )
        {
            my $cfg =
                $CONFIG{ 'output' } . "/" . $CONFIG{ 'hostname' } .
                $CONFIG{ 'extension' };

            if ( !-e $cfg )
            {
                logprint("Creating auto-start symlink to: $cfg\n");

                my $link = "ln -s $cfg /etc/xen/auto/";
                runCommand($link, \%CONFIG);
            }
        }

        #
        #
        #  Start the image
        #

        # Config file.
        my $cfg =
            $CONFIG{ 'output' } . "/" . $CONFIG{ 'hostname' } .
            $CONFIG{ 'extension' };

        # Start the DomU
        runCommand("$CONFIG{'xm'} create $cfg", \%CONFIG);

        logprint("Started new Xen guest: $CONFIG{'hostname'} [$cfg]\n");
    }

    #
    #  Here we print out the status message when finishing.
    #
    #  NOTE:  We use the $CONFIG{'pid'} here to control whether the
    # message is displayed - since this avoids it from being displayed
    # twice when --boot is used.
    #
    if ( ( defined( $CONFIG{ 'hostname' } ) ) &&
         ( -e "/var/log/xen-tools/$CONFIG{'hostname'}.log" ) &&
         ( !$CONFIG{ 'pid' } ) )
    {
        print "\n\nLogfile produced at:\n";
        print "\t /var/log/xen-tools/$CONFIG{'hostname'}.log\n";
    }

    #
    #  Did we fail?  If so then we should remove the broken installation,
    # unless "--keep" was specified.
    #
    #  If we didn't fail, then we assume we succeeded, print a summary
    #
    #  $CONFIG{'FAIL'} = 0  -  Success
    #  $CONFIG{'FAIL'} = 1  -  Failed to install, delete the image
    #  $CONFIG{'FAIL'} = 2  -  Files exist, either .cfg or lvm... etc
    if ( $CONFIG{'FAIL'} == 1 && ( !$CONFIG{ 'keep' } ) )
    {

        #
        #  Run the command
        #
        $CONFIG{ 'verbose' } &&
          logprint("Removing failed install: $CONFIG{'hostname'}\n");

        if ($CONFIG{ 'hostname' }) {
            my $option = '';
            if ($CONFIG{ 'lvm' }) {
                $option = "--lvm=$CONFIG{'lvm'}"
            } elsif ($CONFIG{ 'evms' }) {
                $option = "--evms=$CONFIG{'evms'}"
            } elsif ($CONFIG{ 'dir' }) {
                $option = "--dir=$CONFIG{'dir'}"
            }

            if ($option) {
                runCommand("xen-delete-image $option --hostname=$CONFIG{'hostname'}", \%CONFIG);
            } else {
                die "Assertion that either --dir, --lvm, or --dir are given".
                    " failed.\nThis is probably a bug, please report it.";
            }
        }
    } elsif ( $CONFIG{'FAIL'} == 0 ) {
        #
        #  Assume success
        #
        logprint("\nInstallation Summary\n");
        logprint("---------------------\n");
        logprint("Hostname        :  $CONFIG{'hostname'}\n");
        logprint("Distribution    :  $CONFIG{'dist'}\n");
        logprint("MAC Address     :  $CONFIG{'mac'}\n");
        logprint("IP Address(es)  :  ");
        if ( $CONFIG{ 'dhcp' } ) {
           logprint("dynamic");
        } elsif( $CONFIG{ 'ip' } ) {
           logprint( $IP_ADDRESSES );
        }
        logprint("\n");
        logprint("RSA Fingerprint :  $host_rsa_key\n");
        logprint("Root Password   :  ");
        if ( $PASSWORD ) {
            logprint("$PASSWORD\n");
        } else {
            logprint ("N/A\n");
        }
        logprint("\n");
    }

    exit $exitcode;
}