<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def run_server(working_dir, foreground=False, expected_snapshots=GENESIS_SNAPSHOT, port=None, api_port=None, use_api=None, use_indexer=None, indexer_url=None, recover=False):
 """ Run blockstackd. Optionally daemonize. Return 0 on success Return negative on error """

    global rpc_server
    global api_server

    indexer_log_path = get_logfile_path(working_dir)
    
    logfile = None
    if not foreground:
        if os.path.exists(indexer_log_path):
            logfile = open(indexer_log_path, 'a')
        else:
            logfile = open(indexer_log_path, 'a+')

        child_pid = daemonize(logfile)
        if child_pid < 0:
            log.error("Failed to daemonize: {}".format(child_pid))
            return -1

        if child_pid > 0:
            # we're the parent
            log.debug("Running in the background as PID {}".format(child_pid))
            sys.exit(0)
    
    server_state = server_setup(working_dir, port=port, api_port=api_port, indexer_enabled=use_indexer, indexer_url=indexer_url, api_enabled=use_api, recover=recover)
    atexit.register(server_shutdown, server_state)

    rpc_server = server_state['rpc']
    
    blockstack_opts = get_blockstack_opts()
    blockstack_api_opts = get_blockstack_api_opts()

    if blockstack_opts['enabled']:
        log.debug("Begin Indexing")
        while is_running():
            try:
               running = index_blockchain(server_state, expected_snapshots=expected_snapshots)
            except Exception, e:
               log.exception(e)
               log.error("FATAL: caught exception while indexing")
               os.abort()

            # wait for the next block
            deadline = time.time() + REINDEX_FREQUENCY
            while time.time() < deadline and is_running():
                try:
                    time.sleep(1.0)
                except:
                    # interrupt
                    break

        log.debug("End Indexing")

    elif blockstack_api_opts['enabled']:
        log.debug("Begin serving REST requests")
        while is_running():
            try:
                time.sleep(1.0)
            except:
                # interrupt
                break

        log.debug("End serving REST requests")

    server_shutdown(server_state)
    
    # close logfile
    if logfile is not None:
        logfile.flush()
        logfile.close()
    
    return 0