~zyga/lava-dashboard-tool/new-ui

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
#!/bin/bash
LAVA_DEPLOYMENT_TOOL_VERSION="0.2"

# Global Configuration

# Where all LAVA stuff is kept, this is meant to make /srv/lava extensible in the future
LAVA_ROOT=/srv/lava

# All LAVA instances are created relative to this path
LAVA_PREFIX=$LAVA_ROOT/instances

# Pip download cache 
export PIP_DOWNLOAD_CACHE=$LAVA_ROOT/.downloads

test -n "$http_proxy" && PIP_PROXY_OPTION="--proxy=$http_proxy"

# All LAVA uses this python version
LAVA_PYTHON=python2.6

# All of LAVA is being served by this uWSGI version
LAVA_UWSGI=0.9.9.2

# Current version of setup required by lava (global state)
export LAVA_SETUP_REQUIRED_VERSION=20

# Check if this installation is supported
export LAVA_SUPPORTED=0

# Installation and configuration steps (all the wizard_xxx install_xxx functions)
LAVA_INSTALL_STEPS="user fs venv database broker web_hosting app config_app"


os_check() {
    case `lsb_release -i -s` in
        Ubuntu)
            case `lsb_release -c -s` in
                lucid)
                    export LAVA_PYTHON=python2.6
                    # FIXME: Lucid is not supported
                    export LAVA_SUPPORTED=0
                    # Required system packages
                    LAVA_PKG_LIST="whiptail python-virtualenv python-pip git-core build-essential $LAVA_PYTHON-dev libxml2-dev apache2 apache2-dev postgresql rabbitmq-server mercurial"
                    ;;
                oneiric)
                    export LAVA_PYTHON=python2.7
                    export LAVA_SUPPORTED=1
                    LAVA_PKG_LIST="whiptail python-virtualenv python-pip git build-essential $LAVA_PYTHON-dev libxml2-dev apache2 apache2-dev postgresql rabbitmq-server mercurial"
                    ;;
            esac
            ;;
    esac
}


uid_check() {
    if [ $(id -u) = 0 ]; then
        echo "Running as root is not supported"
        exit 1
    fi
}


_load_configuration() {
    LAVA_INSTANCE=$1

    # Persistent config
    if [ -e $LAVA_PREFIX/$LAVA_INSTANCE/instance.conf ]; then
        . $LAVA_PREFIX/$LAVA_INSTANCE/instance.conf
        # TODO: ensure we have all essential variables or we die verbosely
    else
        # Legacy configs, no lava- prefix
        export LAVA_SYS_USER=$LAVA_INSTANCE
        export LAVA_DB_USER=$LAVA_INSTANCE
        export LAVA_DB_NAME=$LAVA_INSTANCE
        # Single static vhost
        export LAVA_RABBIT_VHOST=/
    fi

    export LAVA_SYS_USER
    export LAVA_DB_USER
    export LAVA_DB_NAME
    export LAVA_RABBIT_VHOST
}


_show_config() {
    cat <<INSTANCE_CONF
# Installation prefix
LAVA_PREFIX='$LAVA_PREFIX'
# Instance name
LAVA_INSTANCE='$LAVA_INSTANCE'
# System configuration (Unix-level)
LAVA_SYS_USER='$LAVA_SYS_USER'
# Apache configuration
LAVA_APACHE_VHOST='$LAVA_APACHE_VHOST'
LAVA_DEV_MODE='$LAVA_DEV_MODE'
# PostgreSQL configuration
LAVA_DB_NAME='$LAVA_DB_NAME'
LAVA_DB_USER='$LAVA_DB_USER'
LAVA_DB_PASSWORD='$LAVA_DB_PASSWORD'
# RabbitMQ configuration
LAVA_RABBIT_VHOST='$LAVA_RABBIT_VHOST'
LAVA_RABBIT_USER='$LAVA_RABBIT_USER'
LAVA_RABBIT_PASSWORD='$LAVA_RABBIT_PASSWORD'
# Scheduler configuration
LAVA_SCHEDULER_ENABLED='$LAVA_SCHEDULER_ENABLED'
INSTANCE_CONF
}


_save_config() {
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/
    cat >$LAVA_PREFIX/$LAVA_INSTANCE/instance.conf <<INSTANCE_CONF
# Installation prefix
LAVA_PREFIX='$LAVA_PREFIX'
# Instance name
LAVA_INSTANCE='$LAVA_INSTANCE'
# System configuration (Unix-level)
LAVA_SYS_USER='$LAVA_SYS_USER'
# Apache configuration
LAVA_APACHE_VHOST='$LAVA_APACHE_VHOST'
LAVA_DEV_MODE='$LAVA_DEV_MODE'
# PostgreSQL configuration
LAVA_DB_NAME='$LAVA_DB_NAME'
LAVA_DB_USER='$LAVA_DB_USER'
LAVA_DB_PASSWORD='$LAVA_DB_PASSWORD'
# RabbitMQ configuration
LAVA_RABBIT_VHOST='$LAVA_RABBIT_VHOST'
LAVA_RABBIT_USER='$LAVA_RABBIT_USER'
LAVA_RABBIT_PASSWORD='$LAVA_RABBIT_PASSWORD'
# Scheduler configuration
LAVA_SCHEDULER_ENABLED='$LAVA_SCHEDULER_ENABLED'
INSTANCE_CONF
}


widget_text_instance_configuration() {
    echo "Instance Configuration"
    echo "----------------------"
    echo
    echo "Before configuring your instance we need to ask you a few questions"
    echo "The defaults are safe so feel free to use them without any changes"
}


widget_whiptail_instance_configuration() {
    whiptail \
        --backtitle "LAVA Deployment Tool, version $LAVA_DEPLOYMENT_TOOL_VERSION" \
        --nocancel \
        --title "Instance Configuration" \
        --msgbox \
"
Before configuring your instance we need to ask you a few questions. The
defaults are safe so feel free to use them without any changes
" \
    9 78
}

_configure() {
    set +x
    export LAVA_INSTANCE="$1"
    # Defaults
    for install_step in $LAVA_INSTALL_STEPS; do
        defaults_$install_step
    done
    # Wizard loop
    while true; do
        show_widget instance_configuration
        # Wizard page loop
        num_steps=1
        for install_step in $LAVA_INSTALL_STEPS; do
            while true; do
                echo
                echo "Note: it is safe to CTRL-C at this stage!"
                wizard_$install_step && break
            done
        done
        echo
        echo "Configuration summary"
        echo "---------------------"
        echo
        _show_config
        echo
        # Response loop
        while true; do
            echo "(it is safe to CTRL-C at this stage!)"
            read -p "Is everything okay? (yes|no) " RESPONSE
            case "$RESPONSE" in
                yes|no)
                    break
                    ;;
            esac
        done
        if [ "$RESPONSE" = "yes" ]; then
            echo "Saving configuration"
            _save_config
            echo "Configuration done"
            break
        else
            echo "Going back to wizard"
            continue
        fi
    done
    set -x
}


_install() {
    for install_step in $LAVA_INSTALL_STEPS; do 
        echo "Running installation step $install_step"
        install_$install_step || die "Failed at $install_step"
    done
    echo "All installation is done"
}


widget_text_user_config() {
    LAVA_SYS_USER="$1"
    LAVA_SYS_USER_DESC="$2"
    echo "User account configuration"
    echo "^^^^^^^^^^^^^^^^^^^^^^^^^^"
    echo
    echo "We need to create a system user for this instance:"
    echo "System user account configuration"
    echo
    echo "User name:        '$LAVA_SYS_USER'"
    echo "User description: '$LAVA_SYS_USER_DESC'"
    echo
    echo "next   - Use the user name as is"
    echo "edit   - Edit the user name"
    echo
    read -p "Please please decide what to do: " RESPONSE
}


widget_whiptail_user_config() {
    LAVA_SYS_USER="$1"
    LAVA_SYS_USER_DESC="$2"

    RESPONSE=$(whiptail \
        --backtitle "LAVA Deployment Tool, version $LAVA_DEPLOYMENT_TOOL_VERSION" \
        --title "User account configuration" \
        --nocancel \
        --menu \
"We need to create a system user for this instance:
System user account configuration

User name:        '$LAVA_SYS_USER'
User description: '$LAVA_SYS_USER_DESC'" \
        15 78 2 \
        "next" "Use the user name as is" \
        "edit" "Edit the user name" \
        2>&1 >/dev/tty)
}


widget_text_user_change_name() {
    echo "Change system user name"
    echo "-----------------------"
    echo
    echo "User name must start with a lowercase letter and is limited"
    echo "to lowercase letters, numbers and the dash (-) character."
    echo
    read -p "New user name: " RESPONSE
}


widget_whiptail_change_user_name() {
    RESPONSE=$(whiptail \
        --backtitle "LAVA Deployment Tool, version $LAVA_DEPLOYMENT_TOOL_VERSION" \
        --title "Change system user name" \
        --inputbox \
"User name must start with a lowercase letter and is limited
to lowercase letters, numbers and the dash (-) character." \
        8 78 \
        "$1" \
        2>&1 >/dev/tty)
}


widget_text_invalid_user_name() {
    echo "Incorrect user name"
    echo "-------------------"
    echo
    echo "User name must start with a lowercase letter and is limited"
    echo "to lowercase letters, numbers and the dash (-) character."
}


widget_whiptail_invalid_user_name() {
    whiptail \
        --backtitle "LAVA Deployment Tool, version $LAVA_DEPLOYMENT_TOOL_VERSION" \
        --title "Incorrect user name" \
        --msgbox \
"User name must start with a lowercase letter and is limited
to lowercase letters, numbers and the dash (-) character." \
        8 78
}


defaults_user() {
    export LAVA_SYS_USER=lava-$LAVA_INSTANCE
}


pkglist_user() {
    true
}


wizard_user() {
    export LAVA_SYS_USER_DESC="User for LAVA instance $LAVA_INSTANCE"
    show_widget user_config "$LAVA_SYS_USER" "$LAVA_SYS_USER_DESC"
    case "$RESPONSE" in
        next)
            return 0  # loop complete
            ;;
        edit)
            if show_widget change_user_name "$LAVA_SYS_USER"; then
                LAVA_SYS_USER_NEW="$RESPONSE"
                if test -n "$LAVA_SYS_USER_NEW" && echo "$LAVA_SYS_USER_NEW" | grep -q -E -e '[a-z]+[-a-z0-9]*'; then
                    LAVA_SYS_USER="$LAVA_SYS_USER_NEW" 
                else
                    show_widget invalid_user_name
                fi
            fi
            ;;
        *)
            echo "Unexpected response $RESPONSE"
            ;;
    esac
    return 1  # another loop please
}


install_user() {
    logger "Creating system user for LAVA instance $LAVA_INSTANCE: $LAVA_SYS_USER"
    echo "Creating system user for LAVA instance $LAVA_INSTANCE: $LAVA_SYS_USER"
    sudo useradd --system --comment "$LAVA_SYS_USER_DESC" "$LAVA_SYS_USER"
}


defaults_fs() {
    true
}


pkglist_fs() {
    true
}


widget_text_fs_config() {
    echo "File system configuration"
    echo "^^^^^^^^^^^^^^^^^^^^^^^^^"
    echo
    echo "We need file system location for this instance"
    echo
    echo "Installation directory: $LAVA_PREFIX/$LAVA_INSTANCE"
    echo
    echo "Note: everything apart from the database and message"
    echo "broker state will be stored there"
    echo
    echo "(this is just a notification, it is not configurable)"
    echo
    echo "next    - continue"
    echo
    read -p "Please decide what to do: " RESPONSE
}


widget_whiptail_fs_config() {
    whiptail \
        --backtitle "LAVA Deployment Tool, version $LAVA_DEPLOYMENT_TOOL_VERSION" \
        --title "File system Configuration" \
        --nocancel \
        --msgbox "
Each LAVA instance resides in a separate file system directory. That directory contains all the application code, application log files, configuration and the so called 'media' files submitted to or generated by the system (for example test results, device log files and attachments).

Installation directory: $LAVA_PREFIX/$LAVA_INSTANCE

Note: application state is stored in a relational database that is outside of that directory. Message broker (if you are using one in your installation) state is also external.
" \
        17 78
    RESPONSE=next
}


wizard_fs() {
    show_widget fs_config
    case "$RESPONSE" in
        next)
            return 0  # loop complete
    esac
    return 1  # another loop please
}


install_fs() {
    logger "Creating filesystem structure for LAVA instance $LAVA_INSTANCE"
    # Create basic directory structure
    # Apache site:
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/etc/apache2/sites-available
    # Dispatcher configuration 
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-dispatcher
    # Dashboard reports
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/reports
    # Dashboard data views
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/views
    # Custom templates
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/templates
    # Static file cache
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/var/www/lava-server/static
    # Repository of precious user-generated data (needs backup)
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/media
    # Celery state 
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-celery
    # Log files
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/var/log
    # Sockets and other runtime stuff
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/run
    # Source code (used when tracking trunk)
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/src
    # Temporary files
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/tmp

    # Allow apache (running as www-data) to read our public web files 
    sudo chgrp -R www-data $LAVA_PREFIX/$LAVA_INSTANCE/var/www/lava-server/
    sudo chmod -R g+rXs $LAVA_PREFIX/$LAVA_INSTANCE/var/www/lava-server/
    # Allow instance user to read all lava-server settings
    sudo chgrp -R $LAVA_SYS_USER $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server
    sudo chmod -R g+rXs $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/
    # Allow instance to write to media directory
    sudo chgrp -R $LAVA_SYS_USER $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/
    sudo chmod -R g+rwXs $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/
    # Prevent anyone else from reading from the media directory
    sudo chmod -R o-rX $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/
    # Allow instance to store lava-celery state 
    sudo chgrp -R $LAVA_SYS_USER $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-celery/
    sudo chmod -R g+rwXs $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-celery/
    # Allow instance user to put stuff in runtime directory
    # and allow www-data to read from that directory
    sudo chown -R $LAVA_SYS_USER:www-data $LAVA_PREFIX/$LAVA_INSTANCE/run
    sudo chmod -R g+rXs $LAVA_PREFIX/$LAVA_INSTANCE/run
    # Allow instance to log stuff to log directory
    # Allow users in the adm group to read those logs
    sudo chown -R $LAVA_SYS_USER:adm $LAVA_PREFIX/$LAVA_INSTANCE/var/log
    sudo chmod -R g+rXs $LAVA_PREFIX/$LAVA_INSTANCE/var/log
    # Allow instance user to put stuff in temporary directory
    # Set the sticky and setgid bits there
    sudo chgrp -R $LAVA_SYS_USER $LAVA_PREFIX/$LAVA_INSTANCE/tmp
    sudo chmod -R g+rwtXs $LAVA_PREFIX/$LAVA_INSTANCE/tmp
}


defaults_venv() {
    true
}


pkglist_venv() {
    echo "https://github.com/zyga/pip/tarball/develop"
}


wizard_venv() {
    echo
    echo "Python virtual environment configuration"
    echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
    echo
    echo "We will use python virtualenv to isolate LAVA code from your system"
    echo
    echo "Python version: $LAVA_PYTHON"
    echo
    echo "You can interact with this source code (installation) as if it"
    echo "was globally by invoking the following line:"
    echo
    echo "$ . $LAVA_PREFIX/$LAVA_INSTANCE/bin/activate"
    echo
    echo "(Note that the intent is to source (read) the file, not execute it)"
    echo "When you are done just type:"
    echo
    echo "$ deactivate"
    echo
    echo "While inside your virtualenv you can invoke additional commands,"
    echo "most notably, lava-server manage ..."
    echo 
    echo "(this is just a notification, it is not configurable)"
    echo
    echo "next    - continue"

    read -p "Please decide what to do: " RESPONSE

    case "$RESPONSE" in
        next)
            return 0  # loop complete
    esac
    return 1  # another loop please
}


install_venv() {
    logger "Creating virtualenv using $LAVA_PYTHON for LAVA instance $LAVA_INSTANCE"

    # Create virtualenv
    virtualenv --no-site-packages --distribute $LAVA_PREFIX/$LAVA_INSTANCE -p $LAVA_PYTHON
}


defaults_database() {
    export LAVA_DB_NAME="lava-$LAVA_INSTANCE"
    export LAVA_DB_USER="lava-$LAVA_INSTANCE"
    export LAVA_DB_PASSWORD=$(dd if=/dev/urandom bs=1 count=128 2>/dev/null | md5sum | cut -d ' ' -f 1)
}


pkglist_database() {
    echo psycopg2 
}


widget_text_database_config() {
    local LAVA_DB_NAME="$1"
    local LAVA_DB_USER="$2"
    local LAVA_DB_PASSWORD="$3"
    echo "PostgreSQL configuration"
    echo "^^^^^^^^^^^^^^^^^^^^^^^^"
    echo
    echo "We will use PostgreSQL to store application state"
    echo "(apart from files that are just files in your filesystem)"
    echo
    echo "Database name: $LAVA_DB_NAME"
    echo "Database user: $LAVA_DB_USER"
    echo "     password: $LAVA_DB_PASSWORD (automatically generated)"
    echo
    echo "(this is just a notification, it is not configurable)"
    echo
    echo "next    - continue"
    echo
    read -p "Please decide what to do: " RESPONSE
}


wizard_database() {
    show_widget database_config "$LAVA_DB_NAME" "$LAVA_DB_USER" "$LAVA_DB_PASSWORD"
    case "$RESPONSE" in
        next)
            return 0  # loop complete
    esac
    return 1  # another loop please
}


install_database()
{
    logger "Creating database configuration for LAVA instance $LAVA_INSTANCE"

    # Create database configuration file
    cat >$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/default_database.conf <<DEFAULT_DATABASE_CONF
dbuser='$LAVA_DB_USER'
dbpass='$LAVA_DB_PASSWORD'
basepath=''
dbname='$LAVA_DB_NAME'
dbserver=''
dbport=''
dbtype='pgsql'
DEFAULT_DATABASE_CONF

    # Create database user
    sudo -u postgres createuser \
        --no-createdb \
        --encrypted \
        --login \
        --no-superuser \
        --no-createrole \
        --no-password \
        "$LAVA_DB_USER" \
        || die "Failed to create database user"

    # Set a password for our new user
    sudo -u postgres psql \
        --quiet \
        --command="ALTER USER \"$LAVA_DB_USER\" WITH PASSWORD '$LAVA_DB_PASSWORD'" \
        || die "Failed to set database password"

    # Create a database for our new user
    sudo -u postgres createdb \
        --encoding=UTF-8 \
        --owner="$LAVA_DB_USER" \
        --no-password \
        "$LAVA_DB_NAME" \
        || die "Failed to create a database"
}


defaults_broker() {
    export LAVA_RABBIT_VHOST="/lava-$LAVA_INSTANCE"
    export LAVA_RABBIT_USER="lava-$LAVA_INSTANCE"
    export LAVA_RABBIT_PASSWORD=$(dd if=/dev/urandom bs=1 count=128 2>/dev/null | md5sum | cut -d ' ' -f 1)
}


pkglist_broker() {
    true
}


wizard_broker() {
    echo
    echo "RabbitMQ configuration"
    echo "^^^^^^^^^^^^^^^^^^^^^^"
    echo
    echo "We will use RabbitMQ to coordinate the distributed state"
    echo "of various LAVA components. For isolation each instance"
    echo "has a separate 'virtual host' created inside RabbitMQ'"
    echo "and runs as a separate RabbitMQ user (this is not a"
    echo "system user account) and password"
    echo
    echo "Broker vhost: $LAVA_RABBIT_VHOST"
    echo "Broker user:  $LAVA_RABBIT_USER"
    echo "   password:  $LAVA_RABBIT_PASSWORD (automatically generated)"
    echo
    echo "(this is just a notification, it is not configurable)"
    echo
    echo "next    - continue"

    read -p "Please decide what to do: " RESPONSE

    case "$RESPONSE" in
        next)
            return 0  # loop complete
    esac
    return 1  # another loop please
}


install_broker() {
    set -x
    sudo rabbitmqctl add_user "$LAVA_RABBIT_USER" "$LAVA_RABBIT_PASSWORD"
    sudo rabbitmqctl add_vhost "$LAVA_RABBIT_VHOST"
    sudo rabbitmqctl set_permissions -p "$LAVA_RABBIT_VHOST" "$LAVA_RABBIT_USER" ".*" ".*" ".*"
    set +x
}


defaults_web_hosting() {
    export LAVA_APACHE_VHOST=$(hostname)
    export LAVA_DEV_MODE=no
}


pkglist_web_hosting() {
    echo "http://projects.unbit.it/downloads/uwsgi-$LAVA_UWSGI.tar.gz"
    echo "django-seatbelt"
    echo "django-debian"
}


wizard_web_hosting() {
    echo
    echo "Apache and uWSGI configuration"
    echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
    echo
    echo "We will use Apache 2 to serve static application files"
    echo "Apache will also use mod uWSGI to talk to the application"
    echo "servers running LAVA code"
    echo
    echo "Normally we use django-seatbelt to prevent importing code"
    echo "from outside of each instance (for isolation and reliability)"
    echo "but this may be annoying when you do development and have"
    echo "some code in your \$HOME directory."
    echo
    echo "Developer mode: $LAVA_DEV_MODE"
    echo
    echo "next    - continue"
    echo "dev     - toggle developer mode"

    read -p "Please decide what to do: " RESPONSE

    case "$RESPONSE" in
        next)
            return 0  # loop complete
            ;;
        dev)
            if [ $LAVA_DEV_MODE = yes ]; then
                LAVA_DEV_MODE=no
            else
                LAVA_DEV_MODE=yes
            fi
            return 1
            ;;
    esac
    return 1  # another loop please
}


install_web_hosting() {
    logger "Installing uWSGI and other hosting parts for LAVA instance $LAVA_INSTANCE"

    if [ \! -e /etc/apache2/mods-available/uwsgi.load ]; then
        logger "Building uWSGI apache module..."
        # NOTE: we may not have this file cached as we used bundle to get it
        if [ ! -e $PIP_DOWNLOAD_CACHE/http%3A%2F%2Fprojects.unbit.it%2Fdownloads%2Fuwsgi-$LAVA_UWSGI.tar.gz ]; then
            pip install $PIP_PROXY_OPTION --no-install http://projects.unbit.it/downloads/uwsgi-$LAVA_UWSGI.tar.gz || die "Failed to download uWSGI"
        fi
        ( cd $LAVA_PREFIX/$LAVA_INSTANCE/tmp && tar zxf $PIP_DOWNLOAD_CACHE/http%3A%2F%2Fprojects.unbit.it%2Fdownloads%2Fuwsgi-$LAVA_UWSGI.tar.gz )
        ( cd $LAVA_PREFIX/$LAVA_INSTANCE/tmp/uwsgi-$LAVA_UWSGI/apache2 && sudo apxs2 -c -i -a mod_uwsgi.c )
    fi

    if [ "$LAVA_DEV_MODE" = "yes" ]; then
        cat >$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/lava-server.wsgi <<INSTANCE_WSGI
# This file was automatically generated by lava-deployment-tool.sh
import os

# Force django to use the specified settings module.
os.environ['DJANGO_SETTINGS_MODULE'] = 'lava_server.settings.debian'
# And force django-debian to look at our instance-specific configuration directory
os.environ['DJANGO_DEBIAN_SETTINGS_TEMPLATE'] = '$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/{filename}.conf'

# Setup django WSGI handler
import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()
INSTANCE_WSGI
    else
        cat >$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/lava-server.wsgi <<INSTANCE_WSGI
# This file was automatically generated by lava-deployment-tool.sh
import os
import sys
from django_seatbelt import seatbelt

# We need those to get stuff like threading that seems not to be supported when
# running virtualenv. Despite virtualenv setting up symlinks for some of the
# .so files this one does not seem to work. More insight on if this is really
# the case welcome.
core_python_paths = [
    "/usr/lib/$LAVA_PYTHON",
    "/usr/lib/$LAVA_PYTHON/lib-dynload"]

# Construct new path starting with core python, followed by the rest
sys.path = core_python_paths + [path for path in sys.path if path not in core_python_paths]

# Filter path, allow only core python paths and prefix paths (no local/user/junk)
def allow_core_python(path):
    return path in core_python_paths

# In virtualenv sys.prefix points to the root of the virtualenv, outside it
# points to the prefix of the system python installation (typically /usr)
def allow_sys_prefix(path):
    return path.startswith(sys.prefix)

# seatbelt.solder filters sys.path according to the callbacks specified below.
seatbelt.solder(allow_callbacks=[allow_sys_prefix, allow_core_python])

# Print summary (for debugging)
# print "sys.prefix:", sys.prefix
# print "sys.path:"
# for path in sys.path:
#    print " - %s" % path

# Force django to use the specified settings module.
os.environ['DJANGO_SETTINGS_MODULE'] = 'lava_server.settings.debian'
# And force django-debian to look at our instance-specific configuration directory
os.environ['DJANGO_DEBIAN_SETTINGS_TEMPLATE'] = '$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/{filename}.conf'

# Setup django WSGI handler
import django.core.handlers.wsgi

# NOTE: Here one might also use applications = {'/': application} to define
# namespace mapping. I'm not sure if this is used by uWSGI or by any handler
# but I found that in the docs to uWSGI.
application = django.core.handlers.wsgi.WSGIHandler()
INSTANCE_WSGI
    fi

    # Create apache2 site
    cat >$LAVA_PREFIX/$LAVA_INSTANCE/etc/apache2/sites-available/lava-server.conf <<INSTANCE_SITE
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName $LAVA_APACHE_VHOST

    # Allow serving media, static and other custom files
    <Directory $LAVA_PREFIX/$LAVA_INSTANCE/var/www>
        Options FollowSymLinks
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    # This is a small directory with just the index.html file that tells users
    # about this instance has a link to application pages
    DocumentRoot        $LAVA_PREFIX/$LAVA_INSTANCE/var/www/lava-server

    # uWSGI mount point. For this to work the uWSGI module needs be loaded.
    # XXX: Perhaps we should just load it ourselves here, dunno.
    <Location />
        SetHandler              uwsgi-handler
        uWSGISocket             $LAVA_PREFIX/$LAVA_INSTANCE/run/uwsgi.sock
    </Location>

    # Make exceptions for static and media.
    # This allows apache to serve those and offload the application server
    <Location /static>
        SetHandler      none
    </Location>
    # We don't need media files as those are private in our implementation

</VirtualHost>
INSTANCE_SITE

    sudo ln -s $LAVA_PREFIX/$LAVA_INSTANCE/etc/apache2/sites-available/lava-server.conf /etc/apache2/sites-available/$LAVA_INSTANCE.conf

    # Create reload file
    echo "Touching this file will gracefully restart uWSGI worker for LAVA instance: $LAVA_INSTANCE" > $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/uwsgi.reload

    # Create uWSGI configuration file
    cat >$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/uwsgi.ini <<UWSGI_INI
[uwsgi]
home = $LAVA_PREFIX/$LAVA_INSTANCE
socket = $LAVA_PREFIX/$LAVA_INSTANCE/run/uwsgi.sock
chmod-socket = 660
wsgi-file = $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/lava-server.wsgi
master = true
workers = 8
logto = $LAVA_PREFIX/$LAVA_INSTANCE/var/log/lava-uwsgi.log
log-master = true
auto-procname = true
touch-reload = $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/uwsgi.reload
gid = $LAVA_SYS_USER
uid = $LAVA_SYS_USER
UWSGI_INI

    sudo a2ensite $LAVA_INSTANCE.conf
    sudo a2dissite 000-default || true
    sudo service apache2 restart
}


defaults_app() {
    true
}


pkglist_app() {
    cat $LAVA_REQUIREMENT
}


wizard_app() {
    echo
    echo "LAVA application configuration"
    echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
    echo
    return 0
}


install_app() {
    echo "Installing/upgrading application code from $LAVA_BUNDLE file"

    . $LAVA_PREFIX/$LAVA_INSTANCE/bin/activate
    set -x
    pip install $PIP_PROXY_OPTION "$LAVA_BUNDLE" || die "Failed to install application bundle"
    set +x
    deactivate

    if [ ! -e $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/settings.conf ]; then
        if [ -e $LAVA_PREFIX/$LAVA_INSTANCE/src/lava-server ]; then
            # We're in editable server mode, let's use alternate paths for tempates and static files
            echo "Generating $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/settings.conf for DEVELOPMENT"
            echo "This means that lava-server (which has to be special) is installed in editable mode"
            echo "Some of the paths will refer to $LAVA_PREFIX/$LAVA_INSTANCE/src/lava-server."
            echo "Even if you later on upgrade to non-editable lava-server those paths"
            echo "will remain to be in use untill you wipe your old config and upgrade again"
            cat >$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/settings.conf <<SETTINGS_CONF
{
    "DEBUG": false,
    "TEMPLATE_DIRS": [
        "$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/templates",
        "$LAVA_PREFIX/$LAVA_INSTANCE/src/lava-server/lava_server/templates/"
    ],
    "STATICFILES_DIRS": [
        ["lava-server", "$LAVA_PREFIX/$LAVA_INSTANCE/src/lava-server/lava_server/htdocs/"]
    ],
    "MEDIA_ROOT": "$LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/media",
    "STATIC_ROOT": "$LAVA_PREFIX/$LAVA_INSTANCE/var/www/lava-server/static",
    "MEDIA_URL": "/media/",
    "STATIC_URL": "/static/",
    "MOUNT_POINT": "/",
    "LOGIN_URL": "/accounts/login/",
    "LOGIN_REDIRECT_URL": "/",
    "BROKER_USER": "$LAVA_RABBIT_USER",
    "BROKER_VHOST": "$LAVA_RABBIT_VHOST",
    "BROKER_PASSWORD": "$LAVA_RABBIT_PASSWORD",
    "DATAREPORT_DIRS": [
        "$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/reports"
    ],
    "DATAVIEW_DIRS": [
        "$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/views"
    ]
}
SETTINGS_CONF
        else
            echo "Generating $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/settings.conf for PRODUCTION"
            cat >$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/settings.conf <<SETTINGS_CONF
{
    "DEBUG": false,
    "TEMPLATE_DIRS": [
        "$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/templates",
        "$LAVA_PREFIX/$LAVA_INSTANCE/lib/$LAVA_PYTHON/site-packages/lava_server/templates/"
    ],
    "STATICFILES_DIRS": [
        ["lava-server", "$LAVA_PREFIX/$LAVA_INSTANCE/lib/$LAVA_PYTHON/site-packages/lava_server/htdocs/"]
    ],
    "MEDIA_ROOT": "$LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/media",
    "STATIC_ROOT": "$LAVA_PREFIX/$LAVA_INSTANCE/var/www/lava-server/static",
    "MEDIA_URL": "/media/",
    "STATIC_URL": "/static/",
    "MOUNT_POINT": "/",
    "LOGIN_URL": "/accounts/login/",
    "LOGIN_REDIRECT_URL": "/",
    "BROKER_USER": "$LAVA_RABBIT_USER",
    "BROKER_VHOST": "$LAVA_RABBIT_VHOST",
    "BROKER_PASSWORD": "$LAVA_RABBIT_PASSWORD",
    "DATAREPORT_DIRS": [
        "$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/reports"
    ],
    "DATAVIEW_DIRS": [
        "$LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/views"
    ]
}
SETTINGS_CONF
    fi
fi
}


defaults_config_app() {
    export LAVA_SCHEDULER_ENABLED=yes
}


pkglist_config_app() {
    true
}


wizard_config_app() {
    local _question="Do you want to enable the scheduler in this instance?"
    whiptail --title "Enable the scheduler?" --yesno "$_question" 10 40 && LAVA_SCHEDULER_ENABLED=yes || LAVA_SCHEDULER_ENABLED=no
    return 0
}


install_config_app() {
    # Enable virtualenv
    . $LAVA_PREFIX/$LAVA_INSTANCE/bin/activate

    if [ "${LAVA_SCHEDULER_ENABLED-x}" = "x" ]; then
        # LAVA_SCHEDULER_ENABLED was not in the config.
        # Set it to 'yes' as that was the assumed behaviour before
        # LAVA_SCHEDULER_ENABLED was introduced.
        echo "Setting LAVA_SCHEDULER_ENABLED to 'yes'..."
        export LAVA_SCHEDULER_ENABLED='yes'
        _save_config
    fi

    echo "Building cache of static files..."
    set -x
    lava-server manage \
        --instance-template=$LAVA_ROOT/instances/{instance}/etc/lava-server/{{filename}}.conf \
        --instance=$LAVA_INSTANCE \
        build_static --noinput --link || die "Failed to update the cache of static content"
    set +x

    echo "Stopping instance for database changes..."
    set -x
    sudo stop lava-instance LAVA_INSTANCE=$LAVA_INSTANCE || true # in case of upgrades
    set +x

    echo "Synchronizing database..."
    set -x
    lava-server manage \
        --instance-template=$LAVA_ROOT/instances/{instance}/etc/lava-server/{{filename}}.conf \
        --instance=$LAVA_INSTANCE \
        syncdb --noinput || die "Failed to synchronize database (run non-migration db updates)"
    set +x

    echo "Running migrations..."
    set -x
    lava-server manage \
        --instance-template=$LAVA_ROOT/instances/{instance}/etc/lava-server/{{filename}}.conf \
        --instance=$LAVA_INSTANCE \
        migrate --noinput || die "Failed to run database migrations"
    set +x

    # Get out of virtualenv
    deactivate

    echo "Your instance is now ready, please start (or re-start) it with"
    echo "sudo start lava-instance LAVA_INSTANCE=$LAVA_INSTANCE"
}


cmd_setup() {
    SETUP_VER=0
    if [ -e $LAVA_PREFIX/.setup ]; then
        SETUP_VER=$(cat $LAVA_PREFIX/.setup)
    fi


    if [ $SETUP_VER -lt $LAVA_SETUP_REQUIRED_VERSION ]; then
        echo "===================="
        echo "LAVA Deployment Tool"
        echo "===================="
        echo
        echo "System preparation steps:"
        echo " 1) Installing $LAVA_PKG_LIST"
        echo " 2) Setting up $LAVA_PREFIX owned by you"
        echo " 3) Setting up $PIP_DOWNLOAD_CACHE for downloads"
        echo " 4) Setting up upstart jobs (incuding removal of stale jobs)"
        echo
        read -p "Type YES to continue: " RESPONSE
        test "$RESPONSE" = 'YES' || return
    
        echo "Updating apt cache..."
        sudo apt-get update

        echo "Installing english language pack, if needed"
        # XXX: I'm not 100% sure this is needed
        sudo apt-get install --yes language-pack-en

        # Use English locale, this is VERY important for PostgreSQL locale settings
        # XXX: I don't like en_US.UTF-8, is there any POSIX.UTF-8 we could use?
        echo "Installing essential packages, if needed"
        LANG=en_US.UTF-8 sudo apt-get install --yes $LAVA_PKG_LIST

        echo "Creating LAVA filesystem in $LAVA_PREFIX"
        sudo mkdir -p $LAVA_PREFIX
        echo "Making $(whoami) the owner of that location"
        sudo chown $(whoami):$(whoami) $LAVA_PREFIX 

        echo "Creating PIP download cache in $PIP_DOWNLOAD_CACHE and making it writable"
        sudo mkdir -p $PIP_DOWNLOAD_CACHE
        sudo chown $(whoami):$(whoami) $PIP_DOWNLOAD_CACHE 

        echo "Creating upstart script for: lava"
        sudo sh -c "cat >/etc/init/lava.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA (abstract task)"

start on runlevel [2345]
stop on runlevel [06]

post-start script
    logger "Started LAVA (all instances)"
end script

post-stop script
    logger "Stopped LAVA (all instances)"
end script
LAVA_CONF

        echo "Creating upstart script for: lava-instances"
        sudo sh -c "cat >/etc/init/lava-instances.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA (instances)"

start on starting lava

task

script
    for dir in \`ls /srv/lava/instances\`; do
        LAVA_INSTANCE=\`basename \$dir\`
# TODO: Check if the instance should start automatically on boot
        if [ -e $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf ]; then
            start lava-instance LAVA_INSTANCE=\$LAVA_INSTANCE
        fi
    done
end script
LAVA_CONF

        sudo rm -f "/etc/init/lava-uwsgi-workers.conf"

        echo "Creating upstart script for: lava-instance"
        sudo sh -c "cat >/etc/init/lava-instance.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA (instance)"

# Stop when lava is being stopped
stop on stopping lava

# Use LAVA_INSTANCE to differentiate instances
instance \$LAVA_INSTANCE

# Export the instance name so that we can use it in other
# related LAVA jobs.
export LAVA_INSTANCE

pre-start script
    # Don't start unless the instance configuration file is present
    if [ ! -e $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf ]; then
        stop
    else
        logger "LAVA instance (\$LAVA_INSTANCE) starting..."
    fi
end script

post-start script
    logger "LAVA instance (\$LAVA_INSTANCE) started"
end script

pre-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) stopping..."
end script

post-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) stopped"
end script
LAVA_CONF

        sudo rm -f /etc/init/lava-uwsgi-instance.conf

        echo "Creating upstart script for: lava-instance-uwsgi"
        sudo sh -c "cat >/etc/init/lava-instance-uwsgi.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA uWSGI worker"

# This is an instance job, there are many possible workers
# each with different instance variable.
instance \$LAVA_INSTANCE

# Stop and start along with the rest of the instance
start on starting lava-instance
stop on stopping lava-instance LAVA_INSTANCE=\$LAVA_INSTANCE
# TODO: make uwsgi compatible with upstart socket activation
# start on socket PROTO=unix PATH=$LAVA_PREFIX/\$LAVA_INSTANCE/run/uwsgi.sock

# We want each worker to respawn if it gets hurt.
respawn

# Announce activity
pre-start script
    # Don't start unless the instance configuration file is present
    if [ ! -e $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf ]; then
        stop
    else
        # Announce uWSGI becoming online
        logger "LAVA instance (\$LAVA_INSTANCE) uWSGI starting..."
    fi
end script

post-start script
    logger "LAVA instance (\$LAVA_INSTANCE) uWSGI started"
end script

pre-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) uWSGI stopping..."
end script

post-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) uWSGI stopped"
end script

# uWSGI wants to be killed with SIGQUIT to indicate shutdown
# NOTE: this is not supported on Lucid (upstart is too old)
# Currently no workaround exists
kill signal SIGQUIT

# Run uWSGI with instance specific configuration file
script
    # Load instance settings
    . $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf
    # Simluate virtualenv without spawing anything
    export VIRTUAL_ENV=$LAVA_PREFIX/\$LAVA_INSTANCE
    export PATH=\$VIRTUAL_ENV/bin:\$PATH
    # Start uwsgi, no forks, no daemons, gid/uid changing is managed by uwsgi
    exec $LAVA_PREFIX/\$LAVA_INSTANCE/bin/uwsgi --ini=$LAVA_PREFIX/\$LAVA_INSTANCE/etc/lava-server/uwsgi.ini
end script
LAVA_CONF

        echo "Removing stale upstart file (if needed): lava-celeryd-instance"
        sudo rm -f /etc/init/lava-celeryd-instance.conf

        echo "Creating upstart script for: lava-instance-celeryd"
        sudo sh -c "cat >/etc/init/lava-instance-celeryd.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA Celery worker"

# This is an instance job, there are many possible workers
# each with different instance variable.
instance \$LAVA_INSTANCE

# Stop and start along with the rest of the instance
# start on starting lava-instance
# stop on stopping lava-instance LAVA_INSTANCE=\$LAVA_INSTANCE
# FIXME: upstart + virtualenv + pid tracking + sudo is broken, needs attention, celery is not part of this release

# Respawn the worker if it got hurt
respawn

# Announce workers becoming online
pre-start script
    # Don't start unless the instance configuration file is present
    if [ ! -e $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf ]; then
        stop
    else
        # Announce uWSGI becoming online
        logger "LAVA instance (\$LAVA_INSTANCE) celery worker starting..."
    fi
end script

post-start script
    logger "LAVA instance (\$LAVA_INSTANCE) celery worker started"
end script

pre-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) celery worker stopping..."
end script

post-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) celery worker stopped"
end script

# Some workers can take a while to exit, this should be enough
kill timeout 360

kill signal SIGTERM

# Run celery daemon 
script
. $LAVA_PREFIX/\$LAVA_INSTANCE/bin/activate
exec sudo -u \$LAVA_INSTANCE VIRTUAL_ENV=\$VIRTUAL_ENV PATH=\$PATH $LAVA_PREFIX/\$LAVA_INSTANCE/bin/lava-server manage celeryd --logfile=$LAVA_PREFIX/\$LAVA_INSTANCE/var/log/lava-celeryd.log --loglevel=info --events
end script

LAVA_CONF

        echo "Creating upstart script for: lava-instance-celerybeat"
        sudo sh -c "cat >/etc/init/lava-instance-celerybeat.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA Celery Scheduler"

# This is an instance job, there are many possible workers
# each with different instance variable.
instance \$LAVA_INSTANCE

# Stop and start along with the rest of the instance
# start on starting lava-instance
# stop on stopping lava-instance LAVA_INSTANCE=\$LAVA_INSTANCE
# FIXME: upstart + virtualenv + pid tracking + sudo is broken, needs attention, celery is not part of this release

# Respawn the worker if it got hurt
respawn

# Announce workers becoming online
pre-start script
    # Don't start unless the instance configuration file is present
    if [ ! -e $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf ]; then
        stop
    else
        logger "LAVA instance (\$LAVA_INSTANCE) celery scheduler starting..."
    fi
end script

post-start script
    logger "LAVA instance (\$LAVA_INSTANCE) celery scheduler started"
end script

pre-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) celery scheduler stopping..."
end script

post-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) celery scheduler stopped"
end script

# Run celery beat scheduler
script
. $LAVA_PREFIX/\$LAVA_INSTANCE/bin/activate
exec sudo -u \$LAVA_INSTANCE VIRTUAL_ENV=\$VIRTUAL_ENV PATH=\$PATH $LAVA_PREFIX/\$LAVA_INSTANCE/bin/lava-server manage celerybeat --logfile=$LAVA_PREFIX/\$LAVA_INSTANCE/var/log/lava-celerybeat.log --loglevel=info --pidfile=$LAVA_PREFIX/\$LAVA_INSTANCE/run/lava-celerybeat.pid --schedule=$LAVA_PREFIX/\$LAVA_INSTANCE/var/lib/lava-celery/celerybeat-schedule
end script
LAVA_CONF

        echo "Creating upstart script for: lava-instance-celerycam"
        sudo sh -c "cat >/etc/init/lava-instance-celerycam.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA Celery Camera (worker snapshot service)"

# This is an instance job, there are many possible workers
# each with different instance variable.
instance \$LAVA_INSTANCE

# Stop and start along with the rest of the instance
# start on starting lava-instance
# stop on stopping lava-instance LAVA_INSTANCE=\$LAVA_INSTANCE
# FIXME: upstart + virtualenv + pid tracking + sudo is broken, needs attention, celery is not part of this release

# Respawn the worker if it got hurt
respawn

# Announce workers becoming online
pre-start script
    # Don't start unless the instance configuration file is present
    if [ ! -e $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf ]; then
        stop
    else
        logger "LAVA instance (\$LAVA_INSTANCE) celery cam starting..."
    fi
end script

post-start script
    logger "LAVA instance (\$LAVA_INSTANCE) celery cam started"
end script

pre-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) celery cam stopping..."
end script

post-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) celery cam stopped"
end script

# Run celery camera
script
. $LAVA_PREFIX/\$LAVA_INSTANCE/bin/activate
exec sudo -u \$LAVA_INSTANCE VIRTUAL_ENV=\$VIRTUAL_ENV PATH=\$PATH $LAVA_PREFIX/\$LAVA_INSTANCE/bin/lava-server manage celerycam --logfile=$LAVA_PREFIX/\$LAVA_INSTANCE/var/log/lava-celerycam.log --loglevel=info --pidfile=$LAVA_PREFIX/\$LAVA_INSTANCE/run/lava-celerycam.pid
end script
LAVA_CONF

        echo "Creating upstart script for: lava-instance-scheduler"
        sudo sh -c "cat >/etc/init/lava-instance-scheduler.conf" <<LAVA_CONF
author "Zygmunt Krynicki"
description "LAVA Scheduler"

# This is an instance job, there are many possible workers
# each with different instance variable.
instance \$LAVA_INSTANCE

# Stop and start along with the rest of the instance
start on starting lava-instance
stop on stopping lava-instance LAVA_INSTANCE=\$LAVA_INSTANCE

# Respawn the worker if it got hurt
respawn

# Announce workers becoming online
pre-start script
    # Don't start unless the instance configuration file is present
    if [ ! -e $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf ]; then
        stop
    else
        . $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf
        # We only prevent the scheduler from running if
        # LAVA_SCHEDULER_ENABLED is set and set to 'no', to be most
        # compatible with the previous behaviour of always running the
        # scheduler.
        if [ "x\$LAVA_SCHEDULER_ENABLED" = "xno" ]; then
            stop
        else
            logger "LAVA instance (\$LAVA_INSTANCE) scheduler starting..."
        fi
    fi
end script

post-start script
    logger "LAVA instance (\$LAVA_INSTANCE) scheduler started"
end script

pre-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) scheduler stopping..."
end script

post-stop script
    logger "LAVA instance (\$LAVA_INSTANCE) scheduler stopped"
end script

script
    # Load instance settings
    . $LAVA_PREFIX/\$LAVA_INSTANCE/instance.conf
    # Simluate virtualenv without spawing anything
    export VIRTUAL_ENV=$LAVA_PREFIX/\$LAVA_INSTANCE
    export PATH=\$VIRTUAL_ENV/bin:\$PATH
    # Start LAVA scheduler, it runs as root in this release
    exec $LAVA_PREFIX/\$LAVA_INSTANCE/bin/lava-server manage --instance-template=$LAVA_PREFIX/{instance}/etc/lava-server/{{filename}}.conf --instance=\$LAVA_INSTANCE scheduler --logfile=$LAVA_PREFIX/\$LAVA_INSTANCE/var/log/lava-scheduler.log --loglevel=info
end script
LAVA_CONF

        # Store setup version
        echo $LAVA_SETUP_REQUIRED_VERSION > $LAVA_PREFIX/.setup
        echo "Setup complete, you can now install LAVA"
    else
        echo "This step has been already performed"
    fi
}


die() {
    echo "$1"
    exit 1
}


_banner() {
    echo "===================="
    echo "LAVA Deployment Tool"
    echo "===================="
    echo
}


cmd_install() {
    export LAVA_INSTANCE=$1
    export LAVA_BUNDLE=$2

    _banner

    if [ -z "$LAVA_INSTANCE" ]; then
        echo "You need to pass the name of the instance to create as first argument"
        return
    fi

    if [ -z "$LAVA_BUNDLE" ]; then
        echo "You need to pass the name of the bundle to use as second argument"
        return
    fi

    # Sanity checking, ensure that instance does not exist yet
    if [ -d "$LAVA_PREFIX/$LAVA_INSTANCE" ]; then
        echo "Instance $LAVA_INSTANCE already exists"
        return
    fi

    # Configure everything first (get all the answers)
    _configure "$LAVA_INSTANCE"
    # Roll the installation
    _install
}


cmd_upgrade() {
    export LAVA_INSTANCE=$1
    export LAVA_BUNDLE=$2

    _banner

    if [ -z "$LAVA_INSTANCE" ]; then
        echo "You need to pass the name of the instance to create as first argument"
        return
    fi

    if [ -z "$LAVA_BUNDLE" ]; then
        echo "You need to pass the name of the bundle to use as second argument"
        return
    fi

    # Sanity checking, ensure that instance exist
    if [ \! -d "$LAVA_PREFIX/$LAVA_INSTANCE" ]; then
        echo "Instance $LAVA_INSTANCE does not exist"
        return
    fi

    _load_configuration "$LAVA_INSTANCE"
    install_app || die "Failed to upgrade application code"
    install_config_app || die "Failed to run post-upgrade configuration"
}


cmd_remove() {
    LAVA_INSTANCE=${1:-dev}

    _banner

    # Sanity checking, ensure that instance exists
    if [ \! -d "$LAVA_PREFIX/$LAVA_INSTANCE" ]; then
        echo "Instance $LAVA_INSTANCE does not exist"
        return
    fi

    _load_configuration "$LAVA_INSTANCE"

    echo "*** WARNING ***" 
    echo "You are about to IRREVERSIBLY DESTROY the instance $LAVA_INSTANCE"
    echo "There is no automatic backup, there is no way to undo this step"
    echo "*** WARNING ***" 

    echo "We will remove system user $LAVA_SYS_USER"
    echo "We will remove PostgreSQL database $LAVA_DB_NAME"
    echo "We will remove PostgreSQL user: $LAVA_DB_USER"
    echo "We will remove everything in $LAVA_PREFIX/$LAVA_INSTANCE"
    echo "We will remove the apache site $LAVA_INSTANCE.conf"
    echo "We will remove the RabbitMQ user: $LAVA_RABBIT_USER"
    echo "We will remove the RabbitMQ vhost: $LAVA_RABBIT_VHOST"
    echo
    read -p "Type DESTROY to continue: " RESPONSE
    test "$RESPONSE" = 'DESTROY' || return

    logger "Removing LAVA instance $LAVA_INSTANCE"

    set -e
    set -x
    # Remove everything 
    sudo stop lava-instance LAVA_INSTANCE=$LAVA_INSTANCE || true
    sudo rm -f "/etc/apache2/sites-available/$LAVA_INSTANCE.conf" || true
    sudo rm -f "/etc/apache2/sites-enabled/$LAVA_INSTANCE.conf" || true
    sudo -u postgres dropdb "$LAVA_DB_NAME" || true
    sudo -u postgres dropuser "$LAVA_DB_USER" || true
    sudo rabbitmqctl delete_user "$LAVA_RABBIT_USER" || true
    sudo rabbitmqctl delete_vhost "$LAVA_RABBIT_VHOST" || true
    sudo userdel "$LAVA_SYS_USER" || true
    sudo rm -rf "$LAVA_PREFIX/$LAVA_INSTANCE" || true
    set +x
    set +e
}


cmd_restore() {
    LAVA_INSTANCE=${1}

    set -e

    # Sanity checking, ensure that instance exists
    if [ \! -d "$LAVA_PREFIX/$LAVA_INSTANCE" ]; then
        echo "Instance $LAVA_INSTANCE does not exist"
        return
    fi

    local SNAPSHOT_ID=${2}
    local SNAPSHOT_PATH="$LAVA_ROOT/backups/$LAVA_INSTANCE/$SNAPSHOT_ID"
    local SNAPSHOT_PATH_ALT="$LAVA_ROOT/backups/$SNAPSHOT_ID"

    if [ -e "$SNAPSHOT_PATH" ]; then
        SNAPSHOT="$SNAPSHOT_PATH"
    else
        if [ -e "$SNAPSHOT_PATH_ALT" ]; then
            SNAPSHOT="$SNAPSHOT_PATH_ALT"
        else
            echo "Cannot find snapshot called '$SNAPSHOT_ID'"
            echo "It should be in $SNAPSHOT_PATH or $SNAPSHOT_PATH_ALT (alternative)"
            return
        fi
    fi

    _load_configuration "$LAVA_INSTANCE"

    db_snapshot="$SNAPSHOT/database.dump"
    files_snapshot="$SNAPSHOT/files.tar.gz"

    if [ \! -f "$db_snapshot" -o \! -f "$files_snapshot" ]; then
        echo "$SNAPSHOT does not look like a complete snapshot"
        return
    fi

    echo "Are you sure you want to restore instance $LAVA_INSTANCE from"
    echo "$SNAPSHOT_ID?  This will DESTROY the existing state of $LAVA_INSTANCE"
    echo
    read -p "Type RESTORE to continue: " RESPONSE
    test "$RESPONSE" = 'RESTORE' || return

    # Load database configuration
    . $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/default_database.conf

    # Substitute missing defaults for IP-based connection this works around a bug
    # in postgresql configuration on default Ubuntu installs and allows us to use
    # the ~/.pgpass file.
    test -z "$dbport" && dbport=5432
    test -z "$dbserver" && dbserver=localhost

    if [ "$dbserver" != "localhost" ]; then
        echo "You can only run restore on the host on which postgres is running"
        return
    fi

    set -x

    # Stop the instance
    sudo stop lava-instance LAVA_INSTANCE=$LAVA_INSTANCE || true

    sudo -u postgres dropdb \
        --port $dbport \
        $dbname || true
    sudo -u postgres createdb \
        --encoding=UTF-8 \
        --owner=$dbuser \
        --port $dbport \
        --no-password \
        $dbname
    sudo -u postgres pg_restore \
        --exit-on-error --no-owner \
        --port $dbport \
        --role $dbuser \
        --dbname $dbname \
        $SNAPSHOT/database.dump > /dev/null

    sudo rm -rf $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/
    mkdir -p $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/
    tar \
        --extract \
        --gzip \
        --directory $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/ \
        --file "$files_snapshot"

    # Allow instance to write to media directory
    sudo chgrp -R $LAVA_SYS_USER $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/
    sudo chmod -R g+rwXs $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/

    echo "Done"
}


cmd_backup() {
    LAVA_INSTANCE=${1:-dev}

    set -e

    # Sanity checking, ensure that instance exists
    if [ \! -d "$LAVA_PREFIX/$LAVA_INSTANCE" ]; then
        echo "Instance $LAVA_INSTANCE does not exist"
        return
    fi

    # Load database configuration
    . $LAVA_PREFIX/$LAVA_INSTANCE/etc/lava-server/default_database.conf

    # Substitute missing defaults for IP-based connection this works around a bug
    # in postgresql configuration on default Ubuntu installs and allows us to use
    # the ~/.pgpass file.
    test -z "$dbserver" && dbserver=localhost
    test -z "$dbport" && dbport=5432

    export PGPASSWORD=$dbpass

    snapshot_id=$(TZ=UTC date +%Y-%m-%dT%H-%M-%SZ)

    echo "Making backup with id: $snapshot_id"

    destdir="$LAVA_ROOT/backups/$LAVA_INSTANCE/$snapshot_id"

    mkdir -p "$destdir"

    set -x

    echo "Creating database snapshot..."

    pg_dump \
        --no-owner \
        --format=custom \
        --host=$dbserver \
        --port=$dbport \
        --username=$dbuser \
        --no-password $dbname \
        --schema=public \
        > "$destdir/database.dump"

    echo "Backing up instance configuration..."
    tar --create \
        --gzip \
        --directory $LAVA_PREFIX/$LAVA_INSTANCE/ \
        --file "$destdir/etc.tar.gz" \
        etc

    echo "Creating file repository snapshot..."
    # tar exiting with code 1 means that the files changed under us as
    # tar was running.  As this is to be expected, we suppress that
    # exit code.  Exit code 2 means something bad happened, and we
    # should stop.
    GZIP='--rsyncable' tar \
        --create \
        --ignore-failed-read \
        --warning=no-file-changed \
        --gzip \
        --directory $LAVA_PREFIX/$LAVA_INSTANCE/var/lib/lava-server/ \
        --file "$destdir/files.tar.gz" \
        . || [ $? == 1 ]
    #   ^ There is a DOT HERE don't remove it

    ln -sfT "$destdir" "$LAVA_ROOT/backups/$LAVA_INSTANCE/latest"

    echo "Done"
}


cmd_manage() {
    LAVA_INSTANCE=${1:-dev}
    test -n '$1' && shift

    # Sanity checking, ensure that instance exists
    if [ \! -d "$LAVA_PREFIX/$LAVA_INSTANCE" ]; then
        echo "Instance $LAVA_INSTANCE does not exist"
        return
    fi
    _load_configuration "$LAVA_INSTANCE"

    # Enable virtualenv
    . $LAVA_PREFIX/$LAVA_INSTANCE/bin/activate

    set -x
    lava-server manage \
        --instance-template=$LAVA_ROOT/instances/{instance}/etc/lava-server/{{filename}}.conf \
        --instance=$LAVA_INSTANCE \
        "$@"
    set +x
}


cmd_bundle() {
    LAVA_REQUIREMENT=${1:-requirements.txt}
    LAVA_BUNDLE=${2:-lava.pybundle}
    local step
    for step in $LAVA_INSTALL_STEPS; do
        defaults_$step
    done
    LAVA_FULL_REQUIREMENT=$(mktemp)
    for step in $LAVA_INSTALL_STEPS; do
        pkglist_$step >> "$LAVA_FULL_REQUIREMENT"
    done
    echo "The resulting file can be copied for off-line installation"
    echo "Do you wnt to create $LAVA_BUNDLE with the following packages:"
    echo
    cat "$LAVA_FULL_REQUIREMENT"
    echo
    read -p "Type BUNDLE to continue: " RESPONSE
    test "$RESPONSE" = 'BUNDLE' || return
    set -x
    pip bundle "$LAVA_BUNDLE" $PIP_PROXY_OPTION --timeout=30 --use-mirrors --requirement="$LAVA_FULL_REQUIREMENT" || die "Failed to create bundle"
    set +x
    rm -f "$LAVA_FULL_REQUIREMENT"
}


show_widget() {
    # Show a named widget
    # -------------------
    #
    # Widget name must be passed as first argument. Any other arguments are
    # passed down to the widget function.
    #
    # Widget is implemented as a collection of functions with a common suffix.
    # All widgets need a text implementation that is prefixed with text_.
    # Whiptail based widgets can be implemented for better UI experience.
    # Widget set can be overriden by specifying LAVA_UI envirionment variable
    # (either 'text' or 'whiptail')

    # Get widget name and treat rest as arguments
    local widget=$1
    shift;
    # Find desired implementation
    # prefer whiptail if it is installed
    if [ "$LAVA_UI" = "" ]; then
        if [ -n "$(which whiptail)" ]; then
            LAVA_UI=whiptail
        else
            LAVA_UI=text
        fi
    fi
    # Fall back to text widget if requested widget is not implemented
    if [ "$(type -t widget_${LAVA_UI}_${widget})" != "function" ]; then
        LAVA_UI=text
    fi
    # Invoke the widget
    widget_${LAVA_UI}_${widget} "$@"
}


widget_whiptail_lava_not_supported() {
    whiptail \
        --backtitle "LAVA Deployment Tool, version $LAVA_DEPLOYMENT_TOOL_VERSION" \
        --nocancel \
        --ok-button "Quit" \
        --title "LAVA is not supported on this system" \
        --msgbox \
"Please report a bug on lava-deployment-tool
https://bugs.launchpad.net/lava-deployment-tool/+filebug

Please provide the following information

$(lsb_release -a 2>/dev/null)
" \
    15 78
}


widget_text_lava_not_supported() {
    echo "LAVA is not supported on this system"
    echo "------------------------------------"
    echo "Please report a bug on lava-deployment-tool"
    echo "https://bugs.launchpad.net/lava-deployment-tool/+filebug"
    echo
    echo "Please provide the following information"
    echo 
    lsb_release -a
}


main() {
    os_check
    uid_check
    if [ $LAVA_SUPPORTED = 0 ]; then
        show_widget lava_not_supported
        exit 1
    fi

    if [ -n "$1" ]; then
        cmd="$1"
        shift
    else
        cmd=help
    fi
    case "$cmd" in
        ^$|help)
            echo "Usage: lava-deployment-tool.sh <command> [options]"
            echo
            echo "Key commands:"
            echo "    setup   - prepare machine for LAVA (prerequisites)"
            echo "              (do this once before trying out others)"
            echo " working with instances:"
            echo "    bundle  - create a bundle in preparation for installing"
            echo "              or updating"
            echo "    install - install LAVA instance"
            echo "    upgrade - upgrade LAVA instance"
            echo "    remove  - remove LAVA instance (undoes install)"
            echo " working with data:"
            echo "    backup  - backup your data"
            echo "    restore - restore earlier backup (removes current data)"
            echo " working at lower level:"
            echo "    manage  - run lava-server management commands"
            echo
            echo "See the README file for instructions"
            ;;
        setup)
            cmd_setup "$@"
            ;;
        install|upgrade|remove)
            cmd_$cmd "$@" # 2>&1 | tee "$cmd-log-for-instance-$LAVA_INSTANCE.log"
            ;;
        manage)
            cmd_manage "$@"
            ;;
        backup)
            cmd_backup "$@"
            ;;
        restore)
            cmd_restore "$@"
            ;;
        install_*)
            set -x
            set -e
            _load_configuration "$@"
            $cmd
            set +x
            set +e
            ;;
        bundle)
            cmd_bundle "$@"
            ;;
        version)
            echo "LAVA Deployment Tool, version $LAVA_DEPLOYMENT_TOOL_VERSION."
            ;;
        show-wizard)
            local wizard_fn=wizard_$(echo "$1" | sed -e 's/-/_/g')
            local defaults_fn=defaults_$(echo "$1" | sed -e 's/-/_/g')
            local exit_code=
            LAVA_INSTANCE=example
            shift
            echo "Setting fake instance name to $LAVA_INSTANCE"
            echo "Running defaults function $defaults_fn"
            $defaults_fn
            echo "Running wizard function $wizard_fn"
            echo "(output enclosed in vvv and ^^^)"
            while [ "$exit_code" != 0 ]; do
                echo "vvv"
                $wizard_fn "$@"
                exit_code=$?
                echo "^^^"
                case $exit_code in
                    0)
                        echo "Wizard exit code: $exit_code (wizard loop complete)"
                        ;;
                    1)
                        echo "Wizard exit code: $exit_code (another loop requested)"
                        read -p "Press enter to start another loop"
                        ;;
                    *)
                        echo "Wizard exit code: $exit_code (unexpected code)"
                        ;;
                esac
            done
            ;;
        show-widget)
            local widget=$(echo $1 | sed -e 's/-/_/g')
            shift
            echo "Running widget $widget"
            echo "(output enclosed in vvv and ^^^)"
            echo "vvv"
            show_widget $widget "$@"
            echo "^^^"
            echo "Widget exit code is $?"
            echo "Widget response is: $RESPONSE"
            ;;
        *)
            echo "Unknown command: $cmd, try help"
            exit 1
            ;;
    esac
}


main "$@"