+# Handle global options.
+try:
+ optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
+ global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
+except getopt.GetoptError, ex:
+ usage('error: %s' % ex.msg)
+
+help_requested = None
+do_profile = False
+
+for opt in global_args:
+ if opt[0] in ['-?', '--help']:
+ help_requested = True
+ elif opt[0] in ['-V', '--version']:
+ subcmd = ['version']
+ elif opt[0] in ['-D', '--debug']:
+ helpers.buglvl += 1
+ os.environ['BUP_DEBUG'] = str(helpers.buglvl)
+ elif opt[0] in ['--profile']:
+ do_profile = True
+ elif opt[0] in ['-d', '--bup-dir']:
+ os.environ['BUP_DIR'] = opt[1]
+ else:
+ usage('error: unexpected option "%s"' % opt[0])
+
+# Make BUP_DIR absolute, so we aren't affected by chdir (i.e. save -C, etc.).
+if 'BUP_DIR' in os.environ:
+ os.environ['BUP_DIR'] = os.path.abspath(os.environ['BUP_DIR'])
+
+if len(subcmd) == 0:
+ if help_requested:
+ subcmd = ['help']
+ else:
+ usage()
+
+if help_requested and subcmd[0] != 'help':
+ subcmd = ['help'] + subcmd
+
+if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
+ subcmd = ['help', subcmd[0]] + subcmd[2:]
+
+subcmd_name = subcmd[0]
+if not subcmd_name:
+ usage()