summaryrefslogtreecommitdiff
path: root/install
blob: 1f3ea908a66baca38484241063b8937921d14f63 (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
#!/usr/bin/python

"""
Written by Igor Pashev <pashev.igor@gmail.com>

The author has placed this work in the Public Domain,
thereby relinquishing all copyrights. Everyone is free
to use, modify, republish, sell or give away this work
without prior consent from anybody.
"""
from __future__ import print_function

from DysonInstaller.hdd import HDD
from DysonInstaller.snack import *
from DysonInstaller.Network import *
from snack import *
from subprocess import Popen, PIPE, call
from pprint import pprint
from tempfile import mkstemp, mkdtemp
from urllib2 import urlopen, URLError, HTTPError
from time import sleep
from os.path import basename, exists
import os
import re
import sys
import math
import shutil
import traceback

# Snack screen
screen = None

# Physical network interfaces
physlinks = []

# List of disks installed on the system:
hdds = []

# List of zpools found on system:
zpools = []

# List of imported zpools, we should export them after installation:
imported_zpools = []

# Name of the root ZFS pool: either existing or newly created
rpool = None

# Name of the root slice, where ZFS root pool will be created (e. g. c0t0d0s0)
# Used for installing GRUB
rslice = None

# Object, describing solaris partition
solaris_partition = None

# XXX rslice and solaris_partition aare known only
# on new clean installations, so we allow installing GRUB
# only on new installations

# Created boot environment, e. g. rpoot/ROOT/osdy-0
bootenv = None

# Install root dir, mount point for bootenv
rootdir = None

# Version to install:
codename = 'messier'

# Arch to install:
# XXX Use dpkg-architecture when we support more ;-)
archname = 'illumos-amd64'

# Dyson mirrors:
mirror = None
mirrors = [
    ('http://apt.osdyson.org', 'Japan'),
    ('http://mirror-us.osdyson.org/apt/', 'USA'),
    ]

# Top of /rpool/boot/grub/menu.lst, if creating new file:
grub_top = r'''
foreground 343434
background F7FbFF
default 0
timeout 5
'''

# Entry in /rpool/boot/grub/menu.lst for newly created boot environment
# This string must be formatted.
# 0 is the partition number,
# a is the slice number; both are not used
grub_entry = r'''
title Dyson at {bootenv}
findroot (pool_{rpool},{partition},{slice})
bootfs {bootenv}
kernel$ /platform/i86pc/kernel/amd64/unix -B $ZFS-BOOTFS
module$ /platform/i86pc/amd64/boot_archive
'''


# Stages of debootstraping in order. Debootstrap gives
# progress for each stage, but we need entire progress.
# Format: mile : (a, z), where:
# - mile is a stage name, e. g. DOWNDEBS;
# - a, z - the start and the end position on progress bar,
#          e. i. a=0 z=100 - entire progress bar (100%);
miles = {
        'START'       : (0, 0),    # Dummy
        'DOWNREL'     : (0, 1),    # Downloading the 'Release' file
        'DOWNPKGS'    : (1, 5),    # Downloading the 'Packages' file
        'SIZEDEBS'    : (5, 10),   # Finding packags sizes
        'DOWNDEBS'    : (10, 25),  # Downloading packages (*.deb)
        'EXTRACTPKGS' : (25, 45),  # Extracting core packages
        'INSTCORE'    : (45, 50),  # Installing core packages
        'UNPACKREQ'   : (50, 60),  # Unpacking required packages
        'CONFREQ'     : (60, 70),  # Configuring required packages
        'UNPACKBASE'  : (70, 85),  # Unpacking the base system
        'CONFBASE'    : (85, 100), # Configuring the base system
}

# FS to be created in boot environment.
# Order is important.
befs = [
    {'name':'/usr', 'options':{}},
    {'name':'/usr/local', 'options':{
                                'compression':'on',
                                }},
    {'name':'/usr/src', 'options':{
                                'compression':'on',
                                }},
    {'name':'/var', 'options':{}},
    {'name':'/var/cache', 'options':{}},
    {'name':'/var/lib', 'options':{}},
    {'name':'/var/lib/dpkg', 'options':{
                                'compression' : 'on',
                                'setuid'      : 'off',
                                'devices'     : 'off',
                                }},
    {'name':'/var/log', 'options':{
                                'compression' : 'on',
                                'setuid'      : 'off',
                                'devices'     : 'off',
                                }},
    {'name':'/var/mail', 'options':{
                                'compression' : 'on',
                                'setuid'      : 'off',
                                'devices'     : 'off',
                                }},
    {'name':'/var/spool', 'options':{
                                'compression' : 'on',
                                'setuid'      : 'off',
                                'devices'     : 'off',
                                }},
    {'name':'/var/tmp', 'options':{
                                'compression' : 'on',
                                'setuid'      : 'off',
                                'devices'     : 'off',
                                }},
    ]

# XXX Not yet.
befs = []

class Abort(Exception):
    ''' User clicked "Cancel" '''
    pass
class NoDisks(Exception):
    ''' No Hard Drives found '''
    pass

def welcome():
    welcome = ButtonChoiceWindow(screen, "Welcome to the Dyson installer",
            '''
Dyson is an operating system derived from Debian and based on Illumos core. \
It uses Illumos unix kernel and libc, ZFS file system and SMF to manage system startup. \
To learn more visit http://osdyson.org

This installer will guide you through disk paritioning, filesystem creation, \
installation of base system and minimal configuration.

Please note, this system IS VERY EXPERIMENTAL. \
You can LOOSE ALL YOUR DATA which this system can reach ;-)

Whould you like to continue?''',
            buttons=[('Install Dyson', True), ('Exit the installer', False)], width=70)
    if not welcome:
        raise Abort('Installation canceled')

def get_zpool_slice(pool_name):
    result = []
    ''' Returns slices/disks (e. g. c0t4d0s0) on which zpool exists '''
    zpool_cmd = Popen(['zpool', 'status', pool_name], stderr=PIPE, stdout=PIPE)

    # Skip till the header:
    re_header = re.compile(r'NAME\s+STATE\s+READ\s+WRITE\s+CKSUM')
    for line in zpool_cmd.stdout:
        if re_header.search(line):
            break

    re_disk = re.compile(r'(\w+)\s+ONLINE(\s+\d+){3}')
    for line in zpool_cmd.stdout:
        m = re_disk.search(line)
        if m and not m.group(1) in [pool_name, 'mirror']:
            result.append(m.group(1))
    return result

def find_zpools():
    global zpools
    progress = ProgressMessage(screen, title='Please wait', text='Searching for ZFS pools ...')
    zpools = []
    zpool_cmd = Popen(['zpool', 'list', '-H', '-o', 'name'], stdout=PIPE, stderr=PIPE)
    for line in zpool_cmd.stdout:
        zpools.append(line.rstrip())
    zpool_cmd = Popen("zpool import | awk '/pool:/ {print $2}'", shell=True, stdout=PIPE, stderr=PIPE)
    for line in zpool_cmd.stdout:
        zpools.append(line.rstrip())

def find_hdds():
    global hdds
    progress = ProgressMessage(screen, title='Please wait', text='Searching for disks ...')
    hdds = []
    pat = re.compile('\d+\.\s+(\S+)\s+<(.+?)(\s+cyl.*)?>')
    format_cmd = Popen('format </dev/null', shell=True, stdout=PIPE)
    for line in format_cmd.stdout:
        m = pat.search(line)
        if m:
            name = m.group(1)
            desc = m.group(2)
            hdds.append(HDD(name, desc))
    if len(hdds) == 0:
        raise NoDisks('No disks found')


def choose_rpool():
    zpool_items = map(lambda x: (x, x), zpools)
    zpool_items.append(('Create new ZFS pool', None))

    choice = None

    buttons = [('Ok', 'ok'), ('Cancel', 'cancel')]

    while not choice in ['ok', 'cancel']:
        (choice, pool) = ListboxChoiceWindow(screen,
                title='Choose ZFS pool',
                text='Choose ZFS pool where Dyson will be installed.\n'
                'You can selected one of the existing pools or create a new one.',
                items=zpool_items,
                buttons=buttons,
                width=76,
                scroll=1,
                default=0,
                )
        # Enter is pressed:
        if choice == None:
            choice = 'ok'
    if choice == 'ok':
        return pool
    raise Abort('Pool choosing')

def create_root_slice(hdd_name):
    '''Create root slice (0) over entire Solaris partition'''
    progress = ProgressMessage(screen, title='Please wait',
            text='Formatting Solaris partition on disk "{}" ...'.format(hdd_name))

    fd, path = mkstemp()
    os.write(fd, 'partition\nmodify\n1\nyes\n0\n\n\n\n\n\n\nyes\n"{label}"\nquit\nquit\n'.format(label=hdd_name))
    os.close(fd)
    format_cmd = Popen(['format', '-f', path, '-d', hdd_name], stderr=PIPE, stdout=PIPE)
    out, err = format_cmd.communicate()
    os.unlink(path)
    if format_cmd.returncode != 0:
        ButtonChoiceWindow(screen, title='Creating of root slice failed',
                text=err, buttons = ['Ok'], width=70)
        return None
    return hdd_name + 's0'

def create_rpool(hdd):
    global rslice
    rslice = create_root_slice(hdd.name)
    if not rslice:
        return None
    pool_name = None
    for pool_no in ['', 1, 2, 3, 4, 5, 6, 7]:
        pool_name = 'rpool{}'.format(pool_no)
        if not pool_name in zpools:
            break
        else:
            pool_name = None;

    progress = ProgressMessage(screen, title='Please wait',
            text='Creating ZFS pool "{rpool}" on slice "{slice}" ...'.format(rpool=pool_name, slice=rslice))

    zpool_cmd = Popen(['zpool', 'create', '-R', '/mnt/'+pool_name,
        '-m', '/' + pool_name,  '-f', pool_name, rslice],
            stderr=PIPE, stdout=PIPE)
    out, err = zpool_cmd.communicate()
    if 0 != zpool_cmd.returncode:
        ButtonChoiceWindow(screen,
                title='Creating of ZFS root pool failed',
                text=err, buttons = ['Ok'], width=70)
        return None
    imported_zpools.append(pool_name)
    return pool_name

def pool_is_imported(pool):
    rpool_is_imported = call(['zpool', 'status', pool], stdout=PIPE, stderr=PIPE)
    return rpool_is_imported == 0

def configure_rpool():
    global rpool
    find_zpools()
    while not rpool:
        if len(zpools) > 0:
            rpool = choose_rpool()
        if not rpool:
            hdd = choose_hdd(len(zpools))
            if hdd:
                rpool = create_rpool(hdd)
        if rpool:
            if not pool_is_imported(rpool):
                progress = ProgressMessage(screen, title='Please wait',
                        text='Importing ZFS pool "{}" ...'.format(rpool))
                zpool_cmd = Popen(['zpool', 'import', '-R', '/mnt/'+rpool, '-f', rpool], stderr=PIPE, stdout=PIPE)
                out, err = zpool_cmd.communicate()
                if 0 !=  zpool_cmd.returncode:
                    ButtonChoiceWindow(screen,
                            title='Importing of ZFS pool "{}" failed'.format(rpool),
                            text=err, buttons=['Ok'], width=70)
                    rpool = None
                imported_zpools.append(rpool)

def zfs_exists(fs):
    fs_exists = call(['zfs', 'list', '-H', fs], stdout=PIPE, stderr=PIPE)
    return fs_exists == 0

def zfs_create(fs, zvol=None, options={}):
    args = ['zfs', 'create']
    if zvol:
        args += ['-V', zvol]

    for o in options:
        args += ['-o', o + '=' + options[o]]

    args.append(fs)

    zfs_cmd = Popen(args, stderr=PIPE, stdout=PIPE)
    out, err = zfs_cmd.communicate()
    if 0 != zfs_cmd.returncode:
        ButtonChoiceWindow(screen,
                title='Creating of ZFS filesystem failed',
                text=err, buttons = ['Ok'], width=70)
        return False
    return True


def configure_zfs():
    global bootenv
    global rootdir
    progress = ProgressBar(screen,
            title='Creating ZFS filesystems',
            top = 4 + len(befs), # 4 for ROOT, /swap, /home, and BE
            width = 70,
            )
    root = rpool + '/ROOT'
    if not zfs_exists(root):
        progress.text = 'Creating ' + root
        zfs_create(root, options={'canmount':'off', 'mountpoint':'none'})
    progress.advance()

    swap = rpool + '/swap'
    if not zfs_exists(swap):
        progress.text = 'Creating ' + swap
        zfs_create(swap, zvol='2G')
    progress.advance()

    home = rpool + '/home'
    if not zfs_exists(home):
        progress.text = 'Creating ' + home
        zfs_create(home, options={'mountpoint':'/home', 'compression':'on',
            'devices':'off', 'setuid':'off'})
    progress.advance()

    # Make sure we are creating new boot environment
    for be_no in range(50):
        bootenv = root + '/osdy-' + str(be_no)
        if not zfs_exists(bootenv):
            break
        else:
            bootenv = None

    rootdir = mkdtemp(prefix='install-')
    progress.text = 'Creating ' + bootenv
    zfs_create(bootenv, options={'mountpoint':'legacy'})
    call(['mount', '-F', 'zfs', bootenv, rootdir])
    progress.advance()

    for fs in befs:
        p = bootenv + fs['name']
        progress.text = 'Creating ' + p
        zfs_create(p, options=fs['options'])
        progress.advance()

    # Will rollback if debootstrap fails
    call(['zfs', 'snapshot', '-r', bootenv + '@empty'])

def choose_hdd(number_of_zpools=0):
    hdd_items = map(lambda x: '{}: {} {}'.format(x.name, x.capacity, x.description), hdds)
    choice = None

    buttons = []
    buttons.append(('Use selected disk', 'ok'))
    if number_of_zpools > 0:
        buttons.append(('Back', 'zpool'))
    buttons.append(('Cancel', 'cancel'))


    while not choice in ['ok', 'zpool', 'cancel']:
        (choice, hdd_no) = ListboxChoiceWindow(screen,
                title='Choose hard disk drive',
                text='Choose a disk for the root ZFS pool',
                items=hdd_items,
                buttons=buttons,
                width=76,
                scroll=1,
                default=0,
                help=None
                )
        if choice in ['ok', None]:
            choice = configure_partitions(hdds[hdd_no], len(hdds))
            if choice == 'another':
                choice = None

    if choice == 'ok':
        return hdds[hdd_no]
    if choice == 'zpool':
        return None
    raise Abort('HDD choosing')

def configure_partitions(hdd, number_of_disks=1):
    global solaris_partition
    choice = None
    top_text = 'For the root ZFS pool you need a disk containing a Solaris partition (id 0xbf). \
If this disk includes such a partition and you are happy with it, use this disk. \
Otherwise you have to change partitioning. Note that only the first Solaris partition \
will be used.'

    while not choice in ['ok', 'another', 'cancel']:
        part_info = top_text
        part_info += '\n\n'

        have_partitions = len(hdd.partitions) > 0
        have_gpt = False
        solaris_partition = None
        buttons = []

        if have_partitions:
            part_info += 'Partitions on {name} {desc} {size}:\n\n'.format(
                    name=hdd.name, desc=hdd.description, size=hdd.capacity)
            part_info += '    TYPE    ID    NAME                     SIZE\n'
            n = 0
            for p in hdd.partitions:
                n = n + 1
                if p.id == 0xBF and solaris_partition == None:
                    solaris_partition = p
                if p.id == 0xEE:
                    have_gpt = True
                part_info += '#{n:<2} {primary} {id:#04x} {system:25} {capacity:10}\n'.format(
                    n=n, capacity=p.capacity, system=p.system, id=p.id,
                    primary=['primary', 'logical'][p.logical])
        else:
            part_info += 'This disk is not partitioned.\n'

        if solaris_partition != None:
            buttons.append(('Use this disk', 'ok'))

        if have_gpt:
            part_info += '\nThis disk has GUID Partition Table (GPT) and is unsupported.\n'
            # XXX gparted
        else:
            buttons.append(('Edit partitions', 'fdisk'))

        if number_of_disks > 1:
            buttons.append(('Back', 'another'))

        buttons.append(('Cancel', 'cancel'))

        choice = ButtonChoiceWindow(screen,
                title='Partitions of {}'.format(hdd.name),
                text=part_info,
                buttons=buttons,
                width=76,
                help=None
                )
        if choice == 'fdisk':
            screen.suspend()
            call(['cfdisk', hdd.raw_device])
            hdd.reread_partitions()
            screen.resume()
    # end while

    if choice == 'cancel':
        raise Abort('Partitioning')
    return choice

def get_mirror():
    if not hasattr(get_mirror, "m"):
        get_mirror.m=''
    while True:
        (choice, entry) = EntryWindow(screen,
                title='Enter APT repository URL',
                text='If you want to have line '
                '"deb ftp://192.168.1.1 bok main" in /etc/apt/sources.list '
                'enter "ftp://192.168.1.1" here.\n'
                'Remember to add URL protocol.\n',
                prompts=[('URL', get_mirror.m)],
                buttons = [ ('Ok', 'ok'), ('Back', 'back'), ('Cancel', 'cancel')],
                width=70,
                entryWidth=50,
                )
        if choice == 'back':
            return None
        if choice in ['ok', None]:
            get_mirror.m = entry[0].strip()
            if valid_mirror(get_mirror.m):
                return get_mirror.m
        if choice == 'cancel':
            raise Abort('Entering an APT mirror')

def choose_physlink():
    pass

def configure_network():
    global physlinks
    if not physlinks:
        physlinks = dladm_show_phys()
    if not physlinks:
        choice = ButtonChoiceWindow(screen, title='Network is unreachable',
                text='No network interfaces found on this system. '
                'This mean that public APT repositories cannot be used '
                'to install Dyson.',
                buttons=['Ok'])
        return
    while True:
        if len(physlinks) > 1:
            link = choose_physlink()
        else:
            link = physlinks[0]
        break

def valid_mirror(mirror):
    progress = ProgressMessage(screen, title='Please wait...',
            text='Checking APT mirror: ' + mirror)
    try:
        o = urlopen('{mirror}/dists/{codename}/Release'.format(
            mirror=mirror, codename=codename), timeout=15)
        have_code_name = False
        have_arch = False
        re_arch = re.compile(r'^Architectures:.+\b{archname}\b.*$'.format(archname=archname))
        re_code = re.compile(r'^Codename: +\b{codename}\b.*$'.format(codename=codename))
        for line in o.read(400).split('\n'):
            if re_code.match(line):
                have_code_name = True
            if re_arch.match(line):
                have_arch = True
            if have_code_name and have_arch:
                return True
        raise URLError('Not a valid Dyson APT repository')
    except HTTPError as e:
        ButtonChoiceWindow(screen,
                title='Error',
                text='{code} {reason}.\n\nMirror {mirror} is not usable.'.format(
                    mirror=mirror, code=e.code, reason=e.reason),
                buttons = ['Ok'], width=70)
    except URLError as e:
        ButtonChoiceWindow(screen,
                title='Error',
                text='{reason}.\n\nMirror {mirror} is not usable.'.format(
                    reason=e.reason,mirror=mirror),
                buttons = ['Ok'], width=70)
    except ValueError:
        ButtonChoiceWindow(screen,
                title='Failed to check mirror',
                text='Invalid URL: ' + mirror,
                buttons = ['Ok'], width=70)
    except Exception:
        ButtonChoiceWindow(screen,
                title='Failed to check mirror',
                text='Unknown error: ' + mirror,
                buttons = ['Ok'], width=70)
    return False

def configure_mirror():
    global mirror
    global mirrors
    maxlen = 0
    for m in mirrors:
        if len(m[0]) > maxlen:
            maxlen = len(m[0])
    items = map(lambda x: '{url: <{0}}  - {info}'.format(maxlen, url=x[0], info=x[1]), mirrors)
    items.append(('Enter another  mirror', None))
    mirror = None
    while not mirror:
        (choice, m) = ListboxChoiceWindow(screen,
                title='Choose APT mirror',
                text='Choose APT repository from which Dyson will be installed',
                items=items,
                buttons=[('Ok','ok'), ('Cancel', 'cancel')],
                width=76,
                scroll=1,
                default=0,
                )
        if choice in ['ok', None]:
            if m == None:
                mirror = get_mirror()
            else:
                if valid_mirror(mirrors[m][0]):
                    mirror = mirrors[m][0]
        if choice == 'cancel':
            raise Abort('Choosing APT mirror')


def debootstrap():
    progress = ProgressBar(screen,
            title='Installing base system, please wait...',
            width=70)

    progress.text = ' '

    read, write = os.pipe()

    os.makedirs(rootdir + '/root')
    log = os.open(rootdir + '/root/debootstrap.log', os.O_WRONLY + os.O_CREAT)

    pid = os.fork()
    if pid == 0:
        os.close(read)
        os.dup2(write, 3)
        os.dup2(log, 1)
        os.dup2(log, 2)
        os.close(log)
        os.close(write)
        try:
            os.execl('/usr/sbin/debootstrap', 'debootstrap',
                    '--debian-installer', '--no-check-gpg',
    '--exclude=gawk,aptitude,aptitude-common,libboost-iostreams1.48.0,libboost-iostreams1.49.0,libcwidget3',
                    '--include=illumos-grub,illumos-kernel,locales,bash-completion,vim',
                    codename,  rootdir, mirror)
        except EnvironmentError as e:
            sys.exit(e.errno)
    else:
        os.close(write)
        di = os.fdopen(read, 'r', 1)
        info_re = re.compile(' +')
        m = 'START'
        IA = [] # Arguments for IF, cleaned after each IF
        PA = [] # Arguments for PF, cleaned after each PF
        EA = [] # Arguments for EF, cleaned after each EF
        WA = [] # Arguments for WF, cleaned after each WF
        while True:
            line = di.readline()
            if not line:
                break
            try:
                colon = line.find(':')
                if colon == -1:
                    continue
                cmd = line[:colon]
                info = line[colon+1:].strip()
                text = None
                if cmd == 'P': # "P: 23 454 XYZ" or "P: 123 3445"
                    p = info_re.split(info)
                    if len(p) == 3:
                        m = p[2].strip()
                    progress.progress = math.ceil(miles[m][0] + float(p[0])*(miles[m][1] - miles[m][0]) / float(p[1]))
                elif cmd == 'IA':
                    IA.append(info)
                elif cmd == 'PA':
                    PA.append(info)
                elif cmd == 'EA':
                    EA.append(info)
                elif cmd == 'WA':
                    WA.append(info)
                elif cmd == 'IF':
                    text = (info % tuple(IA))
                    IA = []
                elif cmd == 'PF':
                    text = (info % tuple(PA))
                    PA = []
                elif cmd == 'EF':
                    text = (info % tuple(EA))
                    EA = []
                elif cmd == 'WF':
                    text = (info % tuple(WA))
                    WA = []
                if text:
                    progress.text = text
                    os.write(log, text)
                    os.write(log, '\n')
            except:
                pass
        status = os.wait()[1]
        os.close(log)
        return os.WEXITSTATUS(status)

def install():
    while True:
        configure_mirror()
        code = debootstrap()
        if code == 0:
            return
        while True:
            choice = ButtonChoiceWindow(screen, title='Installation failed',
                    text='Debootstrap failed.',
                    buttons=[('View log', 'log'), ('Try again', 'again'), ('Cancel', 'cancel')],
                    width=40)
            if choice == 'log':
                screen.suspend()
                call(['less', rootdir + '/root/debootstrap.log'])
                screen.resume()
                continue
            if choice == 'again':
                break
            if choice == 'cancel':
                raise Abort('debootstrap failed')
        p = ProgressMessage(screen, title='Please wait', text='Undoing previous try ...')
        umount_in_bootenv() # debootstrap mounts required FS for us
        call(['zfs', 'rollback', '-r', bootenv + '@empty'])


def umount_in_bootenv():
    '''unmount all FS mounted in BE on final cleanup.
    These FS also may be left after interruption or debootstrap failure'''
    global bootenv
    global rootdir

    if not bootenv:
        return
    fslist = ['/dev/fd', '/proc', '/devices', '/home']
    for fs in fslist:
        call(['umount', rootdir + fs], stdout=PIPE, stderr=PIPE)

def in_bootenv(cmd):
    chroot = ['chroot', rootdir]
    chroot += cmd
    pobject = Popen(chroot, stderr=PIPE, stdout=PIPE)
    out, err = pobject.communicate()
    return (pobject.returncode, out, err)


def write_vfstab():
    vfstab='''
#device                        device          mount           FS      fsck    mount   mount
#to mount                      to fsck         point           type    pass    at boot options
#
fd                             -               /dev/fd         fd      -       no      -
swap                           -               /tmp            tmpfs   -       yes     -
/dev/zvol/dsk/{rpool}/swap       -               -               swap    -       no      -
'''.format(rpool=rpool)
    try:
        f = open(rootdir + '/etc/vfstab', 'w')
        print(vfstab, file=f)
        f.close()
    except:
        pass

# http://stackoverflow.com/questions/2532053/validate-a-hostname-string
def isValidNodename(hostname):
    if len(hostname) > 63:
        return False
    return re.match(r'^(?!-)[a-z0-9\-]+(?<!-)$', hostname) != None

def configure_nodename():
    nodename = 'frontier'
    while True:
        choice, entry = EntryWindow(screen, title='Set hostname',
                text='Please enter the hostname for this system',
                prompts=[('Hostname', nodename)],
                width=70, entryWidth=63, buttons = ['Ok'])
        nodename = entry[0].strip()
        if isValidNodename(nodename):
            break
        ButtonChoiceWindow(screen, title='Invalid hostname',
                text='The name "{}" is not a valid hostname'.format(nodename),
                buttons=['Ok'])
    try:
        f = open(rootdir + '/etc/nodename', 'w')
        print(nodename, file=f)
        f.close()
    except:
        pass

def configure_packages():
    screen.suspend()
    call(['chroot', rootdir, '/usr/sbin/dpkg-reconfigure', 'tzdata', 'locales'], stderr=PIPE)
    screen.resume()

def create_bootarchive():
    progress = ProgressMessage(screen, title='Please wait')
    progress.text = 'Creating boot archive, please wait ...'
    in_bootenv(['/sbin/bootadm', 'update-archive'])

def mount_in_bootenv():
    call(['mount', '-F' , 'lofs', '/devices', rootdir + '/devices'], stdout=PIPE, stderr=PIPE)
    call(['mount', '-F' , 'fd', '-', rootdir + '/dev/fd'], stdout=PIPE, stderr=PIPE)
    call(['mount', '-F' , 'proc', '-', rootdir + '/proc'], stdout=PIPE, stderr=PIPE)

def set_root_password():
    entry1 = Entry(width=30, password=1, returnExit=0)
    entry2 = Entry(width=30, password=1, returnExit=1)
    passwd = None
    while not passwd:
        choice, entries = EntryWindow(screen, title='Set root password',
                text='Enter the root password. The password is not shown, you have to type it twice.',
                prompts=[('Password', entry1), ('Confirm', entry2)],
                allowCancel=0, width=40, entryWidth=30, buttons=['Ok'])
        if entries[0] == entries[1]:
            passwd = entries[0]
        else:
            ButtonChoiceWindow(screen, title='Error',
                    text='Entries do not match. Try again.', buttons=['Ok'])
    chpasswd_cmd = Popen(['chpasswd', '-R', rootdir], stderr=PIPE, stdout=PIPE, stdin=PIPE)
    chpasswd_cmd.communicate(input='root:'+passwd)

def configure_bootenv():
    write_vfstab()
    mount_in_bootenv()
    in_bootenv(['/usr/sbin/devfsadm'])
    open(rootdir + '/reconfigure', 'w').close()
    configure_packages()
    configure_nodename()

    # quick and dirty: if network is configured on livecd, copy config into boot env
    try:
        shutil.copy2('/etc/ipadm/ipadm.conf',
                rootdir+'/etc/ipadm/ipadm.conf')
    except:
        pass
    set_root_password()
    create_bootarchive()


def slice4grub(s):
    '''c0t4d0s0 -> a, c0t4d0s3 -> d'''
    try:
        n = s[s.rfind('s')+1:]
        return chr(int(n) + ord('a'))
    except: # random
        return 'a'


def configure_grub():
    global rslice
    # write grub menu for references:
    try:
        menu = open(rootdir + '/boot/grub/menu.lst', 'w')
        print('# This file is just for references. It is not used by GRUB', file=menu)
        print('# Actual menu.lst used by GRUB is {}/boot/grub/menu.lst'.format(rpool), file=menu)
        print('# where {} is the name of root ZFS pool'.format(rpool), file=menu)
        print(grub_top, file=menu)
        print(grub_entry.format(rpool=rpool, bootenv=bootenv, partition=1, slice='a'), file=menu)
        menu.close()
    except:
        pass

    # Zpool was not created during installation, trying to guess slice name:
    if not rslice:
        slices = get_zpool_slice(rpool)
        if len(slices) == 1 and re.match(r'^\w+s\d+$', slices[0]):
            rslice = slices[0]

    items = []
    default = None
    text = ''
    if rslice:
        text += 'Installing GRUB on the master boot sector (MBR) '
        text += 'overrides any boot manager currently installed: '
        text += 'the system will always boot the GRUB in the solaris partition'
        items.append(('Install GRUB to MBR', 'mbr'))
        items.append(('Install GRUB to a partition only', 'partition'))
        items.append(('Only update GRUB menu', 'menu'))
        if rpool in zpools: # installing on existing pool
            default = 'menu'
        else:
            default = 'mbr'
    else:
        text += 'It looks like root ZFS pool "{rpool}" was not created during this installation, '.format(rpool=rpool)
        text += 'so installing GRUB is not supported. '
        text += 'Laterly you can consult {bootenv}/boot/grub/menu.lst for details.'.format(bootenv=bootenv)
        default = 'skip'
    items.append(('Do nothing', 'skip'))
    button, install = ListboxChoiceWindow(screen, title='Configure GRUB',
            text=text, items=items, buttons=['Ok'], width=50, default=default)
    if install == 'skip':
        return

    progress = ProgressMessage(screen, title='Configuring GRUB')
    installgrub_cmd = ['/usr/sbin/installgrub']
    if install == 'mbr':
        progress.text = 'Installing GRUB to the master boot record ...'
        installgrub_cmd += ['-f', '-m']
    elif install == 'menu': # dry run, just to get partition number
        progress.text = 'Updating GRUB menu ...'
        installgrub_cmd += ['-n']
    else:
        progress.text = 'Installing GRUB to partition ...'

    installgrub_cmd += [rootdir+'/boot/grub/stage1', rootdir+'/boot/grub/stage2',
            '/dev/rdsk/' + rslice]
    installgrub = Popen(installgrub_cmd, stdout=PIPE, stderr=PIPE)
    out, err = installgrub.communicate()
    if installgrub.returncode != 0:
        ButtonChoiceWindow(screen, title='Error',
            text='Installing of GRUB failed: '+err, buttons=['Ok'], width=60)

    m = re.search(r'stage1 written to partition (\d)', out)
    if m:
        partition = m.group(1)
    else:
        partition = 0 # Random
    rpool_path = '/mnt/{rpool}/{rpool}'.format(rpool=rpool)
    try:
        if not exists(rpool_path + '/boot'):
            os.mkdir(rpool_path + '/boot')
        if not exists(rpool_path + '/boot/grub'):
            os.mkdir(rpool_path + '/boot/grub')
        if not exists(rpool_path + '/boot/grub/bootsign'):
            os.mkdir(rpool_path + '/boot/grub/bootsign')
        if not exists(rpool_path + '/boot/grub/bootsign/pool_'+rpool):
            open(rpool_path + '/boot/grub/bootsign/pool_'+rpool, 'w').close()
        if not exists(rpool_path + '/boot/grub/menu.lst'):
            menu = open(rpool_path + '/boot/grub/menu.lst', 'w')
            print(grub_top, file=menu)
            menu.close()
        re_bootfs = re.compile(r'^\s*bootfs\s+' + bootenv)
        have_this_bootenv = False
        menu = open(rpool_path + '/boot/grub/menu.lst', 'r+')
        for line in menu:
            if re_bootfs.match(line):
                have_this_bootenv = True
                break
        if not have_this_bootenv:
            print(grub_entry.format(rpool=rpool, bootenv=bootenv,
                partition=partition, slice=slice4grub(rslice)),
                    file=menu)
        menu.close()
    except EnvironmentError as e:
        text = 'Failed to write GRUB configuration: '
        if e.filename:
            text += e.filename + ': '
        text += e.strerror
        ButtonChoiceWindow(screen, title='Error', text=text, buttons=['Ok'], width=60)


def cleanup(destroy_bootenv=False):
    global bootenv
    global rootdir
    progress = ProgressMessage(screen, title='Cleaning up')
    if bootenv:
        umount_in_bootenv()
        call(['umount', rootdir], stdout=PIPE, stderr=PIPE)
        if destroy_bootenv:
            progress.text='Destroying {}, please wait ...'.format(bootenv)
            call(['zfs', 'destroy', '-r',  bootenv], stdout=PIPE, stderr=PIPE)
        else:
            progress.text = 'Adjusting boot environment "{}" ...'.format(bootenv)
            call(['zfs', 'destroy', '-r',  bootenv + '@empty'], stdout=PIPE, stderr=PIPE)
            call(['zfs', 'set', 'canmount=noauto', bootenv], stdout=PIPE, stderr=PIPE)
            call(['zfs', 'set', 'mountpoint=/', bootenv], stdout=PIPE, stderr=PIPE)

        try:
            os.rmdir(rootdir)
        except:
            pass
        bootenv = None

    progress.text = 'Exporting ZFS pools ...'
    for pool in imported_zpools:
        call(['zpool', 'export', '-f',  pool], stdout=PIPE, stderr=PIPE)

def goodbye():
    ButtonChoiceWindow(screen, title='Success',
            text='The Dyson system is successfully installed and configured. '
            'Hopefully, it will boot :-)',
            buttons=['Reboot'])

screen = SnackScreen()
while True:
    try:
        screen.pushHelpLine('F2 - switch to console, F1 - switch back to the installer')
        welcome()
        screen.pushHelpLine(' ')
        find_hdds()
        configure_rpool()
        configure_zfs()
        install()
        configure_bootenv()
        configure_grub()
        goodbye()
        cleanup()
        break

    except Abort as e:
        choice = ButtonChoiceWindow(screen, title='Cancel installation',
                text='Installation is canceled. Would do you like to start it again or reboot?',
                buttons=[('Restart', 'restart'), ('Reboot', 'reboot')], width=50)
        cleanup(destroy_bootenv=True)
        if choice == 'reboot':
            break
    except NoDisks as e:
        ButtonChoiceWindow(screen, title='Error',
                text='No disks found on the system. '
                'Installation of Dyson is not possible.',
                buttons=['Reboot'])
        break
    except:
        ButtonChoiceWindow(screen, title='FATAL ERROR',
                text='The installer has badly failed:\n'+traceback.format_exc(),
                width=70, buttons=['Restart the installer'])
        cleanup(destroy_bootenv=True)

screen.finish()
sys.exit(0)