aboutsummaryrefslogtreecommitdiff
path: root/kvmx
blob: 0420211479a355b6ad9b78ca3033cd139d89349d (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
#!/usr/bin/env bash
#
# kvmx virtual machine manager
#
# Copyright (C) 2017 Silvio Rhatto - rhatto at riseup.net
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Basic parameters
VERSION="0.1.0"
BASENAME="`basename $0`"
DIRNAME="`dirname $0`"
ACTION="$1"
GLOBAL_USER_CONFIG_FOLDER="$HOME/.config/kvmx"
GLOBAL_USER_CONFIG_FILE="$HOME/.config/kvmxconfig"

# Get the application base
function kvmx_app_base {
  local dest
  local base

  # Determine if we are in a local or system-wide install.
  if [ -h "$0" ]; then
    dest="$(readlink $0)"

    # Check again as the caller might be a symlink as well
    if [ -h "$dest" ]; then
      base="`dirname $dest`"
      dest="$(dirname $(readlink $dest))"
    else
      base="`dirname $0`"
      dest="`dirname $dest`"
    fi

    # Deal with relative or absolute links
    if [ "`basename $dest`" == "$dest" ]; then
      APP_BASE="$base"
    else
      APP_BASE="$dest"
    fi
  else
    APP_BASE="`dirname $0`"
  fi

  echo $APP_BASE
}

# Build a SSH command
function __kvmx_ssh_command {
  if [ ! -z "$1" ]; then
    #local ssh_key_param="-i $1"
    # See https://makandracards.com/makandra/512-how-to-fix-too-many-authentic-authentication-failures-with-ssh-and-or-capistrano
    local ssh_key_param="-o IdentityFile=$1 -o IdentitiesOnly=yes"
  fi

  # See http://blog.djm.net.au/2013/11/chacha20-and-poly1305-in-openssh.html
  SSH_OPTS="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=FATAL -o ProxyCommand=none -o Ciphers=chacha20-poly1305@openssh.com -o User=$SSH_LOGIN $ssh_key_param"
  SSH_COMMAND="ssh $SSH_OPTS"
  SCP_COMMAND="scp $SSH_OPTS"
}

# Create a guest entry at the global user config folder
function __kvmx_create_config_entry {
  if [ -z "$FOLDER" ]; then
    return 1
  fi

  ( cd $GLOBAL_USER_CONFIG_FOLDER && ln -sf $FOLDER/kvmxfile $VM )
}

# Initialize
function __kvmx_initialize {
  if [ "$ACTION" == "app_base" ] || [ "$ACTION" == "version" ]; then
    return
  fi

  # Load basic functions
  export APP_BASE="`$DIRNAME/kvmx app_base`"
  source $APP_BASE/lib/kvmx/functions || exit 1

  # Check dependencies
  __kvmx_check_dependencies

  # Alias to be used in config files
  KVMX_BASE="$APP_BASE"

  # Initialize
  mkdir -p $GLOBAL_USER_CONFIG_FOLDER

  # Stop processing here for some actions
  if [ "$ACTION" == "init" ] || [ "$ACTION" == "list" ]; then
    return
  fi

  # Check if second argument is a VM name or option
  if [ -z "$2" ]; then
    VM="$(basename `pwd`)"
    SHIFTARGS="1"
  elif [ -e 'kvmxfile' ] && [ ! -e "$GLOBAL_USER_CONFIG_FOLDER/$2" ] && [ "$2" != "$(basename `pwd`)" ]; then
    VM="$(basename `pwd`)"
    SHIFTARGS="1"
  else
    VM="$2"
    SHIFTARGS="2"
  fi

  # Default parameters
  PORT="$(($RANDOM + 1024))"
  SSH="$(($PORT + 22))"
  GUEST_DISPLAY="$(((RANDOM % 10) + 1))"
  XDMCP_PORT="$(($RANDOM + 10000))"

  # Load user config
  if [ -e "$GLOBAL_USER_CONFIG_FILE" ]; then
    source $GLOBAL_USER_CONFIG_FILE
  fi

  # Load and check guest config
  if [ "$ACTION" != "ls" ] && [ "$ACTION" != "edit" ] && [ "$ACTION" != "usage" ]; then
    if [ ! -e "$GLOBAL_USER_CONFIG_FOLDER/$VM" ]; then
      if [ -e "kvmxfile" ]; then
        # Existing kvmxfile but not registered at the global user config
        FOLDER="$(pwd)"
        __kvmx_create_config_entry
      else
        echo "$BASENAME: config not found: $GLOBAL_USER_CONFIG_FOLDER/$VM"
        exit 1
      fi
    else
      source $GLOBAL_USER_CONFIG_FOLDER/$VM
    fi

    if [ -z "$image" ]; then
      if [ -z "$image_base" ]; then
        image_base="$HOME/.local/share/kvmx"
      fi

      # There might be trouble managing the guest when project folder name is different from
      # hostname and no image param is set (kvmx-create puts image in one
      # place, kvmx expects in the other). So we try to guess first the image by hostname
      # and then by guest name. Note that it might be possible to have conflicts if there
      # are machines with hostnames set to the name os other machines. But here we hope that
      # the user is not messing that much ;)
      if [ ! -z "$hostname" ] && [ -e "$image_base/$hostname/box.img" ]; then
        image="$image_base/$hostname/box.img"
      else
        image="$image_base/$VM/box.img"
      fi
    fi

    if [ ! -h "$GLOBAL_USER_CONFIG_FOLDER/$VM" ]; then
      echo "error: $GLOBAL_USER_CONFIG_FOLDER/$VM is not a symlink"
      exit 1
    fi

    # Box and folder config
    KVMXFILE="`readlink $GLOBAL_USER_CONFIG_FOLDER/$VM`"
    KVMX_PROJECT_FOLDER="`dirname $KVMXFILE`"
    STORAGE="`dirname $image`"
    DATADIR="${datadir:-$STORAGE}"
    STATE_DIR="$DATADIR/state/$VM"
    LOG_DIR="$DATADIR/log"
    PIDFILE="$STATE_DIR/pid"
    PORTFILE="$STATE_DIR/port"
    XDMCPPORTFILE="$STATE_DIR/xdmcp"
    SSHFILE="$STATE_DIR/ssh"
    DISPLAYFILE="$STATE_DIR/display"
    SPICEFILE="$STATE_DIR/spice"
    XEPHYRFILE="$STATE_DIR/xephyr"
    LOGFILE="$LOG_DIR/qemu"
    SPICELOG="$LOG_DIR/spice"
    XPRALOG="$LOG_DIR/xpra"
    XDMCPLOG="$LOG_DIR/xdmcp"
    MONITORFILE="$STATE_DIR/monitor"
    CONSOLEFILE="$STATE_DIR/console"

    if [ -z "$ssh_custom_pubkey" ]; then
      if [ -e "$DATADIR/ssh/$VM.key" ]; then
        mkdir -p "$DATADIR/ssh"
        SSHKEY="$DATADIR/ssh/$VM.key"
      else
        SSHKEY="$APP_BASE/share/ssh/insecure_private_key"
      fi
    fi

    if [ ! -z "$user" ]; then
      SSH_LOGIN="$user"
    else
      SSH_LOGIN="user"
    fi

    __kvmx_ssh_command $SSHKEY

    mkdir -p $STATE_DIR $LOG_DIR

    # Additional checks
    if [ "$ACTION" != "up" ]           && [ "$ACTION" != "provision" ] && [ "$ACTION" != "purge" ]  && \
       [ "$ACTION" != "destroy" ]      && [ "$ACTION" != "install" ]   && [ "$ACTION" != "config" ] && \
       [ "$ACTION" != "config_unset" ] && [ "$ACTION" != "create" ]    && [ "$ACTION" != "shell" ]  && \
       [ "$ACTION" != "boot" ]; then
      if [ ! -e "$image" ]; then
        echo "$BASENAME: file not found: $image"
        exit 1
      fi

      # See http://www.linux-kvm.org/page/FAQ
      if ! egrep -q '^flags.*(vmx|svm)' /proc/cpuinfo; then
        echo "$BASENAME: WARNING: Intel VT or AMD-V not present at /proc/cpuinfo, expect slow performance"
      fi

      if ! lsmod | grep -q '^kvm '; then
        echo "$BASENAME: WARNING: kvm kernel module not loaded, expect slow performance"
      fi

      if ! groups `whoami` | grep -q 'kvm'; then
        echo "$BASENAME: WARNING: user `whoami` not in kvm group, expect slow performance"
      fi
    fi
  fi
}

# Run spice client
function kvmx_spice {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$spice" == "0" ]; then
    echo "$BASENAME: spice is disabled for guest $VM"
    exit 1
  fi

  # Ensure we have the right port configuration: we can also be
  # running directly from command line.
  PORT="`cat $PORTFILE`"

  if [ -z "$PORT" ]; then
    echo "$BASENAME: cannot get spice port for $VM"
    exit 1
  fi

  if [ "$spice_client" == "spicy" ] && which spicy &> /dev/null; then
    spicy -h localhost -p $PORT &
  elif [ "$spice_client" == "virt-viewer" ] && which virt-viewer &> /dev/null; then
    remote-viewer spice://localhost:$PORT &
  #elif [ ! -z "$spice_client" ] && [ "$spice_client" != "spicec" ]; then
  elif [ ! -z "$spice_client" ]; then
    echo "$BASENAME: spice_client $spice_client not currently supported"
    exit 1
  else
    if which spicy &> /dev/null; then
      spicy -h localhost -p $PORT &
    fi

    #if which spicec &> /dev/null; then
    #  # https://lists.freedesktop.org/archives/spice-devel/2013-September/014643.html
    #  SPICE_NOGRAB=1 spicec --host localhost --port $PORT &> $SPICELOG &
    #fi
  fi

  SPICEPID="$!"
  echo "$SPICEPID" > $SPICEFILE

  # Give time to connect
  sleep 2

  # Fix window title an position
  if which /usr/bin/xdotool &> /dev/null; then
    if [ ! -z "$xclient_windowmove" ]; then
      #xdotool search --name "SPICEc:0" windowmove $xclient_windowmove
      xdotool search --name "spice display 0:0" windowmove $xclient_windowmove
    fi

    #xdotool search --name "SPICEc:0" set_window --name $VM
    xdotool search --name "spice display 0:0" set_window --name $VM
  fi

  if [ "$ACTION" == "spice" ]; then
    # Set screen resolution
    if [ "$xrandr" == "1" ]; then
      kvmx_xrandr
    fi

    # Restart vdagent
    if [ "$ssh_support" == "y" ]; then
      echo "which kvmx-vdagent > /dev/null && DISPLAY=:0 kvmx-vdagent" | kvmx_ssh
    fi
  fi
}

# Bring virtual machine up
function kvmx_up {
  if kvmx_suspended; then
    $DIRNAME/$BASENAME resume $VM

    if [ "$run_spice_client" == "1" ]; then
      $DIRNAME/$BASENAME spice $VM
    fi

    if [ "$run_xpra" == "1" ]; then
      $DIRNAME/$BASENAME xpra $VM
    fi

    if [ "$run_xephyr" == "1" ]; then
      $DIRNAME/$BASENAME xephyr $VM
    fi

    exit
  elif kvmx_running; then
    echo "$BASENAME: guest $VM is already running"

    if [ "$run_spice_client" == "1" ]; then
      kvmx spice $VM
      exit
    else
      exit 1
    fi
  fi

  if [ ! -z "$shared_folder" ]; then
    # Get absolute path of shared folder relative to project path
    shared_folder="`cd $KVMX_PROJECT_FOLDER && cd $shared_folder &> /dev/null && pwd`"
    # Requires samba package installed in the host; see http://unix.stackexchange.com/a/183609
    #local shared="-net user,smb=$shared_folder"
    # See http://wiki.qemu-project.org/Documentation/9psetup
    local shared="-fsdev local,id=shared,path=$shared_folder,security_model=none -device virtio-9p-pci,fsdev=shared,mount_tag=shared"
  elif [ ! -z "$shared_folders" ]; then
    local old_ifs="$IFS"
    local shared_item
    local shared
    IFS=","
    for shared_item in $shared_folders; do
      local id="`echo $shared_item | cut -d ':' -f 1`"
      local shared_folder="`echo $shared_item | cut -d ':' -f 2`"
      local shared_folder_mountpoint="`echo $shared_item | cut -d ':' -f 3`"

      # Get absolute path of shared folder relative to project path
      shared_folder="`cd $KVMX_PROJECT_FOLDER && cd $shared_folder &> /dev/null && pwd`"

      shared="$shared -fsdev local,id=$id,path=$shared_folder,security_model=none -device virtio-9p-pci,fsdev=$id,mount_tag=$id"

      unset shared_folder
      unset shared_folder_mountpoint
    done
    IFS="$old_ifs"
  fi

  if [ ! -z "$port_mapping" ]; then
    local hostfwd=",$port_mapping"
  fi

  # Check if image exists, create otherwise
  if [ ! -e "$image" ]; then
    if [ ! -z "$basebox" ]; then
      if [ -e "$GLOBAL_USER_CONFIG_FOLDER/$basebox" ]; then
        baseimage="`kvmx list_image $basebox`"
        basekey="$(ls `dirname $baseimage`/ssh/$basebox.key)"

        if [ ! -e "$baseimage" ]; then
          echo "$BASENAME: could not find basebox $baseimage. Please create it first."
          exit 1
        fi

        if [ ! -z "$backing_file" ] && [ "$backing_file" == "1" ]; then
          echo "Creating image $image as an overlay of $baseimage..."
          baseimage_format="`qemu-img info $baseimage | grep "^file format: " | cut -d : -f 2 | sed -e 's/ //g'` "
          qemu-img create -o backing_file=$baseimage,backing_fmt=$baseimage_format -f $format $image
        else
          echo "Copying base image $baseimage to $image..."
          if which rsync &> /dev/null; then
            rsync -ah --sparse --progress $baseimage $image
          else
            # See https://rwmj.wordpress.com/2010/10/19/tip-making-a-disk-image-sparse/
            cp --sparse=always $baseimage $image
          fi
        fi

        if [ -e "$basekey" ]; then
          vmname="$(basename $STORAGE)"
          imagekey="$STORAGE/ssh/$vmname.key"
          mkdir -p "$STORAGE/ssh"

          cp $basekey     $imagekey
          cp $basekey.pub $imagekey.pub

          # Re-evaluate this if there's a custom SSH key.
          __kvmx_ssh_command $basekey
        fi

        local wait="y"
      fi
    else
      local wait="y"
      kvmx_create
    fi

    if [ "$wait" == "y" ]; then
      echo "Waiting before starting the new guest..."
      sleep 5
    fi
  fi

  if [ -z "$graphics" ]; then
    graphics="-vga qxl"
  fi

  if [ -z "$memory" ]; then
    memory="2048"
  fi

  if [ -z "$smp" ]; then
    smp="2"
  fi

  if [ -z "$drive_interface" ]; then
    drive_interface="virtio"
  fi

  if [ -z "$nic_model" ]; then
    nic_model="virtio"
  fi

  if [ -z "$shared_folder_msize" ]; then
    shared_folders_msize="524288"
  fi

  if [ -z "$shared_folders_cache" ]; then
    shared_folders_cache="none"
  fi

  if [ ! -z "$cdrom" ]; then
    cdrom_opts="-cdrom $cdrom"
  fi

  if [ ! -z "$boot" ]; then
    boot_opts="-boot $boot"
  fi

  if [ -z "$net" ] || [ "$net" == "user" ]; then
    #net_opts="user,hostfwd=tcp:127.0.0.1:$SSH-:22,hostfwd=udp:127.0.0.1:$XDMCP_PORT-:177$hostfwd -net nic,model=$nic_model"
    net_opts="user,hostfwd=tcp:127.0.0.1:$SSH-:22$hostfwd -net nic,model=$nic_model"
  elif [ "$net" == "tap" ]; then
    # Thanks kvm-manager
    tap="${VM}0"
    # MAC address is derived from a hash of the host's name and the guest's name:
    mac_address="$(printf "02:%s" "$(printf "%s\0%s" "$(hostname)" "${VM}" | sha256sum | sed 's/\(..\)/\1:/g' | cut -f1-5 -d:)")"
    bridge="br0"
    net_opts="tap,ifname=$tap,script=no,downscript=no,vlan=0,name=hostnet0 -device virtio-net-pci,vlan=0,id=net0,mac=$mac_address,bus=pci.0"
  fi

  if [ ! -z "$net_dns" ] && [ "$net_dns" != "host" ]; then
    net_opts="$net_opts,dns=$net_dns"
  fi

  net_opts="-net $net_opts"

  if [ -z "$spice" ] || [ "$spice" == "1" ]; then
    spice_opts="-spice port=$PORT,addr=127.0.0.1,disable-ticketing,streaming-video=off,jpeg-wan-compression=never,playback-compression=off,zlib-glz-wan-compression=never,image-compression=off"
    spice_opts="$spice_opts -device virtio-serial-pci"
    spice_opts="$spice_opts -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0"
    spice_opts="$spice_opts -chardev spicevmc,id=spicechannel0,name=vdagent"
  fi

  if [ "$sound" != "0" ]; then
    if [ -z "$sound" ]; then
      sound="ac97"
    fi

    sound_opts="-soundhw $sound"
  fi

  if [ ! -z "$image_drive" ] && [ "$image_drive" == "cdrom" ]; then
    image_opts="-cdrom $image"
  else
    image_opts="-drive file=$image,if=$drive_interface"
  fi

  # USB redirect support
  # See https://people.freedesktop.org/~teuf/spice-doc/html/ch02s06.html
  #usb_opts="-device ich9-usb-ehci1,id=usb"
  #usb_opts="$usb_opts -device ich9-usb-uhci1,masterbus=usb.0,firstport=0,multifunction=on"
  #usb_opts="$usb_opts -device ich9-usb-uhci2,masterbus=usb.0,firstport=2"
  #usb_opts="$usb_opts -device ich9-usb-uhci3,masterbus=usb.0,firstport=4"
  #usb_opts="$usb_opts -chardev spicevmc,name=usbredir,id=usbredirchardev1"
  #usb_opts="$usb_opts -device usb-redir,chardev=usbredirchardev1,id=usbredirdev1"
  #usb_opts="$usb_opts -chardev spicevmc,name=usbredir,id=usbredirchardev2"
  #usb_opts="$usb_opts -device usb-redir,chardev=usbredirchardev2,id=usbredirdev2"
  #usb_opts="$usb_opts -chardev spicevmc,name=usbredir,id=usbredirchardev3"
  #usb_opts="$usb_opts -device usb-redir,chardev=usbredirchardev3,id=usbredirdev3"

  # Run virtual machine, nohup approach
  # See https://en.wikipedia.org/wiki/Nohup#Overcoming_hanging
  #nohup setsid kvm -m $memory -name $VM                                                             \
  #  -chardev "socket,id=monitor,path=$MONITORFILE,server,nowait" -mon chardev=monitor,mode=readline \
  #  -chardev "socket,id=serial0,path=$CONSOLEFILE,server,nowait" -device isa-serial,chardev=serial0 \
  #  -smp $smp -cpu host -balloon virtio                                                             \
  #  $graphics $shared                                                                               \
  #  $image_opts                                                                                     \
  #  $spice_opts                                                                                     \
  #  $sound_opts                                                                                     \
  #  $cdrom_opts                                                                                     \
  #  $boot_opts                                                                                      \
  #  $net_opts                                                                                       \
  #  $qemu_opts &> $LOGFILE < /dev/null &

  # Run virtual machine, screen approach
  # This is more immune to hangups
  screen -S kvmx-qemu-$VM -d -m kvm -m $memory -name $VM                                            \
    -chardev "socket,id=monitor,path=$MONITORFILE,server,nowait" -mon chardev=monitor,mode=readline \
    -chardev "socket,id=serial0,path=$CONSOLEFILE,server,nowait" -device isa-serial,chardev=serial0 \
    -smp $smp -cpu host -balloon virtio                                                             \
    $graphics $shared                                                                               \
    $image_opts                                                                                     \
    $spice_opts                                                                                     \
    $sound_opts                                                                                     \
    $cdrom_opts                                                                                     \
    $boot_opts                                                                                      \
    $net_opts                                                                                       \
    -pidfile $PIDFILE                                                                               \
    -D $LOGFILE                                                                                     \
    $qemu_opts

  # Only if nohup approach is being used
  #PID="$!"

  # Save state
  # Save PID here only if nohup approach is being used
  #echo $PID           > $PIDFILE
  echo $PORT          > $PORTFILE
  echo $SSH           > $SSHFILE
  echo $GUEST_DISPLAY > $DISPLAYFILE
  echo $XDMCP_PORT    > $XDMCPPORTFILE

  # Give time to qemu
  sleep 1

  # Thanks kvm-manager code for that portion
  /usr/bin/screen -D -m -L $LOG_DIR/servicelog \
                  -c $APP_BASE/share/screen/screenrc \
                  -S "kvmx-$VM" -t "kvmx-$VM" socat STDIO,raw,echo=0 "UNIX:${CONSOLEFILE},retry=30" &

  if [ "$run_spice_client" == "1" ]; then
    if [ "$spice" == "0" ]; then
      echo "$BASENAME: spice is disabled for guest $VM"
    else
      kvmx_spice
    fi
  fi

  # Check if on install mode
  if [ "$install" == "1" ]; then
    kvmx_status
    return
  fi

  if [ "$ssh_support" == "y" ]; then
    let ssh_attempts="0"
    echo -n "Waiting for machine to boot..."
    while true; do
      echo true | $SSH_COMMAND -o ConnectTimeout=2 -o NumberOfPasswordPrompts=0 -p $SSH 127.0.0.1 &> /dev/null && break
      echo -n "."
      let ssh_attempts++

      if [ "$ssh_attempts" == "20" ]; then
        echo "$BASENAME: timeout or access denied when trying to SSH into $VM."
        echo "$BASENAME: please check if the image is in a good state and if it accepts passwordless ssh connections"
        #kvmx_stop
        kvmx_poweroff
        exit 1
      fi

      sleep 8
    done
    echo " done."
    #sleep 5
    #echo ""

    kvmx_hostname

    # Somehow it is starting before DBUS and then crashing, so we try to start again
    echo "Ensure spice-vdagent is running..."
    echo "sudo /usr/sbin/service spice-vdagent start" | kvmx_ssh

    # See https://www.kernel.org/doc/Documentation/filesystems/9p.txt
    if [ ! -z "$shared_folder" ] && [ ! -z "$shared_folder_mountpoint" ]; then
      echo "Mounting $shared_folder on $shared_folder_mountpoint on guest..."
      echo "sudo mkdir -p $shared_folder_mountpoint" | kvmx_ssh
      echo "sudo mount -t 9p -o trans=virtio,msize=$shared_folders_msize shared $shared_folder_mountpoint -oversion=9p2000.L,posixacl,cache=$shared_folders_cache -o sync -o dirsync" | kvmx_ssh
      #echo "sudo mount //10.0.2.4/qemu $shared_folder_mountpint" | kvmx_ssh
    elif [ ! -z "$shared_folders" ]; then
      local old_ifs="$IFS"
      local shared_item
      IFS=","
      for shared_item in $shared_folders; do
        local id="`echo $shared_item | cut -d ':' -f 1`"
        local shared_folder="`echo $shared_item | cut -d ':' -f 2`"
        local shared_folder_mountpoint="`echo $shared_item | cut -d ':' -f 3`"

        # Get absolute path of shared folder relative to project path
        shared_folder="`cd $KVMX_PROJECT_FOLDER && cd $shared_folder &> /dev/null && pwd`"

        # Restore IFS for a while or kvmx_ssh won't work
        IFS="$old_ifs"
        echo "Mounting $shared_folder on $shared_folder_mountpoint $id on guest..."
        echo "sudo mkdir -p $shared_folder_mountpoint" | kvmx_ssh
        echo "sudo mount -t 9p -o trans=virtio $id $shared_folder_mountpoint -oversion=9p2000.L,posixacl,cache=$shared_folders_cache -o sync -o dirsync" | kvmx_ssh
        IFS=","
      done
      IFS="$old_ifs"
    fi

    if [ "$xrandr" == "1" ] && [ "$run_spice_client" == "1" ]; then
      echo "Waiting for X11 to come up so we can set machine resolution..."
      sleep 8
      kvmx_xrandr
    fi
  fi

  if [ "$run_xpra" == "1" ]; then
    $DIRNAME/$BASENAME xpra $VM
  fi

  if [ "$run_xephyr" == "1" ]; then
    $DIRNAME/$BASENAME xephyr $VM
  fi

  if [ ! -z "$startup_command" ] && [ "$ssh_support" == "y" ]; then
    echo "Running $startup_command..."
    echo "nohup $startup_command" | kvmx ssh $VM &> /dev/null &
  fi

  kvmx_status
}

# Set hostname
function kvmx_hostname {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: ssh_support is disabled for guest $VM"
    exit 1
  fi

  echo "Setting hostname..."
  $SSH_COMMAND -o ConnectTimeout=2 -p $SSH 127.0.0.1 <<EOF
  ##### BEGIN REMOTE SCRIPT #####
  OLD_HOST="\$(hostname)"

  # Set hosts entry
  if ! grep -q "^127.0.0.1 $hostname.$domain $hostname$" /etc/hosts; then
    echo "127.0.0.1 $hostname.$domain $hostname" | sudo tee -a /etc/hosts &> /dev/null
  fi

  echo "$hostname.$domain" | sudo tee /etc/hostname &> /dev/null
  sudo hostname $hostname.$domain 2> /dev/null

  # Remove old hostname from hosts file
  if [ "\$OLD_HOST" != "$hostname.$domain" ]; then
    if grep -q \$OLD_HOST /etc/hosts; then
      sudo sed -i -e "/\$OLD_HOST/d" /etc/hosts 2> /dev/null
    fi
  fi
  ##### END REMOTE SCRIPT #######
EOF
}

# Display usage
function kvmx_usage {
  echo "$BASENAME $VERSION - virtual machine manager"
  echo ""
  echo "usage: $BASENAME <action> [vm] [options]"
  echo ""
  echo "available actions:"
  echo ""
  grep "^function kvmx_" $0 | cut -d ' ' -f 2 | sed -e 's/kvmx_//' | sort | xargs -L 6 | column -t -c 6 | sed -e 's/^/\t/'
  echo ""
  echo "examples:"
  echo ""
  echo -e "\t$BASENAME list"
  echo -e "\t$BASENAME init  <machine>    [folder]"
  echo -e "\t$BASENAME clone <orig-guest> <dest-guest-or-folder>"
  echo -e "\t$BASENAME ssh   <machine>    -X firefox"
  echo ""

  local list="`kvmx_list`"

  if [ ! -z "$list" ]; then
    echo "available virtual machines:"
    echo ""
    echo "$list" | sed -e 's/^/\t/'
    echo ""
  fi

  exit 1
}

# Log into the guest using SSH
function kvmx_ssh {
  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: SSH support for $VM is disabled"
    exit 1
  fi

  if ! kvmx_running || kvmx_suspended; then
    echo "$BASENAME: $VM not running, trying to start it..."
    kvmx up $VM || exit 1
    #kvmx_up || exit 1
    #echo "$BASENAME: guest $VM is not running"
    #exit 1
  fi

  # Shift params according to how the program was called:
  # either "kvmx ssh" or "kvmx ssh guest".
  #if [ "$ACTION" == "ssh" ]; then
  #  if [ ! -z "$2" ]; then
  #    shift 2
  #  else
  #    shift 1
  #  fi
  #fi

  SSH="`cat $SSHFILE`"
  #TERM=xterm $SSH_COMMAND -p $SSH 127.0.0.1 $*
  $ssh_env $SSH_COMMAND -p $SSH 127.0.0.1 $*
}

# Get guest SSH key fingerprints
function kvmx_ssh_finger {
  if ls $DATADIR/ssh/*.pub.* &> /dev/null; then
    for finger in $DATADIR/ssh/*.pub.*; do
      cat $finger
    done
  else
    # Try to get list of keys in the server
    keys="$(
    echo | kvmx_ssh << EOF
    for key in /etc/ssh/*pub; do
      echo \$key
      #ssh-keygen -l        -f \$key
      #ssh-keygen -l -E md5 -f \$key
    done
EOF
)"

    # Get fingerprint for each key
    if [ ! -z "$keys" ]; then
      for key in $keys; do
        fingerprint="$(echo ssh-keygen -l -f $key | kvmx_ssh)"
        echo $fingerprint | tee $DATADIR/ssh/`basename $key`.sha256

        fingerprint="$(echo ssh-keygen -l -E md5 -f $key | kvmx_ssh)"
        echo $fingerprint | tee $DATADIR/ssh/`basename $key`.md5
      done
    else
      echo "$BASENAME: could not get SSH fingerprints for $VM"
      exit 1
    fi
  fi
}

# Get guest PID
function kvmx_pid {
  if [ -e "$PIDFILE" ]; then
    # QEMU might put weird things into pidfile, so we need a simple filter
    #cat $PIDFILE
    cut -d ' ' -f 1 $PIDFILE | head -1
  else
    return 1
  fi
}

# Suspend the virtual machine
function kvmx_suspend {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  PID="`kvmx_pid`"

  if [ -z "$PID" ]; then
    return 1
  fi

  kill -STOP $PID

  # Alternative
  #kvmx_monitor stop

  if [ -e "$SPICEFILE" ]; then
    SPICEPID="`cat $SPICEFILE`"

    if [ -z "$SPICEPID" ]; then
      return
    fi

    if ps $SPICEPID &> /dev/null; then
      kill $SPICEPID
    fi
  fi
}

# Check if a guest is running
function kvmx_running {
  if [ ! -e "$PIDFILE" ]; then
    return 1
  fi

  PID="`kvmx_pid`"

  if [ -z "$PID" ]; then
    return 1
  fi

  # Simpler check
  #ps $PID &> /dev/null

  # Better check were process should match a qemu binary
  ps -o command $PID | grep -q '^qemu'

  return $?
}

# Check if a guest is running
function kvmx_suspended {
  if ! kvmx_running; then
    return 1
  else
    if ps -p $PID -o stat --no-headers | grep -q 'T'; then
      return 0
    else
      return 1
    fi
  fi
}

# Resume the guest
function kvmx_resume {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  PID="`kvmx_pid`"

  if [ -z "$PID" ]; then
    return 1
  fi

  kill -CONT $PID

  # Alternative
  #kvmx_monitor system_wakeup
}

# Poweroff the guest
function kvmx_poweroff {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$run_xpra" == "1" ]; then
    $DIRNAME/$BASENAME xpra $VM stop
  fi

  if [ "$ssh_support" == "y" ]; then
    echo /usr/bin/sudo poweroff | kvmx_ssh &> /dev/null
  else
    kvmx_monitor system_powerdown
  fi

  kvmx_xephyr_stop

  let poweroff_attempts="0"
  echo -n "Waiting for machine to stop..."
  while true; do
    kvmx_running || break

    echo -n "."
    let poweroff_attempts++

    if [ "$poweroff_attempts" == "20" ]; then
      echo "$BASENAME: guest $VM is still running"
      echo "$BASENAME: please consider to stop it using \"kvmx $VM stop\""
      #kvmx_stop
      exit 1
    fi

    sleep 3
  done
  echo " done."
  #sleep 3
  #echo ""

  kvmx_status
}

# Alias for poweroff
function kvmx_down {
  kvmx_poweroff
}

# Alias for poweroff
function kvmx_halt {
  kvmx_poweroff
}

# Hibernate
function kvmx_hibernate {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: ssh_support is disabled for guest $VM"
    exit 1
  fi

  if ! kvmx_ssh test -s /swapfile; then
    echo "Seems like /swapfile is absent in the guest, aborting"
    exit 1
  fi

  # Currently 9p driver won't survive a reboot
  # Umount shared folders
  #if [ ! -z "$shared_folder" ] && [ ! -z "$shared_folder_mountpoint" ]; then
  #  echo "Umounting $shared_folder_mountpoint on guest..."
  #  echo "sudo umount $shared_folder_mountpoint" | kvmx_ssh

  #  if [ "$?" != "1" ]; then
  #    echo "Problem umounting $shared_folder_mountpoint, you might have errors when restoring"
  #  fi
  #elif [ ! -z "$shared_folders" ]; then
  #  local old_ifs="$IFS"
  #  local shared_item
  #  IFS=","
  #  for shared_item in $shared_folders; do
  #    local shared_folder_mountpoint="`echo $shared_item | cut -d ':' -f 3`"

  #    # Restore IFS for a while or kvmx_ssh won't work
  #    IFS="$old_ifs"
  #    echo "Umounting $shared_folder_mountpoint on guest..."
  #    echo "sudo umount $shared_folder_mountpoint" | kvmx_ssh

  #    if [ "$?" != "1" ]; then
  #      echo "Problem umounting $shared_folder_mountpoint, you might have errors when restoring"
  #    fi

  #    IFS=","
  #  done
  #  IFS="$old_ifs"
  #fi

  echo "which s2disk &> /dev/null && /usr/bin/sudo s2disk" | kvmx_ssh &> /dev/null

  echo "Checking if hibernation was successful..."
  sleep 3

  if kvmx_running; then
    echo "Unable to hibernate guest: please check guest configuration"
    exit 1
  else
    kvmx_xephyr_stop
    kvmx_status
  fi
}

# Reboot the guest
function kvmx_reboot {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  echo /usr/bin/sudo reboot | kvmx_ssh &> /dev/null
  sleep 3
  kvmx_status
}

# Rsync files to the guest
function kvmx_rsync_to {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: ssh_support is disabled for guest $VM"
    exit 1
  fi

  ORIG="$1"
  DEST="$2"

  if [ -z "$DEST" ]; then
    # Error
    #exit 1

    # Assume same as origin
    DEST="$ORIG"
  fi

  # Fix ~/ path
  if echo $DEST | grep -q -e "^$HOME"; then
    DEST="$(echo $DEST | sed -e "s|^$HOME|/home/$SSH_LOGIN|")"
  fi

  SSH="`cat $SSHFILE`"
  rsync -av --delete -e "$SSH_COMMAND -o Port=$SSH" --rsync-path "sudo rsync" $ORIG/ 127.0.0.1:$DEST/
}

# Rsync files to the guest
function kvmx_rsync_from {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: ssh_support is disabled for guest $VM"
    exit 1
  fi

  ORIG="$1"
  DEST="$2"

  if [ -z "$DEST" ]; then
    # Error
    #exit 1

    # Assume same as origin
    DEST="$ORIG"
  fi

  # Fix ~/ path
  if echo $ORIG | grep -q -e "^$HOME"; then
    ORIG="$(echo $ORIG | sed -e "s|^$HOME|/home/$SSH_LOGIN|")"
  fi

  SSH="`cat $SSHFILE`"
  rsync -av --delete -e "$SSH_COMMAND -o Port=$SSH" --rsync-path "sudo rsync" 127.0.0.1:$ORIG/ $DEST/
}

# Copy files from the guest
function kvmx_scp_from {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: ssh_support is disabled for guest $VM"
    exit 1
  fi

  ORIG="$1"
  DEST="$2"

  if [ -z "$DEST" ]; then
    # Error
    #exit 1

    # Assume same as origin
    DEST="$ORIG"
  fi

  # Fix ~/ path
  if echo $ORIG | grep -q -e "^$HOME"; then
    ORIG="$(echo $ORIG | sed -e "s|^$HOME|/home/$SSH_LOGIN|")"
  fi

  SSH="`cat $SSHFILE`"
  $SCP_COMMAND -o Port=$SSH 127.0.0.1:$ORIG $DEST
}

# Copy files to the guest
function kvmx_scp_to {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: ssh_support is disabled for guest $VM"
    exit 1
  fi

  ORIG="$1"
  DEST="$2"

  if [ -z "$DEST" ]; then
    # Error
    #exit 1

    # Assume same as origin
    DEST="$ORIG"
  fi

  # Fix ~/ path
  if echo $DEST | grep -q -e "^$HOME"; then
    DEST="$(echo $DEST | sed -e "s|^$HOME|/home/$SSH_LOGIN|")"
  fi

  SSH="`cat $SSHFILE`"
  $SCP_COMMAND -o Port=$SSH $ORIG 127.0.0.1:$DEST
}

# List guests
function kvmx_list {
  if [ -e "$GLOBAL_USER_CONFIG_FOLDER" ]; then
    ls -1 $GLOBAL_USER_CONFIG_FOLDER | xargs -L 6 | column -t -c 6
  fi
}

# Alias to list command
function kvmx_ls {
  kvmx_list
}

# Upgrade guest
function kvmx_upgrade {
  echo "sudo apt-get update && sudo apt-get dist-upgrade -y && sudo apt-get autoremove -y" | kvmx_ssh
}

# Initializes a new guest
function kvmx_init {
  FOLDER="$1"

  if [ -z "$FOLDER" ]; then
    if [ -z "$VM" ]; then
      VM="$(basename `pwd`)"
      FOLDER="$(dirname `pwd`)/$VM"
    else
      FOLDER="$(pwd)/$VM"
    fi
  else
    VM="$FOLDER"
    FOLDER="$(pwd)/$VM"
  fi

  if [ -e "$GLOBAL_USER_CONFIG_FOLDER/$VM" ]; then
    echo "$BASENAME: guest $VM already exists"
    exit 1
  fi

  if [ ! -d "$FOLDER" ]; then
    mkdir -p $FOLDER
  fi

  # Ensure we have an absolute folder name
  FOLDER="`cd $FOLDER &> /dev/null && pwd`"

  # Copy config from template
  if [ ! -e "$FOLDER/kvmxfile" ]; then
    cp $APP_BASE/kvmxfile $FOLDER/
    sed -i -e "s|hostname=\"machine\"|hostname=\"$VM\"|g" $FOLDER/kvmxfile
  fi

  # Create config entry
  __kvmx_create_config_entry
}

# Clone a guest
function kvmx_clone {
  if kvmx_running; then
    echo "$BASENAME: orig $VM is running, cannot clone."
    exit 1
  fi

  FOLDER="$1"
  DEST="`basename $FOLDER`"
  OPT="$2"

  if [ -z "$FOLDER" ]; then
    kvmx_usage
  fi

  # If dest is given without a full path, clone to the same basedir
  # as the original guest.
  if [ "$FOLDER" == "$DEST" ]; then
    FOLDER="`dirname $STORAGE`/$DEST"
  fi

  # Check if dest machine exists
  if [ -e "$GLOBAL_USER_CONFIG_FOLDER/$DEST" ]; then
    echo "$BASENAME: destination guest $DEST already exists."
    exit 1
  fi

  if [ -d "$FOLDER" ]; then
    echo "$BASENAME: destination $FOLDER already exists."
    exit 1
  fi

  # Ensure we have an absolute folder name
  mkdir -p $FOLDER
  FOLDER="`cd $FOLDER &> /dev/null && pwd`"
  rmdir $FOLDER

  # Copy image and configuration
  echo "Copying basebox..."
  if which rsync &> /dev/null; then
    if [ "$OPT" == "--skell" ]; then
      local exclude="--exclude=box.img"
    fi

    rsync -ah --sparse --progress $exclude $STORAGE/ $FOLDER/
  else
    cp -r --sparse=always $STORAGE/ $FOLDER/
  fi

  # Remove old state folder
  rm -rf $FOLDER/state/*

  # Copy kvmxfile if not present on $FOLDER
  if [ ! -e "$FOLDER/kvmxfile" ]; then
    cat $GLOBAL_USER_CONFIG_FOLDER/$VM > $FOLDER/kvmxfile
  fi

  # Create config entry
  ( cd $GLOBAL_USER_CONFIG_FOLDER && ln -s $FOLDER/kvmxfile $DEST )

  # Update config file
  new_image="$FOLDER/`basename $image`"
  sed -i -e "s|image=\"$image\"|image=\"$new_image\"|g" $FOLDER/kvmxfile
  sed -i -e "s|hostname=\"$VM\"|hostname=\"$DEST\"|g"   $FOLDER/kvmxfile

  # Rename keypair if exists
  if [ -e "$FOLDER/ssh/$VM.key" ]; then
    mv $FOLDER/ssh/$VM.key     $FOLDER/ssh/$DEST.key
    mv $FOLDER/ssh/$VM.key.pub $FOLDER/ssh/$DEST.key.pub
  fi

  if [ "$DATADIR" != "$STORAGE" ]; then
    echo "$BASENAME: please copy datadir $DATADIR manually"
  fi
}

# Alias to clone
function kvmx_copy {
  kvmx_clone $*
}

# Get, set or edit guest config
function kvmx_config {
  if [ -z "$1" ]; then
    if [ -z "$EDITOR" ]; then
      EDITOR="vi"
    fi

    if [ -e "$GLOBAL_USER_CONFIG_FOLDER/$VM" ]; then
      $EDITOR $GLOBAL_USER_CONFIG_FOLDER/$VM
    else
      echo "$BASENAME: $GLOBAL_USER_CONFIG_FOLDER/$VM: file not found."
    fi
  else
    #if [ -z "$2" ]; then
    #  echo "usage: $BASENAME $VM edit $1 <value>"
    #  exit 1
    #fi

    param="$1"
    shift

    if [ -z "$1" ]; then
      grep "^$param=" $KVMXFILE | \
        sed -e 's/="/=/' -e 's/"$//' -e "s/='/=/" -e "s/'$//" -e "s/^$param=//"
    elif ! grep -q "^$param=" $KVMXFILE; then
      echo "$param=\"$*\"" >> $KVMXFILE
    else
      sed -i -e "s#^$param=.*#$param=\"$*\"#" $KVMXFILE
    fi
  fi
}

# Unset a guest config by commenting it
function kvmx_config_unset {
  if [ ! -z "$1" ]; then
    sed -i -e "s/^$1=/#$1=/" $KVMXFILE
  else
    echo $BASENAME: missing config parameter
    exit 1
  fi
}

# Alias to config
function kvmx_edit {
  kvmx_config $*
}

# Stop a guest
function kvmx_stop {
  if kvmx_running; then
    PID="`kvmx_pid`"

    if [ -z "$PID" ]; then
      return 1
    fi

    kill $PID
    kvmx_xephyr_stop
  fi
}

# Kill a guest
function kvmx_kill {
  if kvmx_running; then
    PID="`kvmx_pid`"

    if [ -z "$PID" ]; then
      return 1
    fi

    kill -9 $PID
    kvmx_xephyr_stop
  fi
}

# Destroy a guest
function kvmx_destroy {
  #kvmx_stop

  if kvmx_running; then
    echo "$BASENAME: $VM is running, cannot destroy."
    exit 1
  fi

  rm -f  $image
  rm -rf $STATE_DIR

  echo "$BASENAME: removed image and state files, but not the whole $STORAGE folder."
}

# Shred a guest
function kvmx_shred {
  #kvmx_stop

  if kvmx_running; then
    echo "$BASENAME: $VM is running, cannot shred."
    exit 1
  fi

  if which shred &> /dev/null; then
    shred $image
    rm -f $image
  else
    echo "$BASENAME: error shreding $image: shred program not available."
    exit 1
  fi
}

# Wipe a guest
function kvmx_wipe {
  #kvmx_stop

  if kvmx_running; then
    echo "$BASENAME: $VM is running, cannot wipe."
    exit 1
  fi

  if which wipe &> /dev/null; then
    wipe -f $image
    rm   -f $image
  else
    echo "$BASENAME: error wiping $image: wipe program not available."
    exit 1
  fi
}

# Purge a guest and all its configuration
function kvmx_purge {
  kvmx_destroy
  rm -f $GLOBAL_USER_CONFIG_FOLDER/$VM
  echo "$BASENAME: removed $GLOBAL_USER_CONFIG_FOLDER/$VM config."
}

# Provision a machine
function kvmx_provision {
  if ! kvmx_running; then
    kvmx up $VM || exit 1
    #kvmx_up || exit 1
    #echo "$BASENAME: guest $VM is not running"
    #exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: ssh_support is disabled for guest $VM"
    exit 1
  fi

  if [ -z "$provision_command" ]; then
    echo "$BASENAME: error: parameter provision_command is not configured for $VM."
    exit 1
  fi

  echo "Syncing provision files into the guest..."

  # Always sync default provisioners
  SSH="`cat $SSHFILE`"
  ORIG="$KVMX_BASE/share/provision/"
  DEST="/usr/local/share/kvmx/provision/"

  echo "sudo mkdir -p `dirname $DEST`" | kvmx_ssh
  rsync -av --delete -e "$SSH_COMMAND -o Port=$SSH" $provision_rsync_opts --rsync-path "sudo rsync" $ORIG/ 127.0.0.1:$DEST/

  if [ ! -z "$provision_rsync" ]; then
    local old_ifs="$IFS"
    IFS=","

    for provision_item in $provision_rsync; do
      IFS="$old_ifs"
      ORIG="`echo $provision_item | cut -d ' ' -f 1`"
      DEST="`echo $provision_item | cut -d ' ' -f 2`"

      # Sync custom provisioners
      if [ "$ORIG" != "$KVMX_BASE/share/provision/" ] && [ "$DEST" != "/usr/local/share/kvmx/provision/" ]; then
        (
        # Go inside the project folder so a relative $ORIG works
        cd `dirname $KVMXFILE` &> /dev/null
        echo "sudo mkdir -p `dirname $DEST`" | kvmx_ssh
        rsync -av -e "$SSH_COMMAND -o Port=$SSH" $provision_rsync_opts --rsync-path "sudo rsync" $ORIG/ 127.0.0.1:$DEST/
        )
      fi
      IFS=","
    done

    IFS="$old_ifs"
  fi

  echo "Running provision command inside the guest..."
  echo "$provision_command $hostname $domain $mirror" | kvmx_ssh
}

# Print guest image file name
function kvmx_list_image {
  echo $image
}

# Print guest status
function kvmx_status {
  if kvmx_suspended; then
    echo "$BASENAME: $VM guest is suspended"
  elif kvmx_running; then
    echo "$BASENAME: $VM guest is running"
  else
    echo "$BASENAME: $VM guest is stopped"
    return
  fi

  PID="`kvmx_pid`"

  if [ -z "$PID" ]; then
    return 1
  fi

  ps $PID
}

# Print guest log
function kvmx_log {
  local logs=""

  if [ -s "$LOGFILE" ]; then
    logs="$logs $LOGFILE"
  fi

  if [ -s "$SPICELOG" ]; then
    logs="$logs $SPICELOG"
  fi

  if [ -s "$XPRALOG" ]; then
    logs="$logs $XPRALOG"
  fi

  if [ -s "$XDMCPLOG" ]; then
    logs="$logs $XDMCPLOG"
  fi

  if [ -z "$logs" ]; then
    echo "$BASENAME: $VM: all logs are empty"
    exit
  fi

  tail -F $logs
}

# Rotate SSH keys
function kvmx_rotate_sshkeys {
  # Generate new keypair
  mkdir -p "$DATADIR/ssh"
  SSHKEY="$DATADIR/ssh/$VM.key"
  __kvmx_ssh_keygen $SSHKEY.new "$user@`basename $image .img`"

  # Replace pubkey on server
  echo "touch ~/.ssh/authorized_keys.new && chmod 600 ~/.ssh/authorized_keys.new" | kvmx_ssh
  cat $SSHKEY.new.pub | kvmx_ssh "tee ~/.ssh/authorized_keys.new &> /dev/null"
  echo "mv ~/.ssh/authorized_keys.new ~/.ssh/authorized_keys" | kvmx_ssh

  # Replace keypair locally
  mv $SSHKEY.new     $SSHKEY
  mv $SSHKEY.new.pub $SSHKEY.pub
}

# Xpra integration
function kvmx_xpra {
  if ! which xpra &> /dev/null; then
    echo "$BASENAME: please install xpra package"
    exit 1
  fi

  if ! kvmx_running || kvmx_suspended; then
    echo "$BASENAME: $VM not running"
    exit 1
  fi

  local action="$1"
  shift

  SSH="`cat $SSHFILE`"

  if [ -z "$action" ]; then
    action="start"
  fi

  if [ "$action" == "start" ] || [ "$action" == "attach" ]; then
    nohup xpra $action --ssh="$SSH_COMMAND -p $SSH" ssh:127.0.0.1 $* &> $XPRALOG < /dev/null &
  else
    xpra $action --ssh="$SSH_COMMAND -p $SSH" ssh:127.0.0.1 $*
  fi
}

# X2Go integration
#function kvmx_x2go {
#  if ! which x2goclient &> /dev/null; then
#    echo "$BASENAME: please install x2goclient package"
#    exit 1
#  fi
#
#  if ! kvmx_running || kvmx_suspended; then
#    echo "$BASENAME: $VM not running"
#    exit 1
#  fi
#
#  SSH="`cat $SSHFILE`"
#
#  x2goclient --ssh-port=$SSH --ssh-key=$SSHKEY --session=$VM
#}

# Alias for up command
function kvmx_start {
  kvmx_up $*
}

# Alias for up command
function kvmx_run {
  kvmx_up $*
}

# Restart machine
function kvmx_restart {
  if ! kvmx_running; then
    echo "Guest $VM was not running, so starting it anyway..."
    kvmx_start
  else
    #if [ "$ssh_support" != "y" ]; then
    #  echo sudo reboot | kvmx_ssh
    #  exit
    #fi

    echo "Powering off guest $VM..."
    kvmx_poweroff

    echo "Starting guest $VM again..."
    kvmx_start
  fi
}

# Alias to restart
function kvmx_reboot {
  kvmx_restart $*
}

# Connect to the guest using VNC
function kvmx_vnc {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  GUEST_DISPLAY="`cat $DISPLAYFILE`"

  if [ -z "$vnc_client" ]; then
    vnc_client="virt-viewer"
  fi

  if which $vnc_client &> /dev/null; then
    if [ "$vnclient_client" == "virt-viewer" ]; then
      $vnc_client vnc://127.0.0.1:$GUEST_DISPLAY
    else
      GUEST_DISPLAY="`cat $DISPLAYFILE`"
      $vnc_client :$GUEST_DISPLAY
    fi
  else
    echo "$BASENAME: no vnc_client configured"
    exit 1
  fi
}

# Connect to the guest using XDMCP/Xephyr
# See http://jeffskinnerbox.me/posts/2014/Apr/29/howto-using-xephyr-to-create-a-new-display-in-a-window/
function kvmx_xephyr {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  # Clipboard sharing
  # https://ubuntuforums.org/showthread.php?t=1430363
  GUEST_DISPLAY="`cat $DISPLAYFILE`"
  XDMCP_PORT="`cat $XDMCPPORTFILE`"

  # Check for resolution configuration
  if [ ! -z "$resolution" ]; then
    resolution="-screen $resolution"
  else
    # Detect resolution dynamically
    if which xwininfo &> /dev/null; then
      resolution="`xwininfo -root | grep -- '-geometry' | cut -d '+' -f 1 | sed -e 's/-geometry//'`"

      # Check for resolution_x_offset and resolution_y_offset configuration
      if [ ! -z "$resolution_x_offset" ] || [ ! -z "$resolution_y_offset" ]; then
        local width="`echo $resolution  | cut -d 'x' -f 1`"
        local height="`echo $resolution | cut -d 'x' -f 2`"
        resolution="$(($width $resolution_x_offset))x$(($height $resolution_y_offset))"
      fi

      resolution="-screen $resolution"
    fi
  fi

  if ! which Xephyr &> /dev/null; then
    echo "$BASENAME: please install Xephyr"
    exit 1
  fi

  Xephyr :$GUEST_DISPLAY -to 3 -ac -port $XDMCP_PORT -query 127.0.0.1 $resolution &> $XDMCPLOG < /dev/null &

  XEPHYRPID="$!"
  echo "$XEPHYRPID" > $XEPHYRFILE

  # Give time to connect
  sleep 1

  # Set keyboard layout
  # Thanks https://unix.stackexchange.com/questions/304391/xephyr-keyboard-mapping-not-working-properly
  setxkbmap -display :0 -print | xkbcomp - :$GUEST_DISPLAY &> /dev/null

  # Fix window titles
  if which /usr/bin/xdotool &> /dev/null; then
    if [ ! -z "$xclient_windowmove" ]; then
      xdotool search --name "Xephyr on :" windowmove $xclient_windowmove
    fi

    xdotool search --name "Xephyr on :" set_window --name $VM
  fi
}

# Close Xephyr client
function kvmx_xephyr_stop {
  if [ ! -e "$XEPHYRFILE" ]; then
    if [ "$ACTION" == "xephyr_stop" ]; then
      echo "$BASENAME: Xephyr not running for guest $VM"
      exit 1
    else
      return
    fi
  fi

  XEPHYRPID="`cat $XEPHYRFILE`"

  if [ ! -z "$XEPHYRPID" ]; then
    kill $XEPHYRPID &> /dev/null
  fi
}

# Open a file inside a guest
function kvmx_open {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  ORIG="$1"

  if [ -z "$ORIG" ]; then
    echo "$BASENAME: missing file argument."
    exit 1
  elif [ ! -e "$ORIG" ]; then
    echo "$BASENAME: file not found: $ORIG"
    exit 1
  fi

  DEST_FOLDER="`kvmx ssh $VM /bin/mktemp -d`"
  DEST="$DEST_FOLDER/`basename $ORIG`"

  # Copy and open
  kvmx scp_to $VM $ORIG $DEST
  kvmx ssh    $VM DISPLAY=:0 /usr/bin/xdg-open $DEST

  # Copy back
  TMP_OPEN_FOLDER="`mktemp -d`"
  TMP_OPEN="$TMP_OPEN_FOLDER/`basename $ORIG`"
  kvmx scp_from $VM $DEST $TMP_OPEN

  # Check for changes
  if ! diff $TMP_OPEN $ORIG 2> /dev/null; then
    mv $TMP_OPEN $ORIG
  else
    rm -rf $TMP_OPEN_FOLDER
  fi

  # Remove from guest
  kvmx ssh $VM rm -rf $DEST_FOLDER
}

# Rename a guest
function kvmx_rename {
  if kvmx_running; then
    echo "$BASENAME: guest $VM is running"
    exit 1
  fi

  FOLDER="$1"
  DEST="`basename $FOLDER`"

  if [ -z "$FOLDER" ]; then
    kvmx_usage
  fi

  # If dest is given without a full path, rename to the same basedir
  # as the original guest.
  if [ "$FOLDER" == "$DEST" ]; then
    FOLDER="`dirname $STORAGE`/$DEST"
  fi

  # Check if dest machine exists
  if [ -e "$GLOBAL_USER_CONFIG_FOLDER/$DEST" ]; then
    echo "$BASENAME: destination guest $DEST already exists."
    exit 1
  fi

  if [ -d "$FOLDER" ]; then
    echo "$BASENAME: destination $FOLDER already exists."
    exit 1
  fi

  # Ensure we have an absolute folder name
  mkdir -p $FOLDER
  FOLDER="`cd $FOLDER &> /dev/null && pwd`"
  rmdir $FOLDER

  # Copy image and configuration
  echo "Renaming guest..."
  mv "$STORAGE" "$FOLDER"

  # Remove old state folder
  rm -rf $FOLDER/state/*

  # Create config entry
  ( cd $GLOBAL_USER_CONFIG_FOLDER && ln -s $FOLDER/kvmxfile $DEST )

  # Remove old kvmxfile
  rm $GLOBAL_USER_CONFIG_FOLDER/$VM

  # Update config file
  new_image="$FOLDER/`basename $image`"
  sed -i -e "s|image=\"$image\"|image=\"$new_image\"|g" $FOLDER/kvmxfile
  sed -i -e "s|hostname=\"$VM\"|hostname=\"$DEST\"|g"   $FOLDER/kvmxfile

  # Rename keypair if exists
  if [ -e "$FOLDER/ssh/$VM.key" ]; then
    mv $FOLDER/ssh/$VM.key     $FOLDER/ssh/$DEST.key
    mv $FOLDER/ssh/$VM.key.pub $FOLDER/ssh/$DEST.key.pub
  fi

  if [ "$DATADIR" != "$STORAGE" ]; then
    echo "$BASENAME: please move datadir $DATADIR manually"
  fi
}

# Alias to rename
function kvmx_move {
  kvmx_rename $*
}

# Alias to rename
function kvmx_mv {
  kvmx_rename $*
}

# Interface to QEMU monitor (thanks kvm-manager)
function kvmx_monitor {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if ! which socat &> /dev/null; then
    echo "$BASENAME: please install socat"
    exit 1
  fi

  if [ -z "$1" ]; then
    socat $MONITORFILE STDIO
  else
    socat STDIO $MONITORFILE <<EOF
$1
EOF
  fi
}

# Install system
function kvmx_install {
  if kvmx_running; then
    echo "$BASENAME: guest $VM is running"
    exit 1
  fi

  local media="$1"

  if [ -z "$media" ]; then
    echo "usage: $BASENAME install $VM <installation-media>"

    # Possible places to find existing ISOs
    local candidates="/var/cache/media/distros /usr/local/share/isos"

    for candidate in $candidates; do
      if [ -d "$candidate" ]; then
        results="`find $candidate -not -iwholename '*.git*' -name '*.iso' | sed -e 's/^/\t/'`"

        if [ ! -z "$results" ]; then
          echo "available images at $candidate:"
          echo ""
          echo -n "$results"
        fi
      fi
    done

    exit 1
  elif [ ! -e "$media" ]; then
    echo "$BASENAME: file not found: $media"
    exit 1
  fi

  if [ -z "$memory" ]; then
    memory="2048"
  fi

  if [ -z "$format" ]; then
    format="qcow2"
  fi

  if [ ! -e "$image" ]; then
    echo "Creating $image with size $size..."
    qemu-img create -f $format $image $size
  fi

  # Basic install command
  #kvm -m $memory -net nic,model=virtio -net user -drive file=$image -cdrom $media

  # Install using kvmx_up
  install=1
  cdrom=$media
  boot="once=dc"
  kvmx_up
}

# Alias to install
function kvmx_boot {
  kvmx_install $*
}

# Serial console
function kvmx_console {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  # Script hack, useful for servers when using su before attaching to a console
  # See https://serverfault.com/questions/116775/sudo-as-different-user-and-running-screen
  #script /dev/null && screen -x kvmx-$VM
  #script -q -c "screen -x kvmx-$VM" /dev/null

  screen -x kvmx-$VM
}

# Alias to console
function kvmx_serial {
  kvmx_console $*
}

# Compress guest image
function kvmx_compress {
  if kvmx_running; then
    echo "$BASENAME: guest $VM is running"
    exit 1
  fi

  # Avoid trying to convert guest using other images such as LVM volumes
  if [ "$format" != "qcow2" ]; then
    echo "$BASENAME: please convert guest $VM image to qcow2 and update your config"
    exit 1
  fi

  if [ "$qcow2_compression" == "1" ]; then
    compression="-c"
  fi

  # Size before compression
  local size_before_bytes="`du    $image | awk '{ print $1 }'`"
  local size_before_human="`du -h $image | awk '{ print $1 }'`"

  echo "$BASENAME: compressing $image..."
  qemu-img convert -O qcow2 -p $compression $image $image.new && mv $image.new $image || exit 1

  # Size after compression
  local size_after_bytes="`du    $image | awk '{ print $1 }'`"
  local size_after_human="`du -h $image | awk '{ print $1 }'`"

  # Ratio
  #local ratio="$(($size_after_bytes / $size_before_bytes))"
  local ratio="$(echo "scale=4 ; $size_after_bytes / $size_before_bytes" | bc -l)"

  echo "size before: $size_before_human"
  echo "size_after:  $size_after_human"
  echo "compression ratio: $ratio"
}

# Version
function kvmx_version {
  echo $VERSION
}

# Shell
function kvmx_shell {
  local last_exit_code="0"
  local restricted="$1"
  local restricted_actions=":status:start:stop:poweroff:suspend:resume:console:monitor"
        restricted_actions="$restricted_actions:wipe:shred:app_base:version:list_image:kill:ssh_finger:"

  # While a "quit" command isn't entered, read STDIN
  while read -rep "$last_exit_code kvmx:/${USER}@${VM}> " STDIN; do
    history -s "$STDIN"

    if [ "$STDIN" == "quit" ] || [ "$STDIN" == "exit" ] || [ "$STDIN" == "bye" ]; then
      break
    elif [ "$STDIN" == "shell" ]; then
      echo "Why you need nesting?"
    elif [[ -n "$STDIN" && "$STDIN" != "#"* ]]; then
      # If line is not empty or commented, process command
      STDIN=($STDIN)

      # But check first if we're in a restricted shell
      if [ "$restricted" == "restricted" ]; then
        if ! echo $restricted_actions | grep -q ":${STDIN[0]}:"; then
          echo "Running in restricted shell mode."
          echo "Allowed commands are only `echo $restricted_actions | tr ':' ' '`"
        else
          $APP_BASE/kvmx ${STDIN[0]} $VM ${STDIN[@]:1}
          last_exit_code="$?"
        fi
      else
        $APP_BASE/kvmx ${STDIN[0]} $VM ${STDIN[@]:1}
        last_exit_code="$?"
      fi
    fi
  done
}

# Xrandr integration
function kvmx_xrandr {
  if ! kvmx_running; then
    echo "$BASENAME: guest $VM is not running"
    exit 1
  fi

  if [ "$ssh_support" != "y" ]; then
    echo "$BASENAME: xrandr needs ssh_support config"
    exit 1
  fi

  if echo which xrandr | kvmx_ssh &> /dev/null; then
    local mode="`xrandr | grep '*+' | awk '{ print $1 }' | tr 'x' ' '`"

    if [ ! -z "$resolution_y_offset" ]; then
      local x="`echo $mode | awk '{ print $1 }'`"
      local y="`echo $mode | awk '{ print $2 }'`"

      mode="$x $(($y $resolution_y_offset))"
    fi

    if [ -z "$xrandr_device" ]; then
      xrandr_device="Virtual-0"
    fi

    local line="`cvt $mode  | tail -1   | sed -e 's/^Modeline//'`"
    local name="`echo $line | awk '{ print $1 }'`"

    echo "Setting Modeline $line..."

    echo DISPLAY=:0 xrandr --newmode                       $line | kvmx_ssh
    echo DISPLAY=:0 xrandr --addmode $xrandr_device        $name | kvmx_ssh
    echo DISPLAY=:0 xrandr --output  $xrandr_device --mode $name | kvmx_ssh
  fi
}

# Wrapper to kvmx-create
function kvmx_create {
  if kvmx_running || kvmx_suspended; then
    echo "$BASENAME: guest $VM is running or suspended, cannot (re-)create"
    exit 1
  fi

  kvmx-create $KVMXFILE

  if [ "$?" != "0" ]; then
    exit $?
  fi
}

# Disposable guest
function kvmx_disposable {
  local date="`date +%Y%m%d%I%M%S`"
  local disposable="$VM-disposable-$date"

  # Clone and ensure we use a backing file
  kvmx clone $VM $disposable --skell || exit 1
  echo "basebox=$VM"      >> $GLOBAL_USER_CONFIG_FOLDER/$disposable
  echo 'backing_file="1"' >> $GLOBAL_USER_CONFIG_FOLDER/$disposable

  kvmx up $disposable

  echo "Waiting for the VM $disposable to stop before erasing it..."

  local image="`kvmx list_image $disposable`"
  local folder="`dirname $image`"

  # Remove VM after it stopped
  while true; do
    if ! kvmx running $disposable; then
      kvmx purge $disposable
      rm -rf $folder
      exit
    fi

    sleep 10
  done
}

# Dispatch
if type kvmx_$ACTION 2> /dev/null | grep -q "kvmx_$ACTION ()"; then
  __kvmx_initialize $*

  if [ "$ACTION" != "app_base" ]; then
    shift $SHIFTARGS
  fi

  kvmx_$ACTION $*
else
  kvmx_usage
fi