summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VBoxShell/vboxshell.py
blob: fbca08e0f6cab18da81e8a0326db5cefc4d6fe6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$

"""
VirtualBox Python Shell.

This program is a simple interactive shell for VirtualBox. You can query
information and issue commands from a simple command line.

It also provides you with examples on how to use VirtualBox's Python API.
This shell is even somewhat documented, supports TAB-completion and
history if you have Python readline installed.

Finally, shell allows arbitrary custom extensions, just create
.VirtualBox/shexts/ and drop your extensions there.
                                               Enjoy.

P.S. Our apologies for the code quality.
"""

from __future__ import print_function

__copyright__ = \
"""
Copyright (C) 2009-2019 Oracle Corporation

This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
"""
__version__ = "$Revision$"


import gc
import os
import sys
import traceback
import shlex
import time
import re
import platform
from optparse import OptionParser
from pprint import pprint


#
# Global Variables
#
g_fBatchMode = False
g_sScriptFile = None
g_sCmd = None
g_fHasReadline = True
try:
    import readline
    import rlcompleter
except ImportError:
    g_fHasReadline = False

g_sPrompt = "vbox> "

g_fHasColors  = True
g_dTermColors = {
    'red':      '\033[31m',
    'blue':     '\033[94m',
    'green':    '\033[92m',
    'yellow':   '\033[93m',
    'magenta':  '\033[35m',
    'cyan':     '\033[36m'
}



def colored(strg, color):
    """
    Translates a string to one including coloring settings, if enabled.
    """
    if not g_fHasColors:
        return strg
    col = g_dTermColors.get(color, None)
    if col:
        return col+str(strg)+'\033[0m'
    return strg

if g_fHasReadline:
    class CompleterNG(rlcompleter.Completer):
        def __init__(self, dic, ctx):
            self.ctx = ctx
            rlcompleter.Completer.__init__(self, dic)

        def complete(self, text, state):
            """
            taken from:
            http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
            """
            if False and text == "":
                return ['\t', None][state]
            else:
                return rlcompleter.Completer.complete(self, text, state)

        def canBePath(self, _phrase, word):
            return word.startswith('/')

        def canBeCommand(self, phrase, _word):
            spaceIdx = phrase.find(" ")
            begIdx = readline.get_begidx()
            firstWord = (spaceIdx == -1 or begIdx < spaceIdx)
            if firstWord:
                return True
            if phrase.startswith('help'):
                return True
            return False

        def canBeMachine(self, phrase, word):
            return not self.canBePath(phrase, word) and not self.canBeCommand(phrase, word)

        def global_matches(self, text):
            """
            Compute matches when text is a simple name.
            Return a list of all names currently defined
            in self.namespace that match.
            """

            matches = []
            phrase = readline.get_line_buffer()

            try:
                if self.canBePath(phrase, text):
                    (directory, rest) = os.path.split(text)
                    c = len(rest)
                    for word in os.listdir(directory):
                        if c == 0 or word[:c] == rest:
                            matches.append(os.path.join(directory, word))

                if self.canBeCommand(phrase, text):
                    c = len(text)
                    for lst in [ self.namespace ]:
                        for word in lst:
                            if word[:c] == text:
                                matches.append(word)

                if self.canBeMachine(phrase, text):
                    c = len(text)
                    for mach in getMachines(self.ctx, False, True):
                        # although it has autoconversion, we need to cast
                        # explicitly for subscripts to work
                        word = re.sub("(?<!\\\\) ", "\\ ", str(mach.name))
                        if word[:c] == text:
                            matches.append(word)
                        word = str(mach.id)
                        if word[:c] == text:
                            matches.append(word)

            except Exception as e:
                printErr(self.ctx, e)
                if g_fVerbose:
                    traceback.print_exc()

            return matches

def autoCompletion(cmds, ctx):
    if not g_fHasReadline:
        return

    comps = {}
    for (key, _value) in list(cmds.items()):
        comps[key] = None
    completer = CompleterNG(comps, ctx)
    readline.set_completer(completer.complete)
    delims = readline.get_completer_delims()
    readline.set_completer_delims(re.sub("[\\./-]", "", delims)) # remove some of the delimiters
    readline.parse_and_bind("set editing-mode emacs")
    # OSX need it
    if platform.system() == 'Darwin':
        # see http://www.certif.com/spec_help/readline.html
        readline.parse_and_bind ("bind ^I rl_complete")
        readline.parse_and_bind ("bind ^W ed-delete-prev-word")
        # Doesn't work well
        # readline.parse_and_bind ("bind ^R em-inc-search-prev")
    readline.parse_and_bind("tab: complete")


g_fVerbose = False

def split_no_quotes(s):
    return shlex.split(s)

def progressBar(ctx, progress, wait=1000):
    try:
        while not progress.completed:
            print("%s %%\r" % (colored(str(progress.percent), 'red')), end="")
            sys.stdout.flush()
            progress.waitForCompletion(wait)
            ctx['global'].waitForEvents(0)
        if int(progress.resultCode) != 0:
            reportError(ctx, progress)
        return 1
    except KeyboardInterrupt:
        print("Interrupted.")
        ctx['interrupt'] = True
        if progress.cancelable:
            print("Canceling task...")
            progress.cancel()
        return 0

def printErr(_ctx, e):
    oVBoxMgr = _ctx['global']
    if oVBoxMgr.errIsOurXcptKind(e):
        print(colored('%s: %s' % (oVBoxMgr.xcptToString(e), oVBoxMgr.xcptGetMessage(e)), 'red'))
    else:
        print(colored(str(e), 'red'))

def reportError(_ctx, progress):
    errorinfo = progress.errorInfo
    if errorinfo:
        print(colored("Error in module '%s': %s" % (errorinfo.component, errorinfo.text), 'red'))

def colCat(_ctx, strg):
    return colored(strg, 'magenta')

def colVm(_ctx, vmname):
    return colored(vmname, 'blue')

def colPath(_ctx, path):
    return colored(path, 'green')

def colSize(_ctx, byte):
    return colored(byte, 'red')

def colPci(_ctx, pcidev):
    return colored(pcidev, 'green')

def colDev(_ctx, pcidev):
    return colored(pcidev, 'cyan')

def colSizeM(_ctx, mbyte):
    return colored(str(mbyte)+'M', 'red')

def createVm(ctx, name, kind):
    vbox = ctx['vb']
    mach = vbox.createMachine("", name, [], kind, "")
    mach.saveSettings()
    print("created machine with UUID", mach.id)
    vbox.registerMachine(mach)
    # update cache
    getMachines(ctx, True)

def removeVm(ctx, mach):
    uuid = mach.id
    print("removing machine ", mach.name, "with UUID", uuid)
    cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
    disks = mach.unregister(ctx['global'].constants.CleanupMode_Full)
    if mach:
        progress = mach.deleteConfig(disks)
        if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
            print("Success!")
        else:
            reportError(ctx, progress)
    # update cache
    getMachines(ctx, True)

def startVm(ctx, mach, vmtype):
    vbox = ctx['vb']
    perf = ctx['perf']
    session = ctx['global'].getSessionObject()
    asEnv = []
    progress = mach.launchVMProcess(session, vmtype, asEnv)
    if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
        # we ignore exceptions to allow starting VM even if
        # perf collector cannot be started
        if perf:
            try:
                perf.setup(['*'], [mach], 10, 15)
            except Exception as e:
                printErr(ctx, e)
                if g_fVerbose:
                    traceback.print_exc()
        session.unlockMachine()

class CachedMach:
    def __init__(self, mach):
        if mach.accessible:
            self.name = mach.name
        else:
            self.name = '<inaccessible>'
        self.id = mach.id

def cacheMachines(_ctx, lst):
    result = []
    for mach in lst:
        elem = CachedMach(mach)
        result.append(elem)
    return result

def getMachines(ctx, invalidate = False, simple=False):
    if ctx['vb'] is not None:
        if ctx['_machlist'] is None or invalidate:
            ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
            ctx['_machlistsimple'] = cacheMachines(ctx, ctx['_machlist'])
        if simple:
            return ctx['_machlistsimple']
        else:
            return ctx['_machlist']
    else:
        return []

def asState(var):
    if var:
        return colored('on', 'green')
    else:
        return colored('off', 'green')

def asFlag(var):
    if var:
        return 'yes'
    else:
        return 'no'

def getFacilityStatus(ctx, guest, facilityType):
    (status, _timestamp) = guest.getFacilityStatus(facilityType)
    return asEnumElem(ctx, 'AdditionsFacilityStatus', status)

def perfStats(ctx, mach):
    if not ctx['perf']:
        return
    for metric in ctx['perf'].query(["*"], [mach]):
        print(metric['name'], metric['values_as_string'])

def guestExec(ctx, machine, console, cmds):
    exec(cmds)

def printMouseEvent(_ctx, mev):
    print("Mouse : mode=%d x=%d y=%d z=%d w=%d buttons=%x" % (mev.mode, mev.x, mev.y, mev.z, mev.w, mev.buttons))

def printKbdEvent(ctx, kev):
    print("Kbd: ", ctx['global'].getArray(kev, 'scancodes'))

def printMultiTouchEvent(ctx, mtev):
    print("MultiTouch : contacts=%d time=%d" % (mtev.contactCount, mtev.scanTime))
    xPositions = ctx['global'].getArray(mtev, 'xPositions')
    yPositions = ctx['global'].getArray(mtev, 'yPositions')
    contactIds = ctx['global'].getArray(mtev, 'contactIds')
    contactFlags = ctx['global'].getArray(mtev, 'contactFlags')

    for i in range(0, mtev.contactCount):
        print("  [%d] %d,%d %d %d" % (i, xPositions[i], yPositions[i], contactIds[i], contactFlags[i]))

def monitorSource(ctx, eventSource, active, dur):
    def handleEventImpl(event):
        evtype = event.type
        print("got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)))
        if evtype == ctx['global'].constants.VBoxEventType_OnMachineStateChanged:
            scev = ctx['global'].queryInterface(event, 'IMachineStateChangedEvent')
            if scev:
                print("machine state event: mach=%s state=%s" % (scev.machineId, scev.state))
        elif  evtype == ctx['global'].constants.VBoxEventType_OnSnapshotTaken:
            stev = ctx['global'].queryInterface(event, 'ISnapshotTakenEvent')
            if stev:
                print("snapshot taken event: mach=%s snap=%s" % (stev.machineId, stev.snapshotId))
        elif  evtype == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged:
            gpcev = ctx['global'].queryInterface(event, 'IGuestPropertyChangedEvent')
            if gpcev:
                print("guest property change: name=%s value=%s" % (gpcev.name, gpcev.value))
        elif  evtype == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged:
            psev = ctx['global'].queryInterface(event, 'IMousePointerShapeChangedEvent')
            if psev:
                shape = ctx['global'].getArray(psev, 'shape')
                if shape is None:
                    print("pointer shape event - empty shape")
                else:
                    print("pointer shape event: w=%d h=%d shape len=%d" % (psev.width, psev.height, len(shape)))
        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse:
            mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent')
            if mev:
                printMouseEvent(ctx, mev)
        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
            kev = ctx['global'].queryInterface(event, 'IGuestKeyboardEvent')
            if kev:
                printKbdEvent(ctx, kev)
        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestMultiTouch:
            mtev = ctx['global'].queryInterface(event, 'IGuestMultiTouchEvent')
            if mtev:
                printMultiTouchEvent(ctx, mtev)

    class EventListener(object):
        def __init__(self, arg):
            pass

        def handleEvent(self, event):
            try:
                # a bit convoluted QI to make it work with MS COM
                handleEventImpl(ctx['global'].queryInterface(event, 'IEvent'))
            except:
                traceback.print_exc()
            pass

    if active:
        listener = ctx['global'].createListener(EventListener)
    else:
        listener = eventSource.createListener()
    registered = False
    if dur == -1:
        # not infinity, but close enough
        dur = 100000
    try:
        eventSource.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], active)
        registered = True
        end = time.time() + dur
        while  time.time() < end:
            if active:
                ctx['global'].waitForEvents(500)
            else:
                event = eventSource.getEvent(listener, 500)
                if event:
                    handleEventImpl(event)
                    # otherwise waitable events will leak (active listeners ACK automatically)
                    eventSource.eventProcessed(listener, event)
    # We need to catch all exceptions here, otherwise listener will never be unregistered
    except:
        traceback.print_exc()
        pass
    if listener and registered:
        eventSource.unregisterListener(listener)


g_tsLast = 0
def recordDemo(ctx, console, filename, dur):
    demo = open(filename, 'w')
    header = "VM=" + console.machine.name + "\n"
    demo.write(header)

    global g_tsLast
    g_tsLast = time.time()

    def stamp():
        global g_tsLast
        tsCur = time.time()
        timePassed = int((tsCur-g_tsLast)*1000)
        g_tsLast = tsCur
        return timePassed

    def handleEventImpl(event):
        evtype = event.type
        #print("got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)))
        if evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse:
            mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent')
            if mev:
                line = "%d: m %d %d %d %d %d %d\n" % (stamp(), mev.mode, mev.x, mev.y, mev.z, mev.w, mev.buttons)
                demo.write(line)
        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
            kev = ctx['global'].queryInterface(event, 'IGuestKeyboardEvent')
            if kev:
                line = "%d: k %s\n" % (stamp(), str(ctx['global'].getArray(kev, 'scancodes')))
                demo.write(line)

    listener = console.eventSource.createListener()
    registered = False
    # we create an aggregated event source to listen for multiple event sources (keyboard and mouse in our case)
    agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource])
    demo = open(filename, 'w')
    header = "VM=" + console.machine.name + "\n"
    demo.write(header)
    if dur == -1:
        # not infinity, but close enough
        dur = 100000
    try:
        agg.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], False)
        registered = True
        end = time.time() + dur
        while  time.time() < end:
            event = agg.getEvent(listener, 1000)
            if event:
                handleEventImpl(event)
                # keyboard/mouse events aren't waitable, so no need for eventProcessed
    # We need to catch all exceptions here, otherwise listener will never be unregistered
    except:
        traceback.print_exc()
        pass
    demo.close()
    if listener and registered:
        agg.unregisterListener(listener)


def playbackDemo(ctx, console, filename, dur):
    demo = open(filename, 'r')

    if dur == -1:
        # not infinity, but close enough
        dur = 100000

    header = demo.readline()
    print("Header is", header)
    basere = re.compile(r'(?P<s>\d+): (?P<t>[km]) (?P<p>.*)')
    mre = re.compile(r'(?P<a>\d+) (?P<x>-*\d+) (?P<y>-*\d+) (?P<z>-*\d+) (?P<w>-*\d+) (?P<b>-*\d+)')
    kre = re.compile(r'\d+')

    kbd = console.keyboard
    mouse = console.mouse

    try:
        end = time.time() + dur
        for line in demo:
            if time.time() > end:
                break
            match = basere.search(line)
            if match is None:
                continue

            rdict = match.groupdict()
            stamp = rdict['s']
            params = rdict['p']
            rtype = rdict['t']

            time.sleep(float(stamp)/1000)

            if rtype == 'k':
                codes = kre.findall(params)
                #print("KBD:", codes)
                kbd.putScancodes(codes)
            elif rtype == 'm':
                mm = mre.search(params)
                if mm is not None:
                    mdict = mm.groupdict()
                    if mdict['a'] == '1':
                        # absolute
                        #print("MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b'])
                        mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))
                    else:
                        #print("MR: ", mdict['x'], mdict['y'], mdict['b'])
                        mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))

    # We need to catch all exceptions here, to close file
    except KeyboardInterrupt:
        ctx['interrupt'] = True
    except:
        traceback.print_exc()
        pass
    demo.close()


def takeScreenshotOld(_ctx, console, args):
    from PIL import Image
    display = console.display
    if len(args) > 0:
        f = args[0]
    else:
        f = "/tmp/screenshot.png"
    if len(args) > 3:
        screen = int(args[3])
    else:
        screen = 0
    (fbw, fbh, _fbbpp, fbx, fby, _) = display.getScreenResolution(screen)
    if len(args) > 1:
        w = int(args[1])
    else:
        w = fbw
    if len(args) > 2:
        h = int(args[2])
    else:
        h = fbh

    print("Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f))
    data = display.takeScreenShotToArray(screen, w, h, ctx['const'].BitmapFormat_RGBA)
    size = (w, h)
    mode = "RGBA"
    im = Image.frombuffer(mode, size, str(data), "raw", mode, 0, 1)
    im.save(f, "PNG")

def takeScreenshot(_ctx, console, args):
    display = console.display
    if len(args) > 0:
        f = args[0]
    else:
        f = "/tmp/screenshot.png"
    if len(args) > 3:
        screen = int(args[3])
    else:
        screen = 0
    (fbw, fbh, _fbbpp, fbx, fby, _) = display.getScreenResolution(screen)
    if len(args) > 1:
        w = int(args[1])
    else:
        w = fbw
    if len(args) > 2:
        h = int(args[2])
    else:
        h = fbh

    print("Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f))
    data = display.takeScreenShotToArray(screen, w, h, ctx['const'].BitmapFormat_PNG)
    pngfile = open(f, 'wb')
    pngfile.write(data)
    pngfile.close()

def teleport(ctx, _session, console, args):
    if args[0].find(":") == -1:
        print("Use host:port format for teleport target")
        return
    (host, port) = args[0].split(":")
    if len(args) > 1:
        passwd = args[1]
    else:
        passwd = ""

    if len(args) > 2:
        maxDowntime = int(args[2])
    else:
        maxDowntime = 250

    port = int(port)
    print("Teleporting to %s:%d..." % (host, port))
    progress = console.teleport(host, port, passwd, maxDowntime)
    if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
        print("Success!")
    else:
        reportError(ctx, progress)


def guestStats(ctx, console, args):
    guest = console.guest
    # we need to set up guest statistics
    if len(args) > 0 :
        update = args[0]
    else:
        update = 1
    if guest.statisticsUpdateInterval != update:
        guest.statisticsUpdateInterval = update
        try:
            time.sleep(float(update)+0.1)
        except:
            # to allow sleep interruption
            pass
    all_stats = ctx['const'].all_values('GuestStatisticType')
    cpu = 0
    for s in list(all_stats.keys()):
        try:
            val = guest.getStatistic( cpu, all_stats[s])
            print("%s: %d" % (s, val))
        except:
            # likely not implemented
            pass

def plugCpu(_ctx, machine, _session, args):
    cpu = int(args[0])
    print("Adding CPU %d..." % (cpu))
    machine.hotPlugCPU(cpu)

def unplugCpu(_ctx, machine, _session, args):
    cpu = int(args[0])
    print("Removing CPU %d..." % (cpu))
    machine.hotUnplugCPU(cpu)

def mountIso(_ctx, machine, _session, args):
    machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
    machine.saveSettings()

def cond(c, v1, v2):
    if c:
        return v1
    else:
        return v2

def printHostUsbDev(ctx, ud):
    print("  %s: %s (vendorId=%d productId=%d serial=%s) %s" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber, asEnumElem(ctx, 'USBDeviceState', ud.state)))

def printUsbDev(_ctx, ud):
    print("  %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id,  colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber))

def printSf(ctx, sf):
    print("    name=%s host=%s %s %s" % (sf.name, colPath(ctx, sf.hostPath), cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only")))

def ginfo(ctx, console, _args):
    guest = console.guest
    if guest.additionsRunLevel != ctx['const'].AdditionsRunLevelType_None:
        print("Additions active, version %s" % (guest.additionsVersion))
        print("Support seamless: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Seamless)))
        print("Support graphics: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Graphics)))
        print("Balloon size: %d" % (guest.memoryBalloonSize))
        print("Statistic update interval: %d" % (guest.statisticsUpdateInterval))
    else:
        print("No additions")
    usbs = ctx['global'].getArray(console, 'USBDevices')
    print("Attached USB:")
    for ud in usbs:
        printUsbDev(ctx, ud)
    rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
    print("Remote USB:")
    for ud in rusbs:
        printHostUsbDev(ctx, ud)
    print("Transient shared folders:")
    sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
    for sf in sfs:
        printSf(ctx, sf)

def cmdExistingVm(ctx, mach, cmd, args):
    session = None
    try:
        vbox = ctx['vb']
        session = ctx['global'].openMachineSession(mach, fPermitSharing=True)
    except Exception as e:
        printErr(ctx, "Session to '%s' not open: %s" % (mach.name, str(e)))
        if g_fVerbose:
            traceback.print_exc()
        return
    if session.state != ctx['const'].SessionState_Locked:
        print("Session to '%s' in wrong state: %s" % (mach.name, session.state))
        session.unlockMachine()
        return
    # this could be an example how to handle local only (i.e. unavailable
    # in Webservices) functionality
    if ctx['remote'] and cmd == 'some_local_only_command':
        print('Trying to use local only functionality, ignored')
        session.unlockMachine()
        return
    console = session.console
    ops = {'pause':           lambda: console.pause(),
           'resume':          lambda: console.resume(),
           'powerdown':       lambda: console.powerDown(),
           'powerbutton':     lambda: console.powerButton(),
           'stats':           lambda: perfStats(ctx, mach),
           'guest':           lambda: guestExec(ctx, mach, console, args),
           'ginfo':           lambda: ginfo(ctx, console, args),
           'guestlambda':     lambda: args[0](ctx, mach, console, args[1:]),
           'save':            lambda: progressBar(ctx, session.machine.saveState()),
           'screenshot':      lambda: takeScreenshot(ctx, console, args),
           'teleport':        lambda: teleport(ctx, session, console, args),
           'gueststats':      lambda: guestStats(ctx, console, args),
           'plugcpu':         lambda: plugCpu(ctx, session.machine, session, args),
           'unplugcpu':       lambda: unplugCpu(ctx, session.machine, session, args),
           'mountiso':        lambda: mountIso(ctx, session.machine, session, args),
           }
    try:
        ops[cmd]()
    except KeyboardInterrupt:
        ctx['interrupt'] = True
    except Exception as e:
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()

    session.unlockMachine()


def cmdClosedVm(ctx, mach, cmd, args=[], save=True):
    session = ctx['global'].openMachineSession(mach, fPermitSharing=True)
    mach = session.machine
    try:
        cmd(ctx, mach, args)
    except Exception as e:
        save = False
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()
    if save:
        try:
            mach.saveSettings()
        except Exception as e:
            printErr(ctx, e)
            if g_fVerbose:
                traceback.print_exc()
    ctx['global'].closeMachineSession(session)


def cmdAnyVm(ctx, mach, cmd, args=[], save=False):
    session = ctx['global'].openMachineSession(mach, fPermitSharing=True)
    mach = session.machine
    try:
        cmd(ctx, mach, session.console, args)
    except Exception as e:
        save = False
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()
    if save:
        mach.saveSettings()
    ctx['global'].closeMachineSession(session)

def machById(ctx, uuid):
    mach = ctx['vb'].findMachine(uuid)
    return mach

class XPathNode:
    def __init__(self, parent, obj, ntype):
        self.parent = parent
        self.obj = obj
        self.ntype = ntype
    def lookup(self, subpath):
        children = self.enum()
        matches = []
        for e in children:
            if e.matches(subpath):
                matches.append(e)
        return matches
    def enum(self):
        return []
    def matches(self, subexp):
        if subexp == self.ntype:
            return True
        if not subexp.startswith(self.ntype):
            return False
        match = re.search(r"@(?P<a>\w+)=(?P<v>[^\'\[\]]+)", subexp)
        matches = False
        try:
            if match is not None:
                xdict = match.groupdict()
                attr = xdict['a']
                val = xdict['v']
                matches = (str(getattr(self.obj, attr)) == val)
        except:
            pass
        return matches
    def apply(self, cmd):
        exec(cmd, {'obj':self.obj, 'node':self, 'ctx':self.getCtx()}, {})
    def getCtx(self):
        if hasattr(self, 'ctx'):
            return self.ctx
        return self.parent.getCtx()

class XPathNodeHolder(XPathNode):
    def __init__(self, parent, obj, attr, heldClass, xpathname):
        XPathNode.__init__(self, parent, obj, 'hld '+xpathname)
        self.attr = attr
        self.heldClass = heldClass
        self.xpathname = xpathname
    def enum(self):
        children = []
        for node in self.getCtx()['global'].getArray(self.obj, self.attr):
            nodexml = self.heldClass(self, node)
            children.append(nodexml)
        return children
    def matches(self, subexp):
        return subexp == self.xpathname

class XPathNodeValue(XPathNode):
    def __init__(self, parent, obj, xpathname):
        XPathNode.__init__(self, parent, obj, 'val '+xpathname)
        self.xpathname = xpathname
    def matches(self, subexp):
        return subexp == self.xpathname

class XPathNodeHolderVM(XPathNodeHolder):
    def __init__(self, parent, vbox):
        XPathNodeHolder.__init__(self, parent, vbox, 'machines', XPathNodeVM, 'vms')

class XPathNodeVM(XPathNode):
    def __init__(self, parent, obj):
        XPathNode.__init__(self, parent, obj, 'vm')
    #def matches(self, subexp):
    #    return subexp=='vm'
    def enum(self):
        return [XPathNodeHolderNIC(self, self.obj),
                XPathNodeValue(self, self.obj.BIOSSettings,  'bios'), ]

class XPathNodeHolderNIC(XPathNodeHolder):
    def __init__(self, parent, mach):
        XPathNodeHolder.__init__(self, parent, mach, 'nics', XPathNodeVM, 'nics')
        self.maxNic = self.getCtx()['vb'].systemProperties.getMaxNetworkAdapters(self.obj.chipsetType)
    def enum(self):
        children = []
        for i in range(0, self.maxNic):
            node = XPathNodeNIC(self, self.obj.getNetworkAdapter(i))
            children.append(node)
        return children

class XPathNodeNIC(XPathNode):
    def __init__(self, parent, obj):
        XPathNode.__init__(self, parent, obj, 'nic')
    def matches(self, subexp):
        return subexp == 'nic'

class XPathNodeRoot(XPathNode):
    def __init__(self, ctx):
        XPathNode.__init__(self, None, None, 'root')
        self.ctx = ctx
    def enum(self):
        return [XPathNodeHolderVM(self, self.ctx['vb'])]
    def matches(self, subexp):
        return True

def eval_xpath(ctx, scope):
    pathnames = scope.split("/")[2:]
    nodes = [XPathNodeRoot(ctx)]
    for path in pathnames:
        seen = []
        while len(nodes) > 0:
            node = nodes.pop()
            seen.append(node)
        for s in seen:
            matches = s.lookup(path)
            for match in matches:
                nodes.append(match)
        if len(nodes) == 0:
            break
    return nodes

def argsToMach(ctx, args):
    if len(args) < 2:
        print("usage: %s [vmname|uuid]" % (args[0]))
        return None
    uuid = args[1]
    mach = machById(ctx, uuid)
    if mach == None:
        print("Machine '%s' is unknown, use list command to find available machines" % (uuid))
    return mach

def helpSingleCmd(cmd, h, sp):
    if sp != 0:
        spec = " [ext from "+sp+"]"
    else:
        spec = ""
    print("    %s: %s%s" % (colored(cmd, 'blue'), h, spec))

def helpCmd(_ctx, args):
    if len(args) == 1:
        print("Help page:")
        names = list(commands.keys())
        names.sort()
        for i in names:
            helpSingleCmd(i, commands[i][0], commands[i][2])
    else:
        cmd = args[1]
        c = commands.get(cmd)
        if c == None:
            print("Command '%s' not known" % (cmd))
        else:
            helpSingleCmd(cmd, c[0], c[2])
    return 0

def asEnumElem(ctx, enum, elem):
    enumVals = ctx['const'].all_values(enum)
    for e in list(enumVals.keys()):
        if str(elem) == str(enumVals[e]):
            return colored(e, 'green')
    return colored("<unknown>", 'green')

def enumFromString(ctx, enum, strg):
    enumVals = ctx['const'].all_values(enum)
    return enumVals.get(strg, None)

def listCmd(ctx, _args):
    for mach in getMachines(ctx, True):
        try:
            if mach.teleporterEnabled:
                tele = "[T] "
            else:
                tele = "    "
                print("%sMachine '%s' [%s], machineState=%s, sessionState=%s" % (tele, colVm(ctx, mach.name), mach.id, asEnumElem(ctx, "MachineState", mach.state), asEnumElem(ctx, "SessionState", mach.sessionState)))
        except Exception as e:
            printErr(ctx, e)
            if g_fVerbose:
                traceback.print_exc()
    return 0

def infoCmd(ctx, args):
    if len(args) < 2:
        print("usage: info [vmname|uuid]")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    try:
        vmos = ctx['vb'].getGuestOSType(mach.OSTypeId)
    except:
        vmos = None
    print(" One can use setvar <mach> <var> <value> to change variable, using name in [].")
    print("  Name [name]: %s" % (colVm(ctx, mach.name)))
    print("  Description [description]: %s" % (mach.description))
    print("  ID [n/a]: %s" % (mach.id))
    print("  OS Type [via OSTypeId]: %s" % (vmos.description if vmos is not None else mach.OSTypeId))
    print("  Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx, "FirmwareType", mach.firmwareType), mach.firmwareType))
    print()
    print("  CPUs [CPUCount]: %d" % (mach.CPUCount))
    print("  RAM [memorySize]: %dM" % (mach.memorySize))
    print("  VRAM [VRAMSize]: %dM" % (mach.graphicsAdapter.VRAMSize))
    print("  Monitors [monitorCount]: %d" % (mach.graphicsAdapter.monitorCount))
    print("  Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx, "ChipsetType", mach.chipsetType), mach.chipsetType))
    print()
    print("  Clipboard mode [clipboardMode]: %s (%s)" % (asEnumElem(ctx, "ClipboardMode", mach.clipboardMode), mach.clipboardMode))
    print("  Machine status [n/a]: %s (%s)" % (asEnumElem(ctx, "SessionState", mach.sessionState), mach.sessionState))
    print()
    if mach.teleporterEnabled:
        print("  Teleport target on port %d (%s)" % (mach.teleporterPort, mach.teleporterPassword))
        print()
    bios = mach.BIOSSettings
    print("  ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(bios.ACPIEnabled)))
    print("  APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(bios.IOAPICEnabled)))
    hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
    print("  Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled))
    hwVirtVPID = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID)
    print("  VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID))
    hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging)
    print("  Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging))

    print("  Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.graphicsAdapter.accelerate3DEnabled))
    print("  Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.graphicsAdapter.accelerate2DVideoEnabled))

    print("  Use universal time [RTCUseUTC]: %s" % (asState(mach.RTCUseUTC)))
    print("  HPET [HPETEnabled]: %s" % (asState(mach.HPETEnabled)))
    if mach.audioAdapter.enabled:
        print("  Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx, "AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx, "AudioDriverType",  mach.audioAdapter.audioDriver)))
    print("  CPU hotplugging [CPUHotPlugEnabled]: %s" % (asState(mach.CPUHotPlugEnabled)))

    print("  Keyboard [keyboardHIDType]: %s (%s)" % (asEnumElem(ctx, "KeyboardHIDType", mach.keyboardHIDType), mach.keyboardHIDType))
    print("  Pointing device [pointingHIDType]: %s (%s)" % (asEnumElem(ctx, "PointingHIDType", mach.pointingHIDType), mach.pointingHIDType))
    print("  Last changed [n/a]: " + time.asctime(time.localtime(int(mach.lastStateChange)/1000)))
    # OSE has no VRDE
    try:
        print("  VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled)))
    except:
        pass

    print()
    print(colCat(ctx, "  USB Controllers:"))
    for oUsbCtrl in ctx['global'].getArray(mach, 'USBControllers'):
        print("    '%s': type %s  standard: %#x" \
            % (oUsbCtrl.name, asEnumElem(ctx, "USBControllerType", oUsbCtrl.type), oUsbCtrl.USBStandard))

    print()
    print(colCat(ctx, "  I/O subsystem info:"))
    print("   Cache enabled [IOCacheEnabled]: %s" % (asState(mach.IOCacheEnabled)))
    print("   Cache size [IOCacheSize]: %dM" % (mach.IOCacheSize))

    controllers = ctx['global'].getArray(mach, 'storageControllers')
    if controllers:
        print()
        print(colCat(ctx, "  Storage Controllers:"))
    for controller in controllers:
        print("    '%s': bus %s type %s" % (controller.name, asEnumElem(ctx, "StorageBus", controller.bus), asEnumElem(ctx, "StorageControllerType", controller.controllerType)))

    attaches = ctx['global'].getArray(mach, 'mediumAttachments')
    if attaches:
        print()
        print(colCat(ctx, "  Media:"))
    for a in attaches:
        print("   Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx, "DeviceType", a.type), a.type))
        medium = a.medium
        if a.type == ctx['global'].constants.DeviceType_HardDisk:
            print("   HDD:")
            print("    Id: %s" % (medium.id))
            print("    Location: %s" % (colPath(ctx, medium.location)))
            print("    Name: %s" % (medium.name))
            print("    Format: %s" % (medium.format))

        if a.type == ctx['global'].constants.DeviceType_DVD:
            print("   DVD:")
            if medium:
                print("    Id: %s" % (medium.id))
                print("    Name: %s" % (medium.name))
                if medium.hostDrive:
                    print("    Host DVD %s" % (colPath(ctx, medium.location)))
                    if a.passthrough:
                        print("    [passthrough mode]")
                else:
                    print("    Virtual image at %s" % (colPath(ctx, medium.location)))
                    print("    Size: %s" % (medium.size))

        if a.type == ctx['global'].constants.DeviceType_Floppy:
            print("   Floppy:")
            if medium:
                print("    Id: %s" % (medium.id))
                print("    Name: %s" % (medium.name))
                if medium.hostDrive:
                    print("    Host floppy %s" % (colPath(ctx, medium.location)))
                else:
                    print("    Virtual image at %s" % (colPath(ctx, medium.location)))
                    print("    Size: %s" % (medium.size))

    print()
    print(colCat(ctx, "  Shared folders:"))
    for sf in ctx['global'].getArray(mach, 'sharedFolders'):
        printSf(ctx, sf)

    return 0

def startCmd(ctx, args):
    if len(args) < 2:
        print("usage: start name <frontend>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    if len(args) > 2:
        vmtype = args[2]
    else:
        vmtype = "gui"
    startVm(ctx, mach, vmtype)
    return 0

def createVmCmd(ctx, args):
    if len(args) != 3:
        print("usage: createvm name ostype")
        return 0
    name = args[1]
    oskind = args[2]
    try:
        ctx['vb'].getGuestOSType(oskind)
    except Exception:
        print('Unknown OS type:', oskind)
        return 0
    createVm(ctx, name, oskind)
    return 0

def ginfoCmd(ctx, args):
    if len(args) < 2:
        print("usage: ginfo [vmname|uuid]")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'ginfo', '')
    return 0

def execInGuest(ctx, console, args, env, user, passwd, tmo, inputPipe=None, outputPipe=None):
    if len(args) < 1:
        print("exec in guest needs at least program name")
        return
    guest = console.guest
    guestSession = guest.createSession(user, passwd, "", "vboxshell guest exec")
    # shall contain program name as argv[0]
    gargs = args
    print("executing %s with args %s as %s" % (args[0], gargs, user))
    flags = 0
    if inputPipe is not None:
        flags = 1 # set WaitForProcessStartOnly
    print(args[0])
    process = guestSession.processCreate(args[0], gargs, env, [], tmo)
    print("executed with pid %d" % (process.PID))
    if pid != 0:
        try:
            while True:
                if inputPipe is not None:
                    indata = inputPipe(ctx)
                    if indata is not None:
                        write = len(indata)
                        off = 0
                        while write > 0:
                            w = guest.setProcessInput(pid, 0, 10*1000, indata[off:])
                            off = off + w
                            write = write - w
                    else:
                        # EOF
                        try:
                            guest.setProcessInput(pid, 1, 10*1000, " ")
                        except:
                            pass
                data = guest.getProcessOutput(pid, 0, 10000, 4096)
                if data and len(data) > 0:
                    sys.stdout.write(data)
                    continue
                progress.waitForCompletion(100)
                ctx['global'].waitForEvents(0)
                data = guest.getProcessOutput(pid, 0, 0, 4096)
                if data and len(data) > 0:
                    if outputPipe is not None:
                        outputPipe(ctx, data)
                    else:
                        sys.stdout.write(data)
                    continue
                if progress.completed:
                    break

        except KeyboardInterrupt:
            print("Interrupted.")
            ctx['interrupt'] = True
            if progress.cancelable:
                progress.cancel()
        (_reason, code, _flags) = guest.getProcessStatus(pid)
        print("Exit code: %d" % (code))
        return 0
    else:
        reportError(ctx, progress)

def copyToGuest(ctx, console, args, user, passwd):
    src = args[0]
    dst = args[1]
    flags = 0
    print("Copying host %s to guest %s" % (src, dst))
    progress = console.guest.copyToGuest(src, dst, user, passwd, flags)
    progressBar(ctx, progress)

def nh_raw_input(prompt=""):
    stream = sys.stdout
    prompt = str(prompt)
    if prompt:
        stream.write(prompt)
    line = sys.stdin.readline()
    if not line:
        raise EOFError
    if line[-1] == '\n':
        line = line[:-1]
    return line


def getCred(_ctx):
    import getpass
    user = getpass.getuser()
    user_inp = nh_raw_input("User (%s): " % (user))
    if len(user_inp) > 0:
        user = user_inp
    passwd = getpass.getpass()

    return (user, passwd)

def gexecCmd(ctx, args):
    if len(args) < 2:
        print("usage: gexec [vmname|uuid] command args")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    gargs = args[2:]
    env = [] # ["DISPLAY=:0"]
    (user, passwd) = getCred(ctx)
    gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000))
    cmdExistingVm(ctx, mach, 'guestlambda', gargs)
    return 0

def gcopyCmd(ctx, args):
    if len(args) < 2:
        print("usage: gcopy [vmname|uuid] host_path guest_path")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    gargs = args[2:]
    (user, passwd) = getCred(ctx)
    gargs.insert(0, lambda ctx, mach, console, args: copyToGuest(ctx, console, args, user, passwd))
    cmdExistingVm(ctx, mach, 'guestlambda', gargs)
    return 0

def readCmdPipe(ctx, _hcmd):
    try:
        return ctx['process'].communicate()[0]
    except:
        return None

def gpipeCmd(ctx, args):
    if len(args) < 4:
        print("usage: gpipe [vmname|uuid] hostProgram guestProgram, such as gpipe linux  '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    hcmd = args[2]
    gcmd = args[3]
    (user, passwd) = getCred(ctx)
    import subprocess
    ctx['process'] = subprocess.Popen(split_no_quotes(hcmd), stdout=subprocess.PIPE)
    gargs = split_no_quotes(gcmd)
    env = []
    gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000, lambda ctx:readCmdPipe(ctx, hcmd)))
    cmdExistingVm(ctx, mach, 'guestlambda', gargs)
    try:
        ctx['process'].terminate()
    except:
        pass
    ctx['process'] = None
    return 0


def removeVmCmd(ctx, args):
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    removeVm(ctx, mach)
    return 0

def pauseCmd(ctx, args):
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'pause', '')
    return 0

def powerdownCmd(ctx, args):
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'powerdown', '')
    return 0

def powerbuttonCmd(ctx, args):
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'powerbutton', '')
    return 0

def resumeCmd(ctx, args):
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'resume', '')
    return 0

def saveCmd(ctx, args):
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'save', '')
    return 0

def statsCmd(ctx, args):
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'stats', '')
    return 0

def guestCmd(ctx, args):
    if len(args) < 3:
        print("usage: guest name commands")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    if mach.state != ctx['const'].MachineState_Running:
        cmdClosedVm(ctx, mach, lambda ctx, mach, a: guestExec (ctx, mach, None, ' '.join(args[2:])))
    else:
        cmdExistingVm(ctx, mach, 'guest', ' '.join(args[2:]))
    return 0

def screenshotCmd(ctx, args):
    if len(args) < 2:
        print("usage: screenshot vm <file> <width> <height> <monitor>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'screenshot', args[2:])
    return 0

def teleportCmd(ctx, args):
    if len(args) < 3:
        print("usage: teleport name host:port <password>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'teleport', args[2:])
    return 0

def portalsettings(_ctx, mach, args):
    enabled = args[0]
    mach.teleporterEnabled = enabled
    if enabled:
        port = args[1]
        passwd = args[2]
        mach.teleporterPort = port
        mach.teleporterPassword = passwd

def openportalCmd(ctx, args):
    if len(args) < 3:
        print("usage: openportal name port <password>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    port = int(args[2])
    if len(args) > 3:
        passwd = args[3]
    else:
        passwd = ""
    if not mach.teleporterEnabled or mach.teleporterPort != port or passwd:
        cmdClosedVm(ctx, mach, portalsettings, [True, port, passwd])
    startVm(ctx, mach, "gui")
    return 0

def closeportalCmd(ctx, args):
    if len(args) < 2:
        print("usage: closeportal name")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    if mach.teleporterEnabled:
        cmdClosedVm(ctx, mach, portalsettings, [False])
    return 0

def gueststatsCmd(ctx, args):
    if len(args) < 2:
        print("usage: gueststats name <check interval>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'gueststats', args[2:])
    return 0

def plugcpu(_ctx, mach, args):
    plug = args[0]
    cpu = args[1]
    if plug:
        print("Adding CPU %d..." % (cpu))
        mach.hotPlugCPU(cpu)
    else:
        print("Removing CPU %d..." % (cpu))
        mach.hotUnplugCPU(cpu)

def plugcpuCmd(ctx, args):
    if len(args) < 2:
        print("usage: plugcpu name cpuid")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    if str(mach.sessionState) != str(ctx['const'].SessionState_Locked):
        if mach.CPUHotPlugEnabled:
            cmdClosedVm(ctx, mach, plugcpu, [True, int(args[2])])
    else:
        cmdExistingVm(ctx, mach, 'plugcpu', args[2])
    return 0

def unplugcpuCmd(ctx, args):
    if len(args) < 2:
        print("usage: unplugcpu name cpuid")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    if str(mach.sessionState) != str(ctx['const'].SessionState_Locked):
        if mach.CPUHotPlugEnabled:
            cmdClosedVm(ctx, mach, plugcpu, [False, int(args[2])])
    else:
        cmdExistingVm(ctx, mach, 'unplugcpu', args[2])
    return 0

def setvar(_ctx, _mach, args):
    expr = 'mach.'+args[0]+' = '+args[1]
    print("Executing", expr)
    exec(expr)

def setvarCmd(ctx, args):
    if len(args) < 4:
        print("usage: setvar [vmname|uuid] expr value")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdClosedVm(ctx, mach, setvar, args[2:])
    return 0

def setvmextra(_ctx, mach, args):
    key = args[0]
    value = args[1]
    print("%s: setting %s to %s" % (mach.name, key, value if value else None))
    mach.setExtraData(key, value)

def setExtraDataCmd(ctx, args):
    if len(args) < 3:
        print("usage: setextra [vmname|uuid|global] key <value>")
        return 0
    key = args[2]
    if len(args) == 4:
        value = args[3]
    else:
        value = ''
    if args[1] == 'global':
        ctx['vb'].setExtraData(key, value)
        return 0

    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdClosedVm(ctx, mach, setvmextra, [key, value])
    return 0

def printExtraKey(obj, key, value):
    print("%s: '%s' = '%s'" % (obj, key, value))

def getExtraDataCmd(ctx, args):
    if len(args) < 2:
        print("usage: getextra [vmname|uuid|global] <key>")
        return 0
    if len(args) == 3:
        key = args[2]
    else:
        key = None

    if args[1] == 'global':
        obj = ctx['vb']
    else:
        obj = argsToMach(ctx, args)
        if obj == None:
            return 0

    if key == None:
        keys = obj.getExtraDataKeys()
    else:
        keys = [ key ]
    for k in keys:
        printExtraKey(args[1], k, obj.getExtraData(k))

    return 0

def quitCmd(_ctx, _args):
    return 1

def aliasCmd(ctx, args):
    if len(args) == 3:
        aliases[args[1]] = args[2]
        return 0

    for (key, value) in list(aliases.items()):
        print("'%s' is an alias for '%s'" % (key, value))
    return 0

def verboseCmd(ctx, args):
    global g_fVerbose
    if len(args) > 1:
        g_fVerbose = (args[1]=='on')
    else:
        g_fVerbose = not g_fVerbose
    return 0

def colorsCmd(ctx, args):
    global g_fHasColors
    if len(args) > 1:
        g_fHasColors = (args[1] == 'on')
    else:
        g_fHasColors = not g_fHasColors
    return 0

def hostCmd(ctx, args):
    vbox = ctx['vb']
    try:
        print("VirtualBox version %s" % (colored(vbox.version, 'blue')))
    except Exception as e:
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()
    props = vbox.systemProperties
    print("Machines: %s" % (colPath(ctx, props.defaultMachineFolder)))

    #print("Global shared folders:")
    #for ud in ctx['global'].getArray(vbox, 'sharedFolders'):
    #    printSf(ctx, sf)
    host = vbox.host
    cnt = host.processorCount
    print(colCat(ctx, "Processors:"))
    print("  available/online: %d/%d " % (cnt, host.processorOnlineCount))
    for i in range(0, cnt):
        print("  processor #%d speed: %dMHz %s" % (i, host.getProcessorSpeed(i), host.getProcessorDescription(i)))

    print(colCat(ctx, "RAM:"))
    print("  %dM (free %dM)" % (host.memorySize, host.memoryAvailable))
    print(colCat(ctx, "OS:"))
    print("  %s (%s)" % (host.operatingSystem, host.OSVersion))
    if host.acceleration3DAvailable:
        print(colCat(ctx, "3D acceleration available"))
    else:
        print(colCat(ctx, "3D acceleration NOT available"))

    print(colCat(ctx, "Network interfaces:"))
    for ni in ctx['global'].getArray(host, 'networkInterfaces'):
        print("  %s (%s)" % (ni.name, ni.IPAddress))

    print(colCat(ctx, "DVD drives:"))
    for dd in ctx['global'].getArray(host, 'DVDDrives'):
        print("  %s - %s" % (dd.name, dd.description))

    print(colCat(ctx, "Floppy drives:"))
    for dd in ctx['global'].getArray(host, 'floppyDrives'):
        print("  %s - %s" % (dd.name, dd.description))

    print(colCat(ctx, "USB devices:"))
    for ud in ctx['global'].getArray(host, 'USBDevices'):
        printHostUsbDev(ctx, ud)

    if ctx['perf']:
        for metric in ctx['perf'].query(["*"], [host]):
            print(metric['name'], metric['values_as_string'])

    return 0

def monitorGuestCmd(ctx, args):
    if len(args) < 2:
        print("usage: monitorGuest name (duration)")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    dur = 5
    if len(args) > 2:
        dur = float(args[2])
    active = False
    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  monitorSource(ctx, console.eventSource, active, dur)])
    return 0

def monitorGuestKbdCmd(ctx, args):
    if len(args) < 2:
        print("usage: monitorGuestKbd name (duration)")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    dur = 5
    if len(args) > 2:
        dur = float(args[2])
    active = False
    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  monitorSource(ctx, console.keyboard.eventSource, active, dur)])
    return 0

def monitorGuestMouseCmd(ctx, args):
    if len(args) < 2:
        print("usage: monitorGuestMouse name (duration)")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    dur = 5
    if len(args) > 2:
        dur = float(args[2])
    active = False
    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  monitorSource(ctx, console.mouse.eventSource, active, dur)])
    return 0

def monitorGuestMultiTouchCmd(ctx, args):
    if len(args) < 2:
        print("usage: monitorGuestMultiTouch name (duration)")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    dur = 5
    if len(args) > 2:
        dur = float(args[2])
    active = False
    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  monitorSource(ctx, console.mouse.eventSource, active, dur)])
    return 0

def monitorVBoxCmd(ctx, args):
    if len(args) > 2:
        print("usage: monitorVBox (duration)")
        return 0
    dur = 5
    if len(args) > 1:
        dur = float(args[1])
    vbox = ctx['vb']
    active = False
    monitorSource(ctx, vbox.eventSource, active, dur)
    return 0

def getAdapterType(ctx, natype):
    if (natype == ctx['global'].constants.NetworkAdapterType_Am79C970A or
        natype == ctx['global'].constants.NetworkAdapterType_Am79C973 or
        natype == ctx['global'].constants.NetworkAdapterType_Am79C960):
        return "pcnet"
    elif (natype == ctx['global'].constants.NetworkAdapterType_I82540EM or
          natype == ctx['global'].constants.NetworkAdapterType_I82545EM or
          natype == ctx['global'].constants.NetworkAdapterType_I82543GC):
        return "e1000"
    elif (natype == ctx['global'].constants.NetworkAdapterType_Virtio):
        return "virtio"
    elif (natype == ctx['global'].constants.NetworkAdapterType_Virtio_1_0):
        return "virtio_1.0"
    elif (natype == ctx['global'].constants.NetworkAdapterType_Null):
        return None
    else:
        raise Exception("Unknown adapter type: "+natype)


def portForwardCmd(ctx, args):
    if len(args) != 5:
        print("usage: portForward <vm> <adapter> <hostPort> <guestPort>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    adapterNum = int(args[2])
    hostPort = int(args[3])
    guestPort = int(args[4])
    proto = "TCP"
    session = ctx['global'].openMachineSession(mach, fPermitSharing=True)
    mach = session.machine

    adapter = mach.getNetworkAdapter(adapterNum)
    adapterType = getAdapterType(ctx, adapter.adapterType)

    profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
    config = "VBoxInternal/Devices/" + adapterType + "/"
    config = config + str(adapter.slot)  +"/LUN#0/Config/" + profile_name

    mach.setExtraData(config + "/Protocol", proto)
    mach.setExtraData(config + "/HostPort", str(hostPort))
    mach.setExtraData(config + "/GuestPort", str(guestPort))

    mach.saveSettings()
    session.unlockMachine()

    return 0


def showLogCmd(ctx, args):
    if len(args) < 2:
        print("usage: showLog vm <num>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0

    log = 0
    if len(args) > 2:
        log = args[2]

    uOffset = 0
    while True:
        data = mach.readLog(log, uOffset, 4096)
        if len(data) == 0:
            break
        # print adds either NL or space to chunks not ending with a NL
        sys.stdout.write(str(data))
        uOffset += len(data)

    return 0

def findLogCmd(ctx, args):
    if len(args) < 3:
        print("usage: findLog vm pattern <num>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0

    log = 0
    if len(args) > 3:
        log = args[3]

    pattern = args[2]
    uOffset = 0
    while True:
        # to reduce line splits on buffer boundary
        data = mach.readLog(log, uOffset, 512*1024)
        if len(data) == 0:
            break
        d = str(data).split("\n")
        for s in d:
            match = re.findall(pattern, s)
            if len(match) > 0:
                for mt in match:
                    s = s.replace(mt, colored(mt, 'red'))
                print(s)
        uOffset += len(data)

    return 0


def findAssertCmd(ctx, args):
    if len(args) < 2:
        print("usage: findAssert vm <num>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0

    log = 0
    if len(args) > 2:
        log = args[2]

    uOffset = 0
    ere = re.compile(r'(Expression:|\!\!\!\!\!\!)')
    active = False
    context = 0
    while True:
        # to reduce line splits on buffer boundary
        data = mach.readLog(log, uOffset, 512*1024)
        if len(data) == 0:
            break
        d = str(data).split("\n")
        for s in d:
            if active:
                print(s)
                if context == 0:
                    active = False
                else:
                    context = context - 1
                continue
            match = ere.findall(s)
            if len(match) > 0:
                active = True
                context = 50
                print(s)
        uOffset += len(data)

    return 0

def evalCmd(ctx, args):
    expr = ' '.join(args[1:])
    try:
        exec(expr)
    except Exception as e:
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()
    return 0

def reloadExtCmd(ctx, args):
    # maybe will want more args smartness
    checkUserExtensions(ctx, commands, getHomeFolder(ctx))
    autoCompletion(commands, ctx)
    return 0

def runScriptCmd(ctx, args):
    if len(args) != 2:
        print("usage: runScript <script>")
        return 0
    try:
        lf = open(args[1], 'r')
    except IOError as e:
        print("cannot open:", args[1], ":", e)
        return 0

    try:
        lines = lf.readlines()
        ctx['scriptLine'] = 0
        ctx['interrupt'] = False
        while ctx['scriptLine'] < len(lines):
            line = lines[ctx['scriptLine']]
            ctx['scriptLine'] = ctx['scriptLine'] + 1
            done = runCommand(ctx, line)
            if done != 0 or ctx['interrupt']:
                break

    except Exception as e:
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()
    lf.close()
    return 0

def sleepCmd(ctx, args):
    if len(args) != 2:
        print("usage: sleep <secs>")
        return 0

    try:
        time.sleep(float(args[1]))
    except:
        # to allow sleep interrupt
        pass
    return 0


def shellCmd(ctx, args):
    if len(args) < 2:
        print("usage: shell <commands>")
        return 0
    cmd = ' '.join(args[1:])

    try:
        os.system(cmd)
    except KeyboardInterrupt:
        # to allow shell command interruption
        pass
    return 0


def connectCmd(ctx, args):
    if len(args) > 4:
        print("usage: connect url <username> <passwd>")
        return 0

    if ctx['vb'] is not None:
        print("Already connected, disconnect first...")
        return 0

    if len(args) > 1:
        url = args[1]
    else:
        url = None

    if len(args) > 2:
        user = args[2]
    else:
        user = ""

    if len(args) > 3:
        passwd = args[3]
    else:
        passwd = ""

    ctx['wsinfo'] = [url, user, passwd]
    ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
    try:
        print("Running VirtualBox version %s" % (ctx['vb'].version))
    except Exception as e:
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()
    ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
    return 0

def disconnectCmd(ctx, args):
    if len(args) != 1:
        print("usage: disconnect")
        return 0

    if ctx['vb'] is None:
        print("Not connected yet.")
        return 0

    try:
        ctx['global'].platform.disconnect()
    except:
        ctx['vb'] = None
        raise

    ctx['vb'] = None
    return 0

def reconnectCmd(ctx, args):
    if ctx['wsinfo'] is None:
        print("Never connected...")
        return 0

    try:
        ctx['global'].platform.disconnect()
    except:
        pass

    [url, user, passwd] = ctx['wsinfo']
    ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
    try:
        print("Running VirtualBox version %s" % (ctx['vb'].version))
    except Exception as e:
        printErr(ctx, e)
        if g_fVerbose:
            traceback.print_exc()
    ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
    return 0

def exportVMCmd(ctx, args):
    if len(args) < 3:
        print("usage: exportVm <machine> <path> <format> <license>")
        return 0
    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    path = args[2]
    if len(args) > 3:
        fmt = args[3]
    else:
        fmt = "ovf-1.0"
    if len(args) > 4:
        lic = args[4]
    else:
        lic = "GPL"

    app = ctx['vb'].createAppliance()
    desc = mach.export(app)
    desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, lic, "")
    progress = app.write(fmt, path)
    if (progressBar(ctx, progress) and int(progress.resultCode) == 0):
        print("Exported to %s in format %s" % (path, fmt))
    else:
        reportError(ctx, progress)
    return 0

# PC XT scancodes
scancodes = {
    'a':  0x1e,
    'b':  0x30,
    'c':  0x2e,
    'd':  0x20,
    'e':  0x12,
    'f':  0x21,
    'g':  0x22,
    'h':  0x23,
    'i':  0x17,
    'j':  0x24,
    'k':  0x25,
    'l':  0x26,
    'm':  0x32,
    'n':  0x31,
    'o':  0x18,
    'p':  0x19,
    'q':  0x10,
    'r':  0x13,
    's':  0x1f,
    't':  0x14,
    'u':  0x16,
    'v':  0x2f,
    'w':  0x11,
    'x':  0x2d,
    'y':  0x15,
    'z':  0x2c,
    '0':  0x0b,
    '1':  0x02,
    '2':  0x03,
    '3':  0x04,
    '4':  0x05,
    '5':  0x06,
    '6':  0x07,
    '7':  0x08,
    '8':  0x09,
    '9':  0x0a,
    ' ':  0x39,
    '-':  0xc,
    '=':  0xd,
    '[':  0x1a,
    ']':  0x1b,
    ';':  0x27,
    '\'': 0x28,
    ',':  0x33,
    '.':  0x34,
    '/':  0x35,
    '\t': 0xf,
    '\n': 0x1c,
    '`':  0x29
}

extScancodes = {
    'ESC' :    [0x01],
    'BKSP':    [0xe],
    'SPACE':   [0x39],
    'TAB':     [0x0f],
    'CAPS':    [0x3a],
    'ENTER':   [0x1c],
    'LSHIFT':  [0x2a],
    'RSHIFT':  [0x36],
    'INS':     [0xe0, 0x52],
    'DEL':     [0xe0, 0x53],
    'END':     [0xe0, 0x4f],
    'HOME':    [0xe0, 0x47],
    'PGUP':    [0xe0, 0x49],
    'PGDOWN':  [0xe0, 0x51],
    'LGUI':    [0xe0, 0x5b], # GUI, aka Win, aka Apple key
    'RGUI':    [0xe0, 0x5c],
    'LCTR':    [0x1d],
    'RCTR':    [0xe0, 0x1d],
    'LALT':    [0x38],
    'RALT':    [0xe0, 0x38],
    'APPS':    [0xe0, 0x5d],
    'F1':      [0x3b],
    'F2':      [0x3c],
    'F3':      [0x3d],
    'F4':      [0x3e],
    'F5':      [0x3f],
    'F6':      [0x40],
    'F7':      [0x41],
    'F8':      [0x42],
    'F9':      [0x43],
    'F10':     [0x44 ],
    'F11':     [0x57],
    'F12':     [0x58],
    'UP':      [0xe0, 0x48],
    'LEFT':    [0xe0, 0x4b],
    'DOWN':    [0xe0, 0x50],
    'RIGHT':   [0xe0, 0x4d],
}

def keyDown(ch):
    code = scancodes.get(ch, 0x0)
    if code != 0:
        return [code]
    extCode = extScancodes.get(ch, [])
    if len(extCode) == 0:
        print("bad ext", ch)
    return extCode

def keyUp(ch):
    codes = keyDown(ch)[:] # make a copy
    if len(codes) > 0:
        codes[len(codes)-1] += 0x80
    return codes

def typeInGuest(console, text, delay):
    pressed = []
    group = False
    modGroupEnd = True
    i = 0
    kbd = console.keyboard
    while i < len(text):
        ch = text[i]
        i = i+1
        if ch == '{':
            # start group, all keys to be pressed at the same time
            group = True
            continue
        if ch == '}':
            # end group, release all keys
            for c in pressed:
                kbd.putScancodes(keyUp(c))
            pressed = []
            group = False
            continue
        if ch == 'W':
            # just wait a bit
            time.sleep(0.3)
            continue
        if  ch == '^' or  ch == '|' or ch == '$' or ch == '_':
            if ch == '^':
                ch = 'LCTR'
            if ch == '|':
                ch = 'LSHIFT'
            if ch == '_':
                ch = 'LALT'
            if ch == '$':
                ch = 'LGUI'
            if not group:
                modGroupEnd = False
        else:
            if ch == '\\':
                if i < len(text):
                    ch = text[i]
                    i = i+1
                    if ch == 'n':
                        ch = '\n'
            elif ch == '&':
                combo = ""
                while i  < len(text):
                    ch = text[i]
                    i = i+1
                    if ch == ';':
                        break
                    combo += ch
                ch = combo
            modGroupEnd = True
        kbd.putScancodes(keyDown(ch))
        pressed.insert(0, ch)
        if not group and modGroupEnd:
            for c in pressed:
                kbd.putScancodes(keyUp(c))
            pressed = []
            modGroupEnd = True
        time.sleep(delay)

def typeGuestCmd(ctx, args):
    if len(args) < 3:
        print("usage: typeGuest <machine> <text> <charDelay>")
        return 0
    mach = argsToMach(ctx, args)
    if mach is None:
        return 0

    text = args[2]

    if len(args) > 3:
        delay = float(args[3])
    else:
        delay = 0.1

    gargs = [lambda ctx, mach, console, args: typeInGuest(console, text, delay)]
    cmdExistingVm(ctx, mach, 'guestlambda', gargs)

    return 0

def optId(verbose, uuid):
    if verbose:
        return ": "+uuid
    else:
        return ""

def asSize(val, inBytes):
    if inBytes:
        return int(val)/(1024*1024)
    else:
        return int(val)

def listMediaCmd(ctx, args):
    if len(args) > 1:
        verbose = int(args[1])
    else:
        verbose = False
    hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
    print(colCat(ctx, "Hard disks:"))
    for hdd in hdds:
        if hdd.state != ctx['global'].constants.MediumState_Created:
            hdd.refreshState()
        print("   %s (%s)%s %s [logical %s]" % (colPath(ctx, hdd.location), hdd.format, optId(verbose, hdd.id), colSizeM(ctx, asSize(hdd.size, True)), colSizeM(ctx, asSize(hdd.logicalSize, True))))

    dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
    print(colCat(ctx, "CD/DVD disks:"))
    for dvd in dvds:
        if dvd.state != ctx['global'].constants.MediumState_Created:
            dvd.refreshState()
        print("   %s (%s)%s %s" % (colPath(ctx, dvd.location), dvd.format, optId(verbose, dvd.id), colSizeM(ctx, asSize(dvd.size, True))))

    floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
    print(colCat(ctx, "Floppy disks:"))
    for floppy in floppys:
        if floppy.state != ctx['global'].constants.MediumState_Created:
            floppy.refreshState()
        print("   %s (%s)%s %s" % (colPath(ctx, floppy.location), floppy.format, optId(verbose, floppy.id), colSizeM(ctx, asSize(floppy.size, True))))

    return 0

def listUsbCmd(ctx, args):
    if len(args) > 1:
        print("usage: listUsb")
        return 0

    host = ctx['vb'].host
    for ud in ctx['global'].getArray(host, 'USBDevices'):
        printHostUsbDev(ctx, ud)

    return 0

def findDevOfType(ctx, mach, devtype):
    atts = ctx['global'].getArray(mach, 'mediumAttachments')
    for a in atts:
        if a.type == devtype:
            return [a.controller, a.port, a.device]
    return [None, 0, 0]

def createHddCmd(ctx, args):
    if len(args) < 3:
        print("usage: createHdd sizeM location type")
        return 0

    size = int(args[1])
    loc = args[2]
    if len(args) > 3:
        fmt = args[3]
    else:
        fmt = "vdi"

    hdd = ctx['vb'].createMedium(fmt, loc, ctx['global'].constants.AccessMode_ReadWrite, ctx['global'].constants.DeviceType_HardDisk)
    progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, ))
    if progressBar(ctx,progress) and hdd.id:
        print("created HDD at %s as %s" % (colPath(ctx,hdd.location), hdd.id))
    else:
       print("cannot create disk (file %s exist?)" % (loc))
       reportError(ctx,progress)
       return 0

    return 0

def registerHddCmd(ctx, args):
    if len(args) < 2:
        print("usage: registerHdd location")
        return 0

    vbox = ctx['vb']
    loc = args[1]
    setImageId = False
    imageId = ""
    setParentId = False
    parentId = ""
    hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    print("registered HDD as %s" % (hdd.id))
    return 0

def controldevice(ctx, mach, args):
    [ctr, port, slot, devtype, uuid] = args
    mach.attachDevice(ctr, port, slot, devtype, uuid)

def attachHddCmd(ctx, args):
    if len(args) < 3:
        print("usage: attachHdd vm hdd controller port:slot")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    vbox = ctx['vb']
    loc = args[2]
    try:
        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    except:
        print("no HDD with path %s registered" % (loc))
        return 0
    if len(args) > 3:
        ctr = args[3]
        (port, slot) = args[4].split(":")
    else:
        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)

    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk, hdd.id))
    return 0

def detachVmDevice(ctx, mach, args):
    atts = ctx['global'].getArray(mach, 'mediumAttachments')
    hid = args[0]
    for a in atts:
        if a.medium:
            if hid == "ALL" or a.medium.id == hid:
                mach.detachDevice(a.controller, a.port, a.device)

def detachMedium(ctx, mid, medium):
    cmdClosedVm(ctx, machById(ctx, mid), detachVmDevice, [medium])

def detachHddCmd(ctx, args):
    if len(args) < 3:
        print("usage: detachHdd vm hdd")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    vbox = ctx['vb']
    loc = args[2]
    try:
        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    except:
        print("no HDD with path %s registered" % (loc))
        return 0

    detachMedium(ctx, mach.id, hdd)
    return 0

def unregisterHddCmd(ctx, args):
    if len(args) < 2:
        print("usage: unregisterHdd path <vmunreg>")
        return 0

    vbox = ctx['vb']
    loc = args[1]
    if len(args) > 2:
        vmunreg = int(args[2])
    else:
        vmunreg = 0
    try:
        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    except:
        print("no HDD with path %s registered" % (loc))
        return 0

    if vmunreg != 0:
        machs = ctx['global'].getArray(hdd, 'machineIds')
        try:
            for mach in machs:
                print("Trying to detach from %s" % (mach))
                detachMedium(ctx, mach, hdd)
        except Exception as e:
            print('failed: ', e)
            return 0
    hdd.close()
    return 0

def removeHddCmd(ctx, args):
    if len(args) != 2:
        print("usage: removeHdd path")
        return 0

    vbox = ctx['vb']
    loc = args[1]
    try:
        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    except:
        print("no HDD with path %s registered" % (loc))
        return 0

    progress = hdd.deleteStorage()
    progressBar(ctx, progress)

    return 0

def registerIsoCmd(ctx, args):
    if len(args) < 2:
        print("usage: registerIso location")
        return 0

    vbox = ctx['vb']
    loc = args[1]
    iso = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    print("registered ISO as %s" % (iso.id))
    return 0

def unregisterIsoCmd(ctx, args):
    if len(args) != 2:
        print("usage: unregisterIso path")
        return 0

    vbox = ctx['vb']
    loc = args[1]
    try:
        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    except:
        print("no DVD with path %s registered" % (loc))
        return 0

    progress = dvd.close()
    print("Unregistered ISO at %s" % (colPath(ctx, loc)))

    return 0

def removeIsoCmd(ctx, args):
    if len(args) != 2:
        print("usage: removeIso path")
        return 0

    vbox = ctx['vb']
    loc = args[1]
    try:
        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    except:
        print("no DVD with path %s registered" % (loc))
        return 0

    progress = dvd.deleteStorage()
    if progressBar(ctx, progress):
        print("Removed ISO at %s" % (colPath(ctx, dvd.location)))
    else:
        reportError(ctx, progress)
    return 0

def attachIsoCmd(ctx, args):
    if len(args) < 3:
        print("usage: attachIso vm iso controller port:slot")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    vbox = ctx['vb']
    loc = args[2]
    try:
        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    except:
        print("no DVD with path %s registered" % (loc))
        return 0
    if len(args) > 3:
        ctr = args[3]
        (port, slot) = args[4].split(":")
    else:
        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd))
    return 0

def detachIsoCmd(ctx, args):
    if len(args) < 3:
        print("usage: detachIso vm iso")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    vbox = ctx['vb']
    loc = args[2]
    try:
        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    except:
        print("no DVD with path %s registered" % (loc))
        return 0

    detachMedium(ctx, mach.id, dvd)
    return 0

def mountIsoCmd(ctx, args):
    if len(args) < 3:
        print("usage: mountIso vm iso controller port:slot")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    vbox = ctx['vb']
    loc = args[2]
    try:
        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    except:
        print("no DVD with path %s registered" % (loc))
        return 0

    if len(args) > 3:
        ctr = args[3]
        (port, slot) = args[4].split(":")
    else:
        # autodetect controller and location, just find first controller with media == DVD
        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)

    cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd, True])

    return 0

def unmountIsoCmd(ctx, args):
    if len(args) < 2:
        print("usage: unmountIso vm controller port:slot")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    vbox = ctx['vb']

    if len(args) > 3:
        ctr = args[2]
        (port, slot) = args[3].split(":")
    else:
        # autodetect controller and location, just find first controller with media == DVD
        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)

    cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, None, True])

    return 0

def attachCtr(ctx, mach, args):
    [name, bus, ctrltype] = args
    ctr = mach.addStorageController(name, bus)
    if ctrltype != None:
        ctr.controllerType = ctrltype

def attachCtrCmd(ctx, args):
    if len(args) < 4:
        print("usage: attachCtr vm cname bus <type>")
        return 0

    if len(args) > 4:
        ctrltype = enumFromString(ctx, 'StorageControllerType', args[4])
        if ctrltype == None:
            print("Controller type %s unknown" % (args[4]))
            return 0
    else:
        ctrltype = None

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    bus = enumFromString(ctx, 'StorageBus', args[3])
    if bus is None:
        print("Bus type %s unknown" % (args[3]))
        return 0
    name = args[2]
    cmdClosedVm(ctx, mach, attachCtr, [name, bus, ctrltype])
    return 0

def detachCtrCmd(ctx, args):
    if len(args) < 3:
        print("usage: detachCtr vm name")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    ctr = args[2]
    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeStorageController(ctr))
    return 0

def usbctr(ctx, mach, console, args):
    if args[0]:
        console.attachUSBDevice(args[1], "")
    else:
        console.detachUSBDevice(args[1])

def attachUsbCmd(ctx, args):
    if len(args) < 3:
        print("usage: attachUsb vm deviceuid")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    dev = args[2]
    cmdExistingVm(ctx, mach, 'guestlambda', [usbctr, True, dev])
    return 0

def detachUsbCmd(ctx, args):
    if len(args) < 3:
        print("usage: detachUsb vm deviceuid")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    dev = args[2]
    cmdExistingVm(ctx, mach, 'guestlambda', [usbctr, False, dev])
    return 0


def guiCmd(ctx, args):
    if len(args) > 1:
        print("usage: gui")
        return 0

    binDir = ctx['global'].getBinDir()

    vbox = os.path.join(binDir, 'VirtualBox')
    try:
        os.system(vbox)
    except KeyboardInterrupt:
        # to allow interruption
        pass
    return 0

def shareFolderCmd(ctx, args):
    if len(args) < 4:
        print("usage: shareFolder vm path name <writable> <persistent>")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    path = args[2]
    name = args[3]
    writable = False
    persistent = False
    if len(args) > 4:
        for a in args[4:]:
            if a == 'writable':
                writable = True
            if a == 'persistent':
                persistent = True
    if persistent:
        cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.createSharedFolder(name, path, writable), [])
    else:
        cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: console.createSharedFolder(name, path, writable)])
    return 0

def unshareFolderCmd(ctx, args):
    if len(args) < 3:
        print("usage: unshareFolder vm name")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    name = args[2]
    found = False
    for sf in ctx['global'].getArray(mach, 'sharedFolders'):
        if sf.name == name:
            cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeSharedFolder(name), [])
            found = True
            break
    if not found:
        cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: console.removeSharedFolder(name)])
    return 0


def snapshotCmd(ctx, args):
    if (len(args) < 2 or args[1] == 'help'):
        print("Take snapshot:    snapshot vm take name <description>")
        print("Restore snapshot: snapshot vm restore name")
        print("Merge snapshot:   snapshot vm merge name")
        return 0

    mach = argsToMach(ctx, args)
    if mach is None:
        return 0
    cmd = args[2]
    if cmd == 'take':
        if len(args) < 4:
            print("usage: snapshot vm take name <description>")
            return 0
        name = args[3]
        if len(args) > 4:
            desc = args[4]
        else:
            desc = ""
        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, mach.takeSnapshot(name, desc, True)[0]))
        return 0

    if cmd == 'restore':
        if len(args) < 4:
            print("usage: snapshot vm restore name")
            return 0
        name = args[3]
        snap = mach.findSnapshot(name)
        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, mach.restoreSnapshot(snap)))
        return 0

    if cmd == 'restorecurrent':
        if len(args) < 4:
            print("usage: snapshot vm restorecurrent")
            return 0
        snap = mach.currentSnapshot()
        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, mach.restoreSnapshot(snap)))
        return 0

    if cmd == 'delete':
        if len(args) < 4:
            print("usage: snapshot vm delete name")
            return 0
        name = args[3]
        snap = mach.findSnapshot(name)
        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, mach.deleteSnapshot(snap.id)))
        return 0

    print("Command '%s' is unknown" % (cmd))
    return 0

def natAlias(ctx, mach, nicnum, nat, args=[]):
    """This command shows/alters NAT's alias settings.
    usage: nat <vm> <nicnum> alias [default|[log] [proxyonly] [sameports]]
    default - set settings to default values
    log - switch on alias logging
    proxyonly - switch proxyonly mode on
    sameports - enforces NAT using the same ports
    """
    alias = {
        'log': 0x1,
        'proxyonly': 0x2,
        'sameports': 0x4
    }
    if len(args) == 1:
        first = 0
        msg = ''
        for aliasmode, aliaskey in list(alias.items()):
            if first == 0:
                first = 1
            else:
                msg += ', '
            if int(nat.aliasMode) & aliaskey:
                msg += '%s: %s' % (aliasmode, 'on')
            else:
                msg += '%s: %s' % (aliasmode, 'off')
        return (0, [msg])
    else:
        nat.aliasMode = 0
        if 'default' not in args:
            for a in range(1, len(args)):
                if args[a] not in alias:
                    print('Invalid alias mode: ' + args[a])
                    print(natAlias.__doc__)
                    return (1, None)
                nat.aliasMode = int(nat.aliasMode) | alias[args[a]]
    return (0, None)

def natSettings(ctx, mach, nicnum, nat, args):
    """This command shows/alters NAT settings.
    usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
    mtu - set mtu <= 16000
    socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
    tcpsndwnd/tcprcvwnd - sets size of initial tcp sending/receiving window
    """
    if len(args) == 1:
        (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings()
        if mtu == 0: mtu = 1500
        if socksndbuf == 0: socksndbuf = 64
        if sockrcvbuf == 0: sockrcvbuf = 64
        if tcpsndwnd == 0: tcpsndwnd = 64
        if tcprcvwnd == 0: tcprcvwnd = 64
        msg = 'mtu:%s socket(snd:%s, rcv:%s) tcpwnd(snd:%s, rcv:%s)' % (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd)
        return (0, [msg])
    else:
        if args[1] < 16000:
            print('invalid mtu value (%s not in range [65 - 16000])' % (args[1]))
            return (1, None)
        for i in range(2, len(args)):
            if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024:
                print('invalid %s parameter (%i not in range [8-1024])' % (i, args[i]))
                return (1, None)
        a = [args[1]]
        if len(args) < 6:
            for i in range(2, len(args)): a.append(args[i])
            for i in range(len(args), 6): a.append(0)
        else:
            for i in range(2, len(args)): a.append(args[i])
        #print(a)
        nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))
    return (0, None)

def natDns(ctx, mach, nicnum, nat, args):
    """This command shows/alters DNS's NAT settings
    usage: nat <vm> <nicnum> dns [passdomain] [proxy] [usehostresolver]
    passdomain - enforces builtin DHCP server to pass domain
    proxy - switch on builtin NAT DNS proxying mechanism
    usehostresolver - proxies all DNS requests to Host Resolver interface
    """
    yesno = {0: 'off', 1: 'on'}
    if len(args) == 1:
        msg = 'passdomain:%s, proxy:%s, usehostresolver:%s' % (yesno[int(nat.DNSPassDomain)], yesno[int(nat.DNSProxy)], yesno[int(nat.DNSUseHostResolver)])
        return (0, [msg])
    else:
        nat.DNSPassDomain = 'passdomain' in args
        nat.DNSProxy = 'proxy' in args
        nat.DNSUseHostResolver = 'usehostresolver' in args
    return (0, None)

def natTftp(ctx, mach, nicnum, nat, args):
    """This command shows/alters TFTP settings
    usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
    prefix - alters prefix TFTP settings
    bootfile - alters bootfile TFTP settings
    server - sets booting server
    """
    if len(args) == 1:
        server = nat.TFTPNextServer
        if server is None:
            server = nat.network
            if server is None:
                server = '10.0.%d/24' % (int(nicnum) + 2)
            (server, mask) = server.split('/')
            while server.count('.') != 3:
                server += '.0'
            (a, b, c, d) = server.split('.')
            server = '%d.%d.%d.4' % (a, b, c)
        prefix = nat.TFTPPrefix
        if prefix is None:
            prefix = '%s/TFTP/' % (ctx['vb'].homeFolder)
        bootfile = nat.TFTPBootFile
        if bootfile is None:
            bootfile = '%s.pxe' % (mach.name)
        msg = 'server:%s, prefix:%s, bootfile:%s' % (server, prefix, bootfile)
        return (0, [msg])
    else:

        cmd = args[1]
        if len(args) != 3:
            print('invalid args:', args)
            print(natTftp.__doc__)
            return (1, None)
        if cmd == 'prefix': nat.TFTPPrefix = args[2]
        elif cmd == 'bootfile': nat.TFTPBootFile = args[2]
        elif cmd == 'server': nat.TFTPNextServer = args[2]
        else:
            print("invalid cmd:", cmd)
            return (1, None)
    return (0, None)

def natPortForwarding(ctx, mach, nicnum, nat, args):
    """This command shows/manages port-forwarding settings
    usage:
        nat <vm> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
            |[no_name tcp|udp <hostip> <hostport> <guestip> <guestport>]
            |[ex tcp|udp <pf-name> <hostip> <hostport> <guestip> <guestport>]
            |[delete <pf-name>]
    """
    if len(args) == 1:
        # note: keys/values are swapped in defining part of the function
        proto = {0: 'udp', 1: 'tcp'}
        msg = []
        pfs = ctx['global'].getArray(nat, 'redirects')
        for pf in pfs:
            (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(', ')
            msg.append('%s: %s %s:%s => %s:%s' % (pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
        return (0, msg) # msg is array
    else:
        proto = {'udp': 0, 'tcp': 1}
        pfcmd = {
            'simple': {
                'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 5,
                'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4]))
            },
            'no_name': {
                'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 7,
                'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6]))
            },
            'ex': {
                'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 8,
                'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7]))
            },
            'delete': {
                'validate': lambda: len(args) == 3,
                'func': lambda: nat.removeRedirect(args[2])
            }
        }

        if not pfcmd[args[1]]['validate']():
            print('invalid port-forwarding or args of sub command ', args[1])
            print(natPortForwarding.__doc__)
            return (1, None)

        a = pfcmd[args[1]]['func']()
    return (0, None)

def natNetwork(ctx, mach, nicnum, nat, args):
    """This command shows/alters NAT network settings
    usage: nat <vm> <nicnum> network [<network>]
    """
    if len(args) == 1:
        if nat.network is not None and len(str(nat.network)) != 0:
            msg = '\'%s\'' % (nat.network)
        else:
            msg = '10.0.%d.0/24' % (int(nicnum) + 2)
        return (0, [msg])
    else:
        (addr, mask) = args[1].split('/')
        if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
            print('Invalid arguments')
            return (1, None)
        nat.network = args[1]
    return (0, None)

def natCmd(ctx, args):
    """This command is entry point to NAT settins management
    usage: nat <vm> <nicnum> <cmd> <cmd-args>
    cmd - [alias|settings|tftp|dns|pf|network]
    for more information about commands:
    nat help <cmd>
    """

    natcommands = {
        'alias' : natAlias,
        'settings' : natSettings,
        'tftp': natTftp,
        'dns': natDns,
        'pf': natPortForwarding,
        'network': natNetwork
    }

    if len(args) < 2 or args[1] == 'help':
        if len(args) > 2:
            print(natcommands[args[2]].__doc__)
        else:
            print(natCmd.__doc__)
        return 0
    if len(args) == 1 or len(args) < 4 or args[3] not in natcommands:
        print(natCmd.__doc__)
        return 0
    mach = ctx['argsToMach'](args)
    if mach == None:
        print("please specify vm")
        return 0
    if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in list(range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType))):
        print('please specify adapter num %d isn\'t in range [0-%d]' % (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType)))
        return 0
    nicnum = int(args[2])
    cmdargs = []
    for i in range(3, len(args)):
        cmdargs.append(args[i])

    # @todo vvl if nicnum is missed but command is entered
    # use NAT func for every adapter on machine.
    func = args[3]
    rosession = 1
    session = None
    if len(cmdargs) > 1:
        rosession = 0
        session = ctx['global'].openMachineSession(mach, fPermitSharing=False)
        mach = session.machine

    adapter = mach.getNetworkAdapter(nicnum)
    natEngine = adapter.NATEngine
    (rc, report) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
    if rosession == 0:
        if rc == 0:
            mach.saveSettings()
        session.unlockMachine()
    elif report is not None:
        for r in report:
            msg ='%s nic%d %s: %s' % (mach.name, nicnum, func, r)
            print(msg)
    return 0

def nicSwitchOnOff(adapter, attr, args):
    if len(args) == 1:
        yesno = {0: 'off', 1: 'on'}
        r = yesno[int(adapter.__getattr__(attr))]
        return (0, r)
    else:
        yesno = {'off' : 0, 'on' : 1}
        if args[1] not in yesno:
            print('%s isn\'t acceptable, please choose %s' % (args[1], list(yesno.keys())))
            return (1, None)
        adapter.__setattr__(attr, yesno[args[1]])
    return (0, None)

def nicTraceSubCmd(ctx, vm, nicnum, adapter, args):
    '''
    usage: nic <vm> <nicnum> trace [on|off [file]]
    '''
    (rc, r) = nicSwitchOnOff(adapter, 'traceEnabled', args)
    if len(args) == 1 and rc == 0:
        r = '%s file:%s' % (r, adapter.traceFile)
        return (0, r)
    elif len(args) == 3 and rc == 0:
        adapter.traceFile = args[2]
    return (0, None)

def nicLineSpeedSubCmd(ctx, vm, nicnum, adapter, args):
    if len(args) == 1:
        r = '%d kbps'% (adapter.lineSpeed)
        return (0, r)
    else:
        if not args[1].isdigit():
            print('%s isn\'t a number' % (args[1]))
            return (1, None)
        adapter.lineSpeed = int(args[1])
    return (0, None)

def nicCableSubCmd(ctx, vm, nicnum, adapter, args):
    '''
    usage: nic <vm> <nicnum> cable [on|off]
    '''
    return nicSwitchOnOff(adapter, 'cableConnected', args)

def nicEnableSubCmd(ctx, vm, nicnum, adapter, args):
    '''
    usage: nic <vm> <nicnum> enable [on|off]
    '''
    return nicSwitchOnOff(adapter, 'enabled', args)

def nicTypeSubCmd(ctx, vm, nicnum, adapter, args):
    '''
    usage: nic <vm> <nicnum> type [Am79c970A|Am79c970A|I82540EM|I82545EM|I82543GC|Virtio]
    '''
    if len(args) == 1:
        nictypes = ctx['const'].all_values('NetworkAdapterType')
        for key in list(nictypes.keys()):
            if str(adapter.adapterType) == str(nictypes[key]):
                return (0, str(key))
        return (1, None)
    else:
        nictypes = ctx['const'].all_values('NetworkAdapterType')
        if args[1] not in list(nictypes.keys()):
            print('%s not in acceptable values (%s)' % (args[1], list(nictypes.keys())))
            return (1, None)
        adapter.adapterType = nictypes[args[1]]
    return (0, None)

def nicAttachmentSubCmd(ctx, vm, nicnum, adapter, args):
    '''
    usage: nic <vm> <nicnum> attachment [Null|NAT|Bridged <interface>|Internal <name>|HostOnly <interface>
    '''
    if len(args) == 1:
        nicAttachmentType = {
            ctx['global'].constants.NetworkAttachmentType_Null: ('Null', ''),
            ctx['global'].constants.NetworkAttachmentType_NAT: ('NAT', ''),
            ctx['global'].constants.NetworkAttachmentType_Bridged: ('Bridged', adapter.bridgedInterface),
            ctx['global'].constants.NetworkAttachmentType_Internal: ('Internal', adapter.internalNetwork),
            ctx['global'].constants.NetworkAttachmentType_HostOnly: ('HostOnly', adapter.hostOnlyInterface),
            # @todo show details of the generic network attachment type
            ctx['global'].constants.NetworkAttachmentType_Generic: ('Generic', ''),
        }
        if type(adapter.attachmentType) != int:
            t = str(adapter.attachmentType)
        else:
            t = adapter.attachmentType
        (r, p) = nicAttachmentType[t]
        return (0, 'attachment:%s, name:%s' % (r, p))
    else:
        nicAttachmentType = {
            'Null': {
                'v': lambda: len(args) == 2,
                'p': lambda: 'do nothing',
                'f': lambda: ctx['global'].constants.NetworkAttachmentType_Null},
            'NAT': {
                'v': lambda: len(args) == 2,
                'p': lambda: 'do nothing',
                'f': lambda: ctx['global'].constants.NetworkAttachmentType_NAT},
            'Bridged': {
                'v': lambda: len(args) == 3,
                'p': lambda: adapter.__setattr__('bridgedInterface', args[2]),
                'f': lambda: ctx['global'].constants.NetworkAttachmentType_Bridged},
            'Internal': {
                'v': lambda: len(args) == 3,
                'p': lambda: adapter.__setattr__('internalNetwork', args[2]),
                'f': lambda: ctx['global'].constants.NetworkAttachmentType_Internal},
            'HostOnly': {
                'v': lambda: len(args) == 2,
                'p': lambda: adapter.__setattr__('hostOnlyInterface', args[2]),
                'f': lambda: ctx['global'].constants.NetworkAttachmentType_HostOnly},
            # @todo implement setting the properties of a generic attachment
            'Generic': {
                'v': lambda: len(args) == 3,
                'p': lambda: 'do nothing',
                'f': lambda: ctx['global'].constants.NetworkAttachmentType_Generic}
        }
        if args[1] not in list(nicAttachmentType.keys()):
            print('%s not in acceptable values (%s)' % (args[1], list(nicAttachmentType.keys())))
            return (1, None)
        if not nicAttachmentType[args[1]]['v']():
            print(nicAttachmentType.__doc__)
            return (1, None)
        nicAttachmentType[args[1]]['p']()
        adapter.attachmentType = nicAttachmentType[args[1]]['f']()
    return (0, None)

def nicCmd(ctx, args):
    '''
    This command to manage network adapters
    usage: nic <vm> <nicnum> <cmd> <cmd-args>
    where cmd : attachment, trace, linespeed, cable, enable, type
    '''
    # 'command name':{'runtime': is_callable_at_runtime, 'op': function_name}
    niccomand = {
        'attachment': nicAttachmentSubCmd,
        'trace':  nicTraceSubCmd,
        'linespeed': nicLineSpeedSubCmd,
        'cable': nicCableSubCmd,
        'enable': nicEnableSubCmd,
        'type': nicTypeSubCmd
    }
    if  len(args) < 2 \
        or args[1] == 'help' \
        or (len(args) > 2 and args[3] not in niccomand):
        if len(args) == 3 \
           and args[2] in niccomand:
            print(niccomand[args[2]].__doc__)
        else:
            print(nicCmd.__doc__)
        return 0

    vm = ctx['argsToMach'](args)
    if vm is None:
        print('please specify vm')
        return 0

    if    len(args) < 3 \
       or int(args[2]) not in list(range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType))):
        print('please specify adapter num %d isn\'t in range [0-%d]'% (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType)))
        return 0
    nicnum = int(args[2])
    cmdargs = args[3:]
    func = args[3]
    session = None
    session = ctx['global'].openMachineSession(vm, fPermitSharing=True)
    vm = session.machine
    adapter = vm.getNetworkAdapter(nicnum)
    (rc, report) = niccomand[func](ctx, vm, nicnum, adapter, cmdargs)
    if rc == 0:
        vm.saveSettings()
    if report is not None:
        print('%s nic %d %s: %s' % (vm.name, nicnum, args[3], report))
    session.unlockMachine()
    return 0


def promptCmd(ctx, args):
    if    len(args) < 2:
        print("Current prompt: '%s'" % (ctx['prompt']))
        return 0

    ctx['prompt'] = args[1]
    return 0

def foreachCmd(ctx, args):
    if len(args) < 3:
        print("usage: foreach scope command, where scope is XPath-like expression //vms/vm[@CPUCount='2']")
        return 0

    scope = args[1]
    cmd = args[2]
    elems = eval_xpath(ctx, scope)
    try:
        for e in elems:
            e.apply(cmd)
    except:
        print("Error executing")
        traceback.print_exc()
    return 0

def foreachvmCmd(ctx, args):
    if len(args) < 2:
        print("foreachvm command <args>")
        return 0
    cmdargs = args[1:]
    cmdargs.insert(1, '')
    for mach in getMachines(ctx):
        cmdargs[1] = mach.id
        runCommandArgs(ctx, cmdargs)
    return 0

def recordDemoCmd(ctx, args):
    if len(args) < 3:
        print("usage: recordDemo vm filename (duration)")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    filename = args[2]
    dur = 10000
    if len(args) > 3:
        dur = float(args[3])
    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  recordDemo(ctx, console, filename, dur)])
    return 0

def playbackDemoCmd(ctx, args):
    if len(args) < 3:
        print("usage: playbackDemo vm filename (duration)")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    filename = args[2]
    dur = 10000
    if len(args) > 3:
        dur = float(args[3])
    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  playbackDemo(ctx, console, filename, dur)])
    return 0


def pciAddr(ctx, addr):
    strg = "%02x:%02x.%d" % (addr >> 8, (addr & 0xff) >> 3, addr & 7)
    return colPci(ctx, strg)

def lspci(ctx, console):
    assigned = ctx['global'].getArray(console.machine, 'PCIDeviceAssignments')
    for a in assigned:
        if a.isPhysicalDevice:
            print("%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress)))

    atts = ctx['global'].getArray(console, 'attachedPCIDevices')
    for a in atts:
        if a.isPhysicalDevice:
            print("%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress)))
        else:
            print("%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress)))
    return

def parsePci(strg):
    pcire = re.compile(r'(?P<b>[0-9a-fA-F]+):(?P<d>[0-9a-fA-F]+)\.(?P<f>\d)')
    match = pcire.search(strg)
    if match is None:
        return -1
    pdict = match.groupdict()
    return ((int(pdict['b'], 16)) << 8) | ((int(pdict['d'], 16)) << 3) | int(pdict['f'])

def lspciCmd(ctx, args):
    if len(args) < 2:
        print("usage: lspci vm")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  lspci(ctx, console)])
    return 0

def attachpciCmd(ctx, args):
    if len(args) < 3:
        print("usage: attachpci vm hostpci <guestpci>")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    hostaddr = parsePci(args[2])
    if hostaddr == -1:
        print("invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]))
        return 0

    if len(args) > 3:
        guestaddr = parsePci(args[3])
        if guestaddr == -1:
            print("invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3]))
            return 0
    else:
        guestaddr = hostaddr
    cmdClosedVm(ctx, mach, lambda ctx, mach, a: mach.attachHostPCIDevice(hostaddr, guestaddr, True))
    return 0

def detachpciCmd(ctx, args):
    if len(args) < 3:
        print("usage: detachpci vm hostpci")
        return 0
    mach = argsToMach(ctx, args)
    if mach == None:
        return 0
    hostaddr = parsePci(args[2])
    if hostaddr == -1:
        print("invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]))
        return 0

    cmdClosedVm(ctx, mach, lambda ctx, mach, a: mach.detachHostPCIDevice(hostaddr))
    return 0

def gotoCmd(ctx, args):
    if len(args) < 2:
        print("usage: goto line")
        return 0

    line = int(args[1])

    ctx['scriptLine'] = line

    return 0

aliases = {'s':'start',
           'i':'info',
           'l':'list',
           'h':'help',
           'a':'alias',
           'q':'quit', 'exit':'quit',
           'tg': 'typeGuest',
           'v':'verbose'}

commands = {'help':['Prints help information', helpCmd, 0],
            'start':['Start virtual machine by name or uuid: start Linux headless', startCmd, 0],
            'createVm':['Create virtual machine: createVm macvm MacOS', createVmCmd, 0],
            'removeVm':['Remove virtual machine', removeVmCmd, 0],
            'pause':['Pause virtual machine', pauseCmd, 0],
            'resume':['Resume virtual machine', resumeCmd, 0],
            'save':['Save execution state of virtual machine', saveCmd, 0],
            'stats':['Stats for virtual machine', statsCmd, 0],
            'powerdown':['Power down virtual machine', powerdownCmd, 0],
            'powerbutton':['Effectively press power button', powerbuttonCmd, 0],
            'list':['Shows known virtual machines', listCmd, 0],
            'info':['Shows info on machine', infoCmd, 0],
            'ginfo':['Shows info on guest', ginfoCmd, 0],
            'gexec':['Executes program in the guest', gexecCmd, 0],
            'gcopy':['Copy file to the guest', gcopyCmd, 0],
            'gpipe':['Pipe between host and guest', gpipeCmd, 0],
            'alias':['Control aliases', aliasCmd, 0],
            'verbose':['Toggle verbosity', verboseCmd, 0],
            'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
            'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print(m.name, "has", m.memorySize, "M")\'', evalCmd, 0],
            'quit':['Exits', quitCmd, 0],
            'host':['Show host information', hostCmd, 0],
            'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0, 0)\'', guestCmd, 0],
            'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
            'monitorGuestKbd':['Monitor guest keyboard for some time: monitorGuestKbd Win32 10', monitorGuestKbdCmd, 0],
            'monitorGuestMouse':['Monitor guest mouse for some time: monitorGuestMouse Win32 10', monitorGuestMouseCmd, 0],
            'monitorGuestMultiTouch':['Monitor guest touch screen for some time: monitorGuestMultiTouch Win32 10', monitorGuestMultiTouchCmd, 0],
            'monitorVBox':['Monitor what happens with VirtualBox for some time: monitorVBox 10', monitorVBoxCmd, 0],
            'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
            'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
            'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
            'findAssert':['Find assert in log file of the VM, : findAssert Win32', findAssertCmd, 0],
            'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
            'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
            'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
            'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
            'exportVm':['Export VM in OVF format: exportVm Win /tmp/win.ovf', exportVMCmd, 0],
            'screenshot':['Take VM screenshot to a file: screenshot Win /tmp/win.png 1024 768 0', screenshotCmd, 0],
            'teleport':['Teleport VM to another box (see openportal): teleport Win anotherhost:8000 <passwd> <maxDowntime>', teleportCmd, 0],
            'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
            'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
            'closeportal':['Close teleportation portal (see openportal, teleport): closeportal Win', closeportalCmd, 0],
            'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
            'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
            'gueststats':['Print available guest stats (only Windows guests with additions so far): gueststats Win32', gueststatsCmd, 0],
            'plugcpu':['Add a CPU to a running VM: plugcpu Win 1', plugcpuCmd, 0],
            'unplugcpu':['Remove a CPU from a running VM (additions required, Windows cannot unplug): unplugcpu Linux 1', unplugcpuCmd, 0],
            'createHdd': ['Create virtual HDD:  createHdd 1000 /disk.vdi ', createHddCmd, 0],
            'removeHdd': ['Permanently remove virtual HDD: removeHdd /disk.vdi', removeHddCmd, 0],
            'registerHdd': ['Register HDD image with VirtualBox instance: registerHdd /disk.vdi', registerHddCmd, 0],
            'unregisterHdd': ['Unregister HDD image with VirtualBox instance: unregisterHdd /disk.vdi', unregisterHddCmd, 0],
            'attachHdd': ['Attach HDD to the VM: attachHdd win /disk.vdi "IDE Controller" 0:1', attachHddCmd, 0],
            'detachHdd': ['Detach HDD from the VM: detachHdd win /disk.vdi', detachHddCmd, 0],
            'registerIso': ['Register CD/DVD image with VirtualBox instance: registerIso /os.iso', registerIsoCmd, 0],
            'unregisterIso': ['Unregister CD/DVD image with VirtualBox instance: unregisterIso /os.iso', unregisterIsoCmd, 0],
            'removeIso': ['Permanently remove CD/DVD image: removeIso /os.iso', removeIsoCmd, 0],
            'attachIso': ['Attach CD/DVD to the VM: attachIso win /os.iso "IDE Controller" 0:1', attachIsoCmd, 0],
            'detachIso': ['Detach CD/DVD from the VM: detachIso win /os.iso', detachIsoCmd, 0],
            'mountIso': ['Mount CD/DVD to the running VM: mountIso win /os.iso "IDE Controller" 0:1', mountIsoCmd, 0],
            'unmountIso': ['Unmount CD/DVD from running VM: unmountIso win "IDE Controller" 0:1', unmountIsoCmd, 0],
            'attachCtr': ['Attach storage controller to the VM: attachCtr win Ctr0 IDE ICH6', attachCtrCmd, 0],
            'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
            'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
            'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
            'listMedia': ['List media known to this VBox instance', listMediaCmd, 0],
            'listUsb': ['List known USB devices', listUsbCmd, 0],
            'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
            'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
            'gui': ['Start GUI frontend', guiCmd, 0],
            'colors':['Toggle colors', colorsCmd, 0],
            'snapshot':['VM snapshot manipulation, snapshot help for more info', snapshotCmd, 0],
            'nat':['NAT (network address translation engine) manipulation, nat help for more info', natCmd, 0],
            'nic' : ['Network adapter management', nicCmd, 0],
            'prompt' : ['Control shell prompt', promptCmd, 0],
            'foreachvm' : ['Perform command for each VM', foreachvmCmd, 0],
            'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print(obj.name)"', foreachCmd, 0],
            'recordDemo':['Record demo: recordDemo Win32 file.dmo 10', recordDemoCmd, 0],
            'playbackDemo':['Playback demo: playbackDemo Win32 file.dmo 10', playbackDemoCmd, 0],
            'lspci': ['List PCI devices attached to the VM: lspci Win32', lspciCmd, 0],
            'attachpci': ['Attach host PCI device to the VM: attachpci Win32 01:00.0', attachpciCmd, 0],
            'detachpci': ['Detach host PCI device from the VM: detachpci Win32 01:00.0', detachpciCmd, 0],
            'goto': ['Go to line in script (script-only)', gotoCmd, 0]
            }

def runCommandArgs(ctx, args):
    c = args[0]
    if aliases.get(c, None) != None:
        c = aliases[c]
    ci = commands.get(c, None)
    if ci == None:
        print("Unknown command: '%s', type 'help' for list of known commands" % (c))
        return 0
    if ctx['remote'] and ctx['vb'] is None:
        if c not in ['connect', 'reconnect', 'help', 'quit']:
            print("First connect to remote server with %s command." % (colored('connect', 'blue')))
            return 0
    return ci[1](ctx, args)


def runCommand(ctx, cmd):
    if not cmd: return 0
    args = split_no_quotes(cmd)
    if len(args) == 0: return 0
    return runCommandArgs(ctx, args)

#
# To write your own custom commands to vboxshell, create
# file ~/.VirtualBox/shellext.py with content like
#
# def runTestCmd(ctx, args):
#    print("Testy test", ctx['vb'])
#    return 0
#
# commands = {
#    'test': ['Test help', runTestCmd]
# }
# and issue reloadExt shell command.
# This file also will be read automatically on startup or 'reloadExt'.
#
# Also one can put shell extensions into ~/.VirtualBox/shexts and
# they will also be picked up, so this way one can exchange
# shell extensions easily.
def addExtsFromFile(ctx, cmds, filename):
    if not os.path.isfile(filename):
        return
    d = {}
    try:
        exec(compile(open(filename).read(), filename, 'exec'), d, d)
        for (k, v) in list(d['commands'].items()):
            if g_fVerbose:
                print("customize: adding \"%s\" - %s" % (k, v[0]))
            cmds[k] = [v[0], v[1], filename]
    except:
        print("Error loading user extensions from %s" % (filename))
        traceback.print_exc()


def checkUserExtensions(ctx, cmds, folder):
    folder = str(folder)
    name = os.path.join(folder, "shellext.py")
    addExtsFromFile(ctx, cmds, name)
    # also check 'exts' directory for all files
    shextdir = os.path.join(folder, "shexts")
    if not os.path.isdir(shextdir):
        return
    exts = os.listdir(shextdir)
    for e in exts:
        # not editor temporary files, please.
        if e.endswith('.py'):
            addExtsFromFile(ctx, cmds, os.path.join(shextdir, e))

def getHomeFolder(ctx):
    if ctx['remote'] or ctx['vb'] is None:
        if 'VBOX_USER_HOME' in os.environ:
            return os.path.join(os.environ['VBOX_USER_HOME'])
        return os.path.join(os.path.expanduser("~"), ".VirtualBox")
    else:
        return ctx['vb'].homeFolder

def interpret(ctx):
    if ctx['remote']:
        commands['connect'] = ["Connect to remote VBox instance: connect http://server:18083 user password", connectCmd, 0]
        commands['disconnect'] = ["Disconnect from remote VBox instance", disconnectCmd, 0]
        commands['reconnect'] = ["Reconnect to remote VBox instance", reconnectCmd, 0]
        ctx['wsinfo'] = ["http://localhost:18083", "", ""]

    vbox = ctx['vb']
    if vbox is not None:
        try:
            print("Running VirtualBox version %s" % (vbox.version))
        except Exception as e:
            printErr(ctx, e)
            if g_fVerbose:
                traceback.print_exc()
        ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
    else:
        ctx['perf'] = None

    home = getHomeFolder(ctx)
    checkUserExtensions(ctx, commands, home)
    if platform.system() in ['Windows', 'Microsoft']:
        global g_fHasColors
        g_fHasColors = False
    hist_file = os.path.join(home, ".vboxshellhistory")
    autoCompletion(commands, ctx)

    if g_fHasReadline and os.path.exists(hist_file):
        readline.read_history_file(hist_file)

    # to allow to print actual host information, we collect info for
    # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
    if ctx['perf']:
        try:
            ctx['perf'].setup(['*'], [vbox.host], 10, 15)
        except:
            pass
    cmds = []

    if g_sCmd is not None:
        cmds = g_sCmd.split(';')
    it = cmds.__iter__()

    while True:
        try:
            if g_fBatchMode:
                cmd = 'runScript %s'% (g_sScriptFile)
            elif g_sCmd is not None:
                cmd = next(it)
            else:
                if sys.version_info[0] <= 2:
                    cmd = raw_input(ctx['prompt'])
                else:
                    cmd = input(ctx['prompt'])
            done = runCommand(ctx, cmd)
            if done != 0: break
            if g_fBatchMode:
                break
        except KeyboardInterrupt:
            print('====== You can type quit or q to leave')
        except StopIteration:
            break
        except EOFError:
            break
        except Exception as e:
            printErr(ctx, e)
            if g_fVerbose:
                traceback.print_exc()
        ctx['global'].waitForEvents(0)
    try:
        # There is no need to disable metric collection. This is just an example.
        if ct['perf']:
            ctx['perf'].disable(['*'], [vbox.host])
    except:
        pass
    if g_fHasReadline:
        readline.write_history_file(hist_file)

def runCommandCb(ctx, cmd, args):
    args.insert(0, cmd)
    return runCommandArgs(ctx, args)

def runGuestCommandCb(ctx, uuid, guestLambda, args):
    mach = machById(ctx, uuid)
    if mach == None:
        return 0
    args.insert(0, guestLambda)
    cmdExistingVm(ctx, mach, 'guestlambda', args)
    return 0

def main(argv):

    #
    # Parse command line arguments.
    #
    parse = OptionParser()
    parse.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help = "switch on verbose")
    parse.add_option("-a", "--autopath", dest="autopath", action="store_true", default=False, help = "switch on autopath")
    parse.add_option("-w", "--webservice", dest="style", action="store_const", const="WEBSERVICE", help = "connect to webservice")
    parse.add_option("-b", "--batch", dest="batch_file", help = "script file to execute")
    parse.add_option("-c", dest="command_line", help = "command sequence to execute")
    parse.add_option("-o", dest="opt_line", help = "option line")
    global g_fVerbose, g_sScriptFile, g_fBatchMode, g_fHasColors, g_fHasReadline, g_sCmd
    (options, args) = parse.parse_args()
    g_fVerbose = options.verbose
    style = options.style
    if options.batch_file is not None:
        g_fBatchMode = True
        g_fHasColors = False
        g_fHasReadline = False
        g_sScriptFile = options.batch_file
    if options.command_line is not None:
        g_fHasColors = False
        g_fHasReadline = False
        g_sCmd = options.command_line

    params = None
    if options.opt_line is not None:
        params = {}
        strparams = options.opt_line
        strparamlist = strparams.split(',')
        for strparam in strparamlist:
            (key, value) = strparam.split('=')
            params[key] = value

    if options.autopath:
        asLocations = [ os.getcwd(), ]
        try:    sScriptDir = os.path.dirname(os.path.abspath(__file__))
        except: pass # In case __file__ isn't there.
        else:
            if platform.system() in [ 'SunOS', ]:
                asLocations.append(os.path.join(sScriptDir, 'amd64'))
            asLocations.append(sScriptDir)


        sPath = os.environ.get("VBOX_PROGRAM_PATH")
        if sPath is None:
            for sCurLoc in asLocations:
                if   os.path.isfile(os.path.join(sCurLoc, "VirtualBox")) \
                  or os.path.isfile(os.path.join(sCurLoc, "VirtualBox.exe")):
                    print("Autodetected VBOX_PROGRAM_PATH as", sCurLoc)
                    os.environ["VBOX_PROGRAM_PATH"] = sCurLoc
                    sPath = sCurLoc
                    break
        if sPath:
            sys.path.append(os.path.join(sPath, "sdk", "installer"))

        sPath = os.environ.get("VBOX_SDK_PATH")
        if sPath is None:
            for sCurLoc in asLocations:
                if os.path.isfile(os.path.join(sCurLoc, "sdk", "bindings", "VirtualBox.xidl")):
                    sCurLoc = os.path.join(sCurLoc, "sdk")
                    print("Autodetected VBOX_SDK_PATH as", sCurLoc)
                    os.environ["VBOX_SDK_PATH"] = sCurLoc
                    sPath = sCurLoc
                    break
        if sPath:
            sCurLoc = sPath
            sTmp = os.path.join(sCurLoc, 'bindings', 'xpcom', 'python')
            if os.path.isdir(sTmp):
                sys.path.append(sTmp)
            del sTmp
        del sPath, asLocations


    #
    # Set up the shell interpreter context and start working.
    #
    from vboxapi import VirtualBoxManager
    oVBoxMgr = VirtualBoxManager(style, params)
    ctx = {
        'global':       oVBoxMgr,
        'vb':           oVBoxMgr.getVirtualBox(),
        'const':        oVBoxMgr.constants,
        'remote':       oVBoxMgr.remote,
        'type':         oVBoxMgr.type,
        'run':          lambda cmd, args: runCommandCb(ctx, cmd, args),
        'guestlambda':  lambda uuid, guestLambda, args: runGuestCommandCb(ctx, uuid, guestLambda, args),
        'machById':     lambda uuid: machById(ctx, uuid),
        'argsToMach':   lambda args: argsToMach(ctx, args),
        'progressBar':  lambda p: progressBar(ctx, p),
        'typeInGuest':  typeInGuest,
        '_machlist':    None,
        'prompt':       g_sPrompt,
        'scriptLine':   0,
        'interrupt':    False,
    }
    interpret(ctx)

    #
    # Release the interfaces references in ctx before cleaning up.
    #
    for sKey in list(ctx.keys()):
        del ctx[sKey]
    ctx = None
    gc.collect()

    oVBoxMgr.deinit()
    del oVBoxMgr

if __name__ == '__main__':
    main(sys.argv)