Get our default blockstack opts from a config file
   or from sane defaults.

def default_blockstack_opts( working_dir, config_file=None ):
   """
   Get our default blockstack opts from a config file
   or from sane defaults.
   """

   global RPC_SERVER_IP, RPC_SERVER_PORT

   from .util import url_to_host_port
   from .scripts import is_name_valid

   if config_file is None:
      config_file = virtualchain.get_config_filename(get_default_virtualchain_impl(), working_dir)

   announce_path = get_announce_filename(working_dir)

   parser = SafeConfigParser()
   parser.read( config_file )

   blockstack_opts = {}
   announcers = "judecn.id,muneeb.id,shea256.id"
   announcements = None
   backup_frequency = 144   # once a day; 10 minute block time
   backup_max_age = 1008    # one week
   rpc_port = RPC_SERVER_PORT 
   zonefile_dir = os.path.join( os.path.dirname(config_file), "zonefiles")
   server_version = VERSION
   atlas_enabled = True
   atlas_seed_peers = "node.blockstack.org:%s" % RPC_SERVER_PORT if not BLOCKSTACK_TESTNET_ACTIVE else ""
   atlasdb_path = os.path.join( os.path.dirname(config_file), "atlas.db" )
   atlas_blacklist = ""
   atlas_hostname = RPC_SERVER_IP
   real_atlas_hostname = None       # if we need to look it up on-the-fly
   atlas_port = RPC_SERVER_PORT
   subdomaindb_path = os.path.join( os.path.dirname(config_file), "subdomains.db" )
   run_indexer = True

   if parser.has_section('blockstack'):
      if parser.has_option('blockstack', 'enabled'):
         run_indexer = parser.get('blockstack', 'enabled').lower() in ['1', 'true', 'on']

      if parser.has_option('blockstack', 'backup_frequency'):
         backup_frequency = int( parser.get('blockstack', 'backup_frequency'))

      if parser.has_option('blockstack', 'backup_max_age'):
         backup_max_age = int( parser.get('blockstack', 'backup_max_age') )

      if parser.has_option('blockstack', 'rpc_port'):
         rpc_port = int(parser.get('blockstack', 'rpc_port'))

      if parser.has_option("blockstack", "zonefiles"):
          zonefile_dir = parser.get("blockstack", "zonefiles")
    
      if parser.has_option('blockstack', 'announcers'):
         # must be a CSV of blockchain IDs
         announcer_list_str = parser.get('blockstack', 'announcers')
         announcer_list = filter( lambda x: len(x) > 0, announcer_list_str.split(",") )

         # validate each one
         valid = True
         for bid in announcer_list:
             if not is_name_valid( bid ):
                 log.error("Invalid blockchain ID '%s'" % bid)
                 valid = False

         if valid:
             announcers = ",".join(announcer_list)

      if parser.has_option('blockstack', 'server_version'):
         server_version = parser.get('blockstack', 'server_version')

      if parser.has_option('blockstack', 'atlas'):
         atlas_enabled = parser.get('blockstack', 'atlas')
         if atlas_enabled.lower() in ['true', '1', 'enabled', 'enabled', 'on']:
            atlas_enabled = True
         else:
            atlas_enabled = False

      if parser.has_option('blockstack', 'atlas_seeds'):
         atlas_seed_peers = parser.get('blockstack', 'atlas_seeds')

         # must be a CSV of host:port
         check_hostport_list(atlas_seed_peers)

      if parser.has_option('blockstack', 'atlasdb_path'):
         atlasdb_path = parser.get('blockstack', 'atlasdb_path')

      if parser.has_option('blockstack', 'atlas_blacklist'):
         atlas_blacklist = parser.get('blockstack', 'atlas_blacklist')

         # must be a CSV of host:port
         hostports = filter( lambda x: len(x) > 0, atlas_blacklist.split(",") )
         for hp in hostports:
             host, port = url_to_host_port( hp )
             assert host is not None and port is not None

      if parser.has_option('blockstack', 'atlas_hostname'):
         atlas_hostname = parser.get('blockstack', 'atlas_hostname')
    
      if parser.has_option('blockstack', 'atlas_port'):
         atlas_port = int(parser.get('blockstack', 'atlas_port'))

      if parser.has_option('blockstack', 'subdomaindb_path'):
         subdomaindb_path = parser.get('blockstack', 'subdomaindb_path')

   if os.environ.get(ATLAS_SEEDS_ENV_VAR, False):
       atlas_seed_peers = os.environ[ATLAS_SEEDS_ENV_VAR]
       check_hostport_list(atlas_seed_peers)

   if os.environ.get(ATLAS_HOSTNAME_ENV_VAR, False):
       atlas_hostname = os.environ[ATLAS_HOSTNAME_ENV_VAR]

   if os.path.exists( announce_path ):
       # load announcement list
       with open( announce_path, "r" ) as f:
           announce_text = f.readlines()

       all_announcements = [ a.strip() for a in announce_text ]
       unseen_announcements = []

       # find announcements we haven't seen yet
       for a in all_announcements:
           if a not in ANNOUNCEMENTS:
               unseen_announcements.append( a )

       announcements = ",".join( unseen_announcements )

   if zonefile_dir is not None and not os.path.exists( zonefile_dir ):
       try:
           os.makedirs( zonefile_dir, 0700 )
       except:
           pass

   if RPC_SERVER_IP is None:
       if atlas_hostname is None or atlas_hostname.lower() == '<stun>':
           real_atlas_hostname = get_atlas_hostname_stun()
           RPC_SERVER_IP = real_atlas_hostname

       elif atlas_hostname.lower() == '<host>':
           real_atlas_hostname = get_atlas_hostname_addrinfo(rpc_port)
           RPC_SERVER_IP = real_atlas_hostname
       
       else:
           log.debug('Using configuration-given Atlas hostname')
           real_atlas_hostname = atlas_hostname
           RPC_SERVER_IP = atlas_hostname

       if atlas_hostname is None and real_atlas_hostname is None:
           log.warning('No Atlas hostname could be determined, assuming 127.0.0.1')
           real_atlas_hostname = '127.0.0.1'
           RPC_SERVER_IP = real_atlas_hostname
   
       log.info('Atlas IP address is ({}, {})'.format(RPC_SERVER_IP, rpc_port))

   else:
       # already set
       real_atlas_hostname = RPC_SERVER_IP

   atlas_hostname = real_atlas_hostname
   RPC_SERVER_PORT = rpc_port

   blockstack_opts = {
       'rpc_port': rpc_port,
       'announcers': announcers,
       'announcements': announcements,
       'backup_frequency': backup_frequency,
       'backup_max_age': backup_max_age,
       'server_version': server_version,
       'atlas': atlas_enabled,
       'atlas_seeds': atlas_seed_peers,
       'atlasdb_path': atlasdb_path,
       'atlas_blacklist': atlas_blacklist,
       'atlas_hostname': atlas_hostname,
       'atlas_port': atlas_port,
       'zonefiles': zonefile_dir,
       'subdomaindb_path': subdomaindb_path,
       'enabled': run_indexer
   }

   # strip Nones
   for (k, v) in blockstack_opts.items():
      if v is None:
         del blockstack_opts[k]

   return blockstack_opts