fslinstaller.py 24.4 KB
Newer Older
1
#!/usr/bin/env python
2
3
4
#
# FSL installer script.
#
5
6


7
from __future__ import print_function, division, unicode_literals
8
9


10
11
12
13
14
15
16
17
import functools      as ft
import os.path        as op
import subprocess     as sp
import                   os
import                   sys
import                   argparse
import                   contextlib
import                   getpass
Paul McCarthy's avatar
Paul McCarthy committed
18
import                   hashlib
19
20
21
22
23
24
import                   json
import                   logging
import                   platform
import                   shlex
import                   shutil
import                   tempfile
25

26
27
28
29
30
31
32
33
34
# TODO check py2/3
import                   urllib
import urllib.parse   as urlparse
import urllib.request as urlrequest


log = logging.getLogger(__name__)


Paul McCarthy's avatar
Paul McCarthy committed
35
36
37
38
39
40
41
42
43
44
45
46
__version__ = '0.0.0'
"""Installer version number. This is automatically updated in release versions
whenever a new version is released.
"""


DEFAULT_INSTALLATION_DIRECTORY = '/usr/local/fsl'
"""Default FSL installation directory. """


FSL_INSTALLER_MANIFEST = 'http://18.133.213.73/installer/manifest,json'
"""URL to download the FSL installer manifest file from. The installer
47
48
49
50
51
manifest file is a JSON file which contains information about available FSL
versions.

See the Context.download_manifest function, and an example manifest file
in test/data/manifest.json, for more details.
Paul McCarthy's avatar
Paul McCarthy committed
52
53
54
55
56
57
58
59
60
"""


class InvalidPassword(Exception):
    """Exception raised by Context.get_admin_password if the user gives an
    incorrect password.
    """


61
62
63
64
65
66
67
68
69
70
71
72
class UnknownVersion(Exception):
    """Exception raised by Context.build if the user has requested a FSL
    version that does not exist.
    """


class BuildNotAvailable(Exception):
    """Exception raised by Context.build if there is no available FSL version
    that matches the target platform and/or requested CUDA version.
    """


Paul McCarthy's avatar
Paul McCarthy committed
73
74
75
class Context(object):
    """Bag of information and settings created in main, and passed around
    this script.
76
77
78

    Several settings are lazily evaluated on first access, but once evaluated,
    their values are immutable.
Paul McCarthy's avatar
Paul McCarthy committed
79
80
81
    """

    def __init__(self, args):
82
83

        self.args = args
Paul McCarthy's avatar
Paul McCarthy committed
84
85

        # These attributes are updated on-demand via
86
87
88
89
90
91
92
        # the property accessors defined below, or all
        # all updated via the finalise-settings method.
        self.__platform       = None
        self.__cuda           = None
        self.__manifest       = None
        self.__build          = None
        self.__destdir        = None
Paul McCarthy's avatar
Paul McCarthy committed
93
94
        self.__need_admin     = None
        self.__admin_password = None
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


    def finalise_settings(self):
        self.platform
        self.cuda
        self.manifest
        self.build
        self.destdir
        self.need_admin
        self.admin_password


    @property
    def platform(self):
        """The platform we are running on, e.g. "linux-64", "macos-64". """
        if self.__platform is None:
            self.__platform = Context.identify_platform()
        return self.__platform


    @property
    def cuda(self):
        """The available CUDA version, or a CUDA version requested by the user.
        """
        if self.__cuda is not None:
            return self.__cuda
        if self.args.cuda is not None:
            self.__cuda = self.args.cuda
        if self.__cuda is None:
            self.__cuda = Context.identify_cuda()
        return self.__cuda


    @property
    def build(self):
        """Returns a suitable FSL build (a dictionary entry from the FSL
        installer manifest) for the target platform and CUDA version.
        """

        fslversion = self.args.fslversion
        if fslversion is None:
            fslversion = 'latest'

        if fslversion not in self.manifest['versions']:
            raise UnknownVersion(
                'FSL version {} is not available'.format(args.fslversion))

        if fslversion == 'latest':
            fslversion = self.manifest['versions']['latest']

        match = None

        for build in self.manifest['versions'][fslversion]:
            if build['platform']       == self.platform and \
               build.get('cuda', None) == self.cuda:
                match = build
                break
        else:
            raise BuildNotAvailable(
                'Cannot find a version of FSL matching platform '
                '{} and CUDA {}'.format(self.platform, self.cuda))

        return match
Paul McCarthy's avatar
Paul McCarthy committed
158
159
160
161


    @property
    def destdir(self):
162
163
164
165
166
        """Installation directory. If not specified at the command line, the
        user is prompted to enter a directory.
        """
        if self.args.dest is not None:
            self.__destdir = op.abspath(self.args.dest)
Paul McCarthy's avatar
Paul McCarthy committed
167
        if self.__destdir is None:
168
169
170
171
172
173
174
175
176
177
            while True:
                printmsg('Where do you want to install FSL?',
                         IMPORTANT, EMPHASIS)
                printmsg('Press enter to install to the default location [{}]'
                         .format(DEFAULT_INSTALLATION_DIRECTORY), INFO)
                response = prompt('FSL installation directory:', QUESTION)
                response = response.rstrip(op.sep)
                if response == '':
                    response = DEFAULT_INSTALLATION_DIRECTORY
                    break
Paul McCarthy's avatar
Paul McCarthy committed
178
                response  = op.abspath(response)
179
                parentdir = op.dirname(response)
Paul McCarthy's avatar
Paul McCarthy committed
180
181
182
                if op.exists(parentdir):
                    break
                else:
183
184
                    printmsg('Destination directory {} does not '
                             'exist!'.format(parentdir), ERROR)
Paul McCarthy's avatar
Paul McCarthy committed
185

186
            self.__destdir = response
Paul McCarthy's avatar
Paul McCarthy committed
187
188
189
190
191
        return self.__destdir


    @property
    def need_admin(self):
192
193
194
        """Returns True if administrator privileges will be needed to install
        FSL.
        """
Paul McCarthy's avatar
Paul McCarthy committed
195
196
        if self.__need_admin is not None:
            return self.__need_admin
197
198
199
        parentdir = op.dirname(self.destdir)
        self.__need_admin = Context.check_need_admin(parentdir)
        return self.__need_admin
Paul McCarthy's avatar
Paul McCarthy committed
200
201
202
203


    @property
    def admin_password(self):
204
205
        """Returns the user's administrator password, prompting them if needed.
        """
Paul McCarthy's avatar
Paul McCarthy committed
206
207
208
209
210
211
212
213
214
215
216
        if self.__admin_password is not None:
            return self.__admin_password
        if self.__need_admin == False:
            return None
        if self.__destdir is None:
            raise RuntimeError('Destination directory has not been set')
        self.__admin_password = Context.get_admin_password()


    @property
    def manifest(self):
217
        """Returns the FSL installer manifest as a dictionary. """
Paul McCarthy's avatar
Paul McCarthy committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
        if self.__manifest is None:
            self.__manifest = Context.download_manifest(self.args.manifest)
        return self.__manifest


    @staticmethod
    def identify_platform():
        """Figures out what platform we are running on. Returns a platform
        identifier string - one of:

          - "linux-64" (Linux, x86_64)
          - "macos-64" (macOS, x86_64)
        """

        platforms = {
            ('linux',  'x86_64') : 'linux-64',
            ('darwin', 'x86_64') : 'linux-64',
235
236
237

            # M1 builds (and possbily ARM for Linux)
            # will be added in the future
Paul McCarthy's avatar
Paul McCarthy committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
            ('darwin', 'arm64')  : 'macos-64',
        }

        system = platform.system().lower()
        cpu    = platform.machine()
        key    = (system, cpu)

        if key not in platforms:
            raise UnsupportedPlatform()

        return platforms[key]


    @staticmethod
    def identify_cuda():
        """Identifies the CUDA version supported on the platform. Returns a
254
255
        string containing the 'X.Y' CUDA version, or None if CUDA is not
        supported.
Paul McCarthy's avatar
Paul McCarthy committed
256
257
258
259
260
261
262
        """

        try:
            output = sp.check_output('nvidia-smi')
        except (sp.CalledProcessError, FileNotFoundError):
            return None

263
        cudaver = '9.2'  # TODO
Paul McCarthy's avatar
Paul McCarthy committed
264
265
266
267
        match   = None

        # Return the most suitable CUDA
        # version that we have a build for
268
269
270
271
        available_cudas = ['9.2', '10.2', '11.1']
        for available in reversed(supported_cudas):
            if float(cudaver) <= float(available):
                match = available
Paul McCarthy's avatar
Paul McCarthy committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
                break

        return match


    @staticmethod
    def check_need_admin(dirname):
        """Returns True if dirname needs administrator privileges to write to,
        False otherwise.
        """
        # TODO os.supports_effective_ids added in python 3.3
        return not os.access(dirname, os.W_OK | os.X_OK)


    @staticmethod
    def get_admin_password():
        """Prompt the user for their administrator password."""

        def validate_admin_password(password):
291
292
293
            proc = sudo_popen(['true'], password)
            proc.communicate()
            return proc.returncode == 0
Paul McCarthy's avatar
Paul McCarthy committed
294

Paul McCarthy's avatar
Paul McCarthy committed
295
296
297
298
299
300
301
302
        for attempt in range(3):
            if attempt == 0:
                msg = 'Your administrator password is needed to ' \
                      'install FSL: '
            else:
                msg = 'Your administrator password is needed to ' \
                      'install FSL [attempt {} of 3]:'.format(attempt + 1)
            printmsg(msg, IMPORTANT, end='', flush=True)
Paul McCarthy's avatar
Paul McCarthy committed
303
304
305
            password = getpass.getpass('')
            valid    = validate_admin_password(password)

Paul McCarthy's avatar
Paul McCarthy committed
306
307
308
309
310
            if valid:
                printmsg('Password accempted', INFO)
                break
            else:
                printmsg('Incorrect password', WARNING)
Paul McCarthy's avatar
Paul McCarthy committed
311
312
313
314
315
316
317
318
319
320
321
322
323

        if not valid:
            raise InvalidPassword()

        return password


    @staticmethod
    def download_manifest(url):
        """Downloads the installer manifest file, which contains information
        about available FSL vesrions, and the most recent version number of the
        installer (this script).

324
325
        The manifest file is a JSON file with the following structure (lines
        beginning with two forward-slashes are ignored):
Paul McCarthy's avatar
Paul McCarthy committed
326

327
          {
Paul McCarthy's avatar
Paul McCarthy committed
328
              "installer" : {
329
330
331
332
333
334
335
336
337
338

                  // Latest version of installer script
                  "version" : "1.2.3",

                  // URL to download installer script
                  "url"     : "http://abc.com/fslinstaller.py"

                  // SHA256 checksum of installer script
                  "sha256"  : "ab238........."
              },
Paul McCarthy's avatar
Paul McCarthy committed
339
340
              "versions" : {

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
                  // Latest must be present, and must
                  // contain the version number of the
                  // latest release
                  "latest" : "6.1.0",
                  "6.1.0"  : {
                      'linux-64' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-linux-64.yml",
                          "sha256"      : "ab23456...",
                      }
                      'macos-64' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-macos-64.yml",
                          "sha256"      : "ab23456...",
                      }
                      'linux-64-cuda9.2' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-linux-64-cuda9.2.yml",
                          "sha256"      : "ab23456...",
                      }
                      'linux-64-cuda10.2' : {
                          "environment" : "http;//abc.com/fsl-6.1.0-linux-64-cuda10.2.yml",
                          "sha256"      : "ab23456...",
                      }
                  }
                  "6.1.1" : {
                      ...
                  }
Paul McCarthy's avatar
Paul McCarthy committed
366
              }
367
          }
Paul McCarthy's avatar
Paul McCarthy committed
368
369
370
371
372
373
374
        """

        log.debug('Downloading FSL installer manifest from %s', url)

        with tempdir():
            download_file(url, 'manifest.json')
            with open('manifest.json') as f:
375
376
377
378
                lines = f.readlines()

        # Drop comments
        lines = [l for l in lines if not l.lstrip().startswith('//')]
Paul McCarthy's avatar
Paul McCarthy committed
379

380
        return json.loads('\n'.join(lines))
Paul McCarthy's avatar
Paul McCarthy committed
381
382


383
384
385
386
387
388
389
390
391
392
393
394
# List of modifiers which can be used to change how
# a message is printed by the printmsg function.
INFO      = 1
IMPORTANT = 2
QUESTION  = 3
PROMPT    = 4
WARNING   = 5
ERROR     = 6
EMPHASIS  = 7
UNDERLINE = 8
RESET     = 9
ANSICODES = {
395
396
397
398
399
400
401
402
403
    INFO      : '\033[37m',         # Light grey
    IMPORTANT : '\033[92m',         # Green
    QUESTION  : '\033[36m\033[4m',  # Blue+underline
    PROMPT    : '\033[36m\033[1m',  # Bright blue+bold
    WARNING   : '\033[93m',         # Yellow
    ERROR     : '\033[91m',         # Red
    EMPHASIS  : '\033[1m',          # White+bold
    UNDERLINE : '\033[4m',          # Underline
    RESET     : '\033[0m',          # Used internally
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
}


def printmsg(msg, *msgtypes, **kwargs):
    """Prints msg according to the ANSI codes provided in msgtypes.
    All other keyword arguments are passed through to the print function.
    """
    msgcodes = [ANSICODES[t] for t in msgtypes]
    msgcodes = ''.join(msgcodes)
    print('{}{}{}'.format(msgcodes, msg, ANSICODES[RESET]), **kwargs)


def prompt(prompt, *msgtypes, **kwargs):
    """Prompts the user for some input. msgtypes and kwargs are passed
    through to the printmsg function.
    """
    printmsg(prompt + ' ', *msgtypes, end='', **kwargs)
    return input().strip()


@contextlib.contextmanager
def tempdir():
    """Returns a context manager which creates and returns a temporary
    directory, and then deletes it on exit.
    """

    testdir = tempfile.mkdtemp()
    prevdir = os.getcwd()

    try:
        os.chdir(testdir)
        yield testdir

    finally:
        os.chdir(prevdir)
        shutil.rmtree(testdir)


def memoize(f):
    """Decorator to memoize a function. """

    cache = f.cache = {}
    def g(*args, **kwargs):
        key = (f, tuple(args), frozenset(kwargs.items()))
        if key not in cache:
            cache[key] = f(*args, **kwargs)
        return cache[key]
    return g


Paul McCarthy's avatar
Paul McCarthy committed
454
455
456
457
class ChecksumError(Exception):
    """Exception raised by the sha256 function if a file checksume does
    not match the expected checksum.
    """
458
459


460
def sha256(filename, check_against=None, blocksize=1048576):
Paul McCarthy's avatar
Paul McCarthy committed
461
462
463
    """Calculate the SHA256 checksum of the given file. If check_against
    is provided, it is compared against the calculated checksum, and an
    error is raised if they are not the same.
464
465
    """

Paul McCarthy's avatar
Paul McCarthy committed
466
    hashobj = hashlib.sha256()
467

Paul McCarthy's avatar
Paul McCarthy committed
468
469
470
471
472
473
    with open(filename, 'rb') as f:
        while True:
            block = f.read(blocksize)
            if len(block) == 0:
                break
            hashobj.update(block)
474

Paul McCarthy's avatar
Paul McCarthy committed
475
476
    checksum = hashobj.hexdigest()

477
    if check_against is not None:
Paul McCarthy's avatar
Paul McCarthy committed
478
        if checksum != check_against:
479
480
481
482
            raise ChecksumError('File {} does not match expected checksum '
                                '({})'.format(filename, check_against))

    return checksum
483

Paul McCarthy's avatar
Paul McCarthy committed
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
class Progress(object):
    def __init__(self, label='', transform=None, total=None, width=None):

        if transform is None:
            transform = Progress.default_transform

        self.width     = width
        self.total     = total
        self.label     = label
        self.transform = transform

    @staticmethod
    def default_transform(val):
        return val

    @staticmethod
    def bytes_to_mb(val):
        return val / 1048576


    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        print()

    def update(self, value, total=None):

        if self.width is None: width = 50 # TODO auto detect
        else:                  width = self.width

        if total is None:
            total = self.total

        value = self.transform(value)

        if total is not None:

            total     = self.transform(total)
            completed = int(round(width * (value  / total)))
            remaining = width - completed
            line      = '[{}{}] {:.1f} / {:.1f} {}'.format(
                '#' * completed,
                ' ' * remaining,
                value,
                total,
                self.label).rstrip()

        else:
            line = '{}{} ...'.format(value, self.label)

        printmsg(line, end='\r')

537

Paul McCarthy's avatar
Paul McCarthy committed
538
539
540
541
class DownloadFailed(Exception):
    """Exception type raised by the download_file function if a
    download fails for some reason.
    """
542
543


Paul McCarthy's avatar
Paul McCarthy committed
544
def download_file(url, destination, progress=None, blocksize=1048576):
Paul McCarthy's avatar
Paul McCarthy committed
545
546
    """Download a file from url, saving it to destination. """

547
548
    def default_progress(downloaded, total):
        pass
Paul McCarthy's avatar
Paul McCarthy committed
549

550
551
552
553
    if progress is None:
        progress = default_progress

    log.debug('Downloading %s ...', url)
Paul McCarthy's avatar
Paul McCarthy committed
554
555
556
557
558
559
560
561
562
563

    try:
        with urlrequest.urlopen(url) as req, \
             open(destination, 'wb') as outf:

            try:             total = int(req.headers['content-length'])
            except KeyError: total = None

            downloaded = 0

Paul McCarthy's avatar
Paul McCarthy committed
564
            progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
565
566
567
568
569
570
            while True:
                block = req.read(blocksize)
                if len(block) == 0:
                    break
                downloaded += len(block)
                outf.write(block)
571
                progress(downloaded, total)
Paul McCarthy's avatar
Paul McCarthy committed
572
573
574
575
576
577

    except urllib.error.HTTPError as e:
        raise DownloadFailed(f'A network error has occurred while '
                             f'trying to download {destname}') from e


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
def sudo_popen(cmd, password, **kwargs):
    """Runs "sudo cmd" using subprocess.Popen. """

    cmd  = ['sudo', '-S', '-k'] + cmd
    proc = sp.Popen(
        cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, **kwargs)
    proc.stdin.write('{}\n'.format(password).encode())
    return proc


def run(ctx, cmd, display_output=False, admin=False):
    """Runs the given command, as administrator if requested. """

    admin = admin and os.getuid() != 0

    log.debug('Running %s [as admin: %s]', cmd, admin)

    cmd = shlex.split(cmd)

    if admin:
        proc = sudo_popen(cmd, password)
    else:
        proc = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)

    (output, error) = proc.communicate()


class UnsupportedPlatform(Exception):
    """Exception raised by the identify_platform function if FSL is not
    available on this platform.
    """


def list_available_versions(ctx):
    """Lists available FSL versions. """
    printmsg('Available FSL versions:', EMPHASIS)
    for version in ctx.manifest['versions']:
        if version == 'latest':
            continue
        printmsg(version, IMPORTANT, EMPHASIS)
        for build in ctx.manifest['versions'][version]:
            if build.get('cuda', '').strip() != '':
                template = '  {platform} [CUDA {cuda}]'
            else:
                template = '  {platform}'
            printmsg(template.format(**build), EMPHASIS, end=' ')
            printmsg(build['environment'], INFO)


def install_miniconda(ctx):
    """Downloads the miniconda/miniforge installer, and installs it to the
    destination directory.
    """

    url      = ctx.manifest['installer']['miniconda'][ctx.platform]['url']
    checksum = ctx.manifest['installer']['miniconda'][ctx.platform]['sha256']

    printmsg('Downloading miniconda from {}...'.format(url))

Paul McCarthy's avatar
Paul McCarthy committed
637
638
639
    with Progress('MB', transform=Progress.bytes_to_mb) as prog:
        download_file(url, 'miniforge.sh', prog.update)

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
    sha256('miniforge.sh', checksum)
    cmd = 'sh miniforge.sh -b -p {}'.format(ctx.destdir)
    run(ctx, cmd, admin=ctx.need_admin)
    # TODO create .condarc


def install_fsl(ctx):
    """Install FSL into ctx.destdir (which is assumed to be a miniforge
    installation.
    """

    builds = ctx.manifest['versions'][ctx.args.fslversion][ctx.platform]
    for build in builds:
        if ctx.cuda == build.get('cuda', None):
            break
    else:
        raise

    if cudaver is not None:
        filename = 'fsl-{}-{}-cuda-{}.yml'.format(fslversion,
                                                  platform,
                                                  cudaver)
    else:
        filename = 'fsl-{}-{}.yml'.format(fslversion, platform)

    download_file(base + filename, 'environment.yml')

    conda = op.join(destdir, 'bin', 'conda')

    run(ctx, conda + ' env update -n base -f environment.yml',
        admin=ctx.need_admin)


def configure_environment(ctx):
    """Configures the user's shell environment (e.g. ~/.bash_profile). """
    # TODO
    pass


Paul McCarthy's avatar
Paul McCarthy committed
679
def self_update(ctx):
680
    """Checks to see if a newer version of the installer (this script) is
681
    available and if so, downloads it to a temporary file, and runs it in
Paul McCarthy's avatar
Paul McCarthy committed
682
    place of this script.
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
    """

    @ft.total_ordering
    class Version(object):
        """Class to hold and compare FSL installer version strings.  Version
        strings must be of the form X.Y.Z, where X, Y, and Z are all integers.
        """
        def __init__(self, verstr):
            major, minor, patch = verstr.split('.')[:3]
            self.verstr         = verstr
            self.major          = int(major)
            self.minor          = int(minor)
            self.patch          = int(patch)

        def __str__(self):
            return self.verstr

        def __eq__(self, other):
            return all((self.major == other.major,
                        self.minor == other.minor,
                        self.patch == other.patch))

        def __lt__(self, other):
            for p1, p2 in zip((self.major,  self.minor,  self.patch),
                              (other.major, other.minor, other.patch)):
                if p1 < p2: return True
                if p1 > p2: return False
            return False

    thisver   = Version(__version__)
Paul McCarthy's avatar
Paul McCarthy committed
713
    latestver = Version(ctx.manifest['installer']['version'])
714
715
716
717
718
719

    if latestver <= thisver:
        log.debug('Installer is up to date (this vesrion: %s, '
                  'latest version: %s)', thisver, latestver)
        return

Paul McCarthy's avatar
Paul McCarthy committed
720
721
    log.debug('New version of installer is available '
              '(%s) - self-updating', latestver)
722

Paul McCarthy's avatar
Paul McCarthy committed
723
724
725
    tmpf = tempfile.NamedTemporaryFile(delete=False)
    tmpf.close()
    tmpf = tmpf.name
726

Paul McCarthy's avatar
Paul McCarthy committed
727
    download_file(ctx.manifest['installer']['url'], tmpf)
728
729
730

    if not ctx.args.disable_checksum:
        sha256(tmpf, ctx.manifest['installer']['sha256'])
731

Paul McCarthy's avatar
Paul McCarthy committed
732
733
734
    cmd = [sys.executable, tmpf] + sys.argv[1:]
    log.debug('Running new installer: %s', cmd)
    os.execv(sys.executable, cmd)
735
736
737
738
739
740
741
742
743


def parse_args(argv=None):
    """Parse command-line arguments, returns an argparse.Namespace object. """

    helps = {
        'dest' :                'Install FSL into this folder (default: '
                                '{})'.format(DEFAULT_INSTALLATION_DIRECTORY),
        'version'             : 'Print installer version number and exit',
Paul McCarthy's avatar
Paul McCarthy committed
744
        'disable_self_update' : 'Do not automatically update the installer '
745
746
747
748
749
                                'script',
        'listversions'        : 'List available versions of FSL',
        'fslversion'          : 'Download this specific version of FSL',
        'cuda'                : 'Install FSL for this CUDA version (default: '
                                'automatically detected)',
Paul McCarthy's avatar
Paul McCarthy committed
750
751
752
753
754
755

        # Path to local installer manifest file
        'manifest'            : argparse.SUPPRESS,

        # Print debugging messages
        'debug'               : argparse.SUPPRESS,
756
757
758

        # Disable SHA256 checksum validation of downloaded files
        'disable_checksum'    : argparse.SUPPRESS,
759
760
761
    }

    parser = argparse.ArgumentParser()
762
763
764
765
    parser.add_argument('-v', '--version', action='version',
                        version=__version__, help=helps['version'])
    parser.add_argument('-D', '--debug', action='store_true',
                        help=helps['debug'])
Paul McCarthy's avatar
Paul McCarthy committed
766
767
    parser.add_argument('-m', '--manifest', default=FSL_INSTALLER_MANIFEST,
                        help=helps['manifest'])
768
769
770
771
    parser.add_argument('-u', '--disable_self_update', action='store_true',
                        help=helps['disable_self_update'])
    parser.add_argument('-d', '--dest', metavar='DESTDIR',
                        help=helps['dest'])
772
773
    parser.add_argument('-s', '--disable_checksum', action='store_true',
                        help=helps['disable_checksum'])
774
775
776
777
    parser.add_argument('-l', '--listversions', action='store_true',
                        help=helps['listversions'])
    parser.add_argument('-V', '--fslversion', default='latest',
                        help=helps['version'])
778
    parser.add_argument('-c', '--cuda', help=helps['cuda'])
779
780

    args = parser.parse_args(argv)
781

782
    logging.basicConfig()
783
784
    if args.debug: logging.getLogger().setLevel(logging.DEBUG)
    else:          logging.getLogger().setLevel(logging.WARNING)
785
786

    return args
787
788
789


def main(argv=None):
790
791

    args = parse_args(argv)
Paul McCarthy's avatar
Paul McCarthy committed
792
793
794
795
    ctx  = Context(args)

    if not args.disable_self_update:
        self_update(ctx)
796

797
798
    printmsg('FSL installer version:', EMPHASIS, UNDERLINE, end='')
    printmsg(' ' + __version__ + '\n')
799
800

    if args.listversions:
Paul McCarthy's avatar
Paul McCarthy committed
801
        list_available_versions(ctx)
802
803
        sys.exit(0)

804
805
    ctx.finalise_settings()

Paul McCarthy's avatar
Paul McCarthy committed
806
    printmsg('Installing FSL into {}'.format(ctx.destdir), EMPHASIS)
807
808

    with tempdir():
809
        install_miniconda(ctx)
Paul McCarthy's avatar
Paul McCarthy committed
810
        install_fsl(ctx)
811
812
813
814


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