// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var ArgumentParser, Base, Config, E, Main, PackageJson, SubParserWrapper, add_option_dict, check_node_async, colors, db, env, gpgw, iced, init_env, ispawn, keyring, log, make_esc, platform_info, proxyca, req, run, session, tor, version_info, __iced_k, __iced_k_noop, _ref, _ref1,
    __slice = [].slice;

  iced = require('iced-runtime').iced;
  __iced_k = __iced_k_noop = function() {};

  Base = require('./base').Base;

  log = require('../log');

  ArgumentParser = require('argparse').ArgumentParser;

  add_option_dict = require('./argparse').add_option_dict;

  PackageJson = require('../package').PackageJson;

  E = require('../err').E;

  make_esc = require('iced-error').make_esc;

  _ref = require('../env'), env = _ref.env, init_env = _ref.init_env;

  Config = require('../config').Config;

  req = require('../req');

  session = require('../session');

  db = require('../db');

  gpgw = require('gpg-wrapper');

  keyring = require('../keyring');

  _ref1 = require('../version'), platform_info = _ref1.platform_info, version_info = _ref1.version_info;

  proxyca = require('../proxyca');

  tor = require('../tor');

  colors = require('../colors');

  check_node_async = require('badnode').check_node_async;

  ispawn = require('iced-spawn');

  exports.SubParserWrapper = SubParserWrapper = (function() {
    function SubParserWrapper(subparsers) {
      this.subparsers = subparsers;
      this._lookup = {};
    }

    SubParserWrapper.prototype.addParser = function() {
      var args, sub, _ref2;
      args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      return this._last_sub = sub = (_ref2 = this.subparsers).addParser.apply(_ref2, args);
    };

    SubParserWrapper.prototype.add_lookup = function(names) {
      var n, _i, _len;
      for (_i = 0, _len = names.length; _i < _len; _i++) {
        n = names[_i];
        this._lookup[n] = this._last_sub;
      }
      return this._last_sub = null;
    };

    SubParserWrapper.prototype.lookup = function(n) {
      return this._lookup[n];
    };

    return SubParserWrapper;

  })();

  Main = (function() {
    function Main() {
      this.commands = {};
      this.pkjson = new PackageJson();
    }

    Main.prototype.arg_parse_init = function() {
      var err;
      err = null;
      this.ap = new ArgumentParser({
        addHelp: true,
        version: this.pkjson.version(),
        description: 'keybase.io command line client',
        prog: this.pkjson.bin()
      });
      if (!this.add_subcommands()) {
        err = new E.InitError("cannot initialize subcommands");
      }
      return err;
    };

    Main.prototype.lookup_parser = function(n) {
      return this._spw.lookup(n);
    };

    Main.prototype.add_subcommands = function() {
      var list, m, mod, n, names, obj, subparsers, _i, _j, _len, _len1;
      add_option_dict(this.ap, Base.OPTS);
      list = ["btc", "cert", "dir", "config", "decrypt", "encrypt", "help", "id", "join", "keygen", "list_signatures", "list_tracking", "login", "logout", "pull", "push", "prove", "reset", "revoke", "revoke_sig", "search", "sign", "status", "switch", "track", "untrack", "update", "verify", "version"];
      subparsers = this.ap.addSubparsers({
        title: 'subcommands',
        dest: 'subcommand_name'
      });
      this._spw = new SubParserWrapper(subparsers);
      this.commands = {};
      for (_i = 0, _len = list.length; _i < _len; _i++) {
        m = list[_i];
        mod = require("./" + m);
        obj = new mod.Command(this);
        names = obj.add_subcommand_parser(this._spw);
        this._spw.add_lookup(names);
        for (_j = 0, _len1 = names.length; _j < _len1; _j++) {
          n = names[_j];
          this.commands[n] = obj;
        }
      }
      return true;
    };

    Main.prototype.parse_args = function(cb) {
      var err;
      this.cmd = null;
      err = this.arg_parse_init();
      if (err == null) {
        this.argv = this.ap.parseArgs(process.argv.slice(2));
        this.cmd = this.commands[this.argv.subcommand_name];
        if (this.cmd == null) {
          log.error("Subcommand not found: " + argv.subcommand_name);
          err = new E.ArgsError("" + argv.subcommand_name + " not found");
        } else {
          err = this.cmd.set_argv(this.argv);
        }
      }
      return cb(err);
    };

    Main.prototype.load_config = function(cb) {
      var esc, res, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "load_config");
      (function(_this) {
        return (function(__iced_k) {
          if (_this.cmd.use_config()) {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                funcname: "Main.load_config"
              });
              env().maybe_fallback_to_layout_v1(esc(__iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return res = arguments[0];
                  };
                })(),
                lineno: 148
              })));
              __iced_deferrals._fulfill();
            })(function() {
              if (res) {
                log.debug("| Fallback to layout_v1");
              }
              _this.config = new Config(env().get_config_filename(), _this.cmd.config_opts());
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                  funcname: "Main.load_config"
                });
                _this.config.open(esc(__iced_deferrals.defer({
                  lineno: 152
                })));
                __iced_deferrals._fulfill();
              })(__iced_k);
            });
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb(null);
        };
      })(this));
    };

    Main.prototype.load_session = function(cb) {
      var err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      err = null;
      (function(_this) {
        return (function(__iced_k) {
          if (_this.cmd.use_session()) {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                funcname: "Main.load_session"
              });
              session.load(__iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return err = arguments[0];
                  };
                })(),
                lineno: 160
              }));
              __iced_deferrals._fulfill();
            })(__iced_k);
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    Main.prototype.main = function() {
      var err, msg, rc, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
            funcname: "Main.main"
          });
          _this.run(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return rc = arguments[1];
              };
            })(),
            lineno: 166
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof rc === "undefined" || rc === null) {
            rc = 0;
          }
          if (typeof err !== "undefined" && err !== null) {
            msg = err instanceof gpgw.E.GpgError ? "`gpg` exited with code " + err.rc : err.message;
            log.error(msg);
            if (err.stderr != null) {
              log.warn(err.stderr.toString('utf8'));
            }
          }
          return process.exit(typeof err !== "undefined" && err !== null ? -2 : rc);
        };
      })(this));
    };

    Main.prototype.run = function(cb) {
      var esc, rc, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "run");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
            funcname: "Main.run"
          });
          _this.setup(esc(__iced_deferrals.defer({
            lineno: 179
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
              funcname: "Main.run"
            });
            _this.cmd.run(esc(__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return rc = arguments[0];
                };
              })(),
              lineno: 180
            })));
            __iced_deferrals._fulfill();
          })(function() {
            return cb(null, rc);
          });
        };
      })(this));
    };

    Main.prototype.config_logger = function() {
      var p;
      p = log["package"]();
      if (this.argv.debug) {
        p.env().set_level(p.DEBUG);
      } else if (this.argv.quiet) {
        p.env().set_level(p.ERROR);
      }
      if (env().get_no_color()) {
        p.env().set_use_color(false);
      }
      return gpgw.set_log(log.warn);
    };

    Main.prototype.init_keyring = function() {
      return keyring.init();
    };

    Main.prototype.load_db = function(cb) {
      var err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      err = null;
      (function(_this) {
        return (function(__iced_k) {
          if (_this.cmd.use_db()) {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                funcname: "Main.load_db"
              });
              db.open(__iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return err = arguments[0];
                  };
                })(),
                lineno: 205
              }));
              __iced_deferrals._fulfill();
            })(__iced_k);
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    Main.prototype.cleanup_previous_crash = function(cb) {
      var err;
      err = null;
      return cb(err);
    };

    Main.prototype.startup_message = function(cb) {
      var err, info, p, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      p = log["package"]();
      log.debug("+ startup message");
      (function(_this) {
        return (function(__iced_k) {
          if (p.env().get_level() === p.DEBUG) {
            log.debug("| CLI version: " + ((new PackageJson).version()));
            log.debug("| Platform info: " + (JSON.stringify(platform_info())));
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                funcname: "Main.startup_message"
              });
              version_info(_this._gpg_version, __iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    err = arguments[0];
                    return info = arguments[1];
                  };
                })(),
                lineno: 222
              }));
              __iced_deferrals._fulfill();
            })(function() {
              return __iced_k(typeof err !== "undefined" && err !== null ? log.error("Error fetching version info: " + err.message) : log.debug("| Version info: " + (JSON.stringify(info))));
            });
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          log.debug("- startup message");
          return cb(null);
        };
      })(this));
    };

    Main.prototype.init_gpg = function(cb) {
      var c, cmd, e2, err, tty, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      err = null;
      (function(_this) {
        return (function(__iced_k) {
          if (_this.cmd.use_gpg()) {
            c = env().get_gpg_cmd();
            log.debug("+ testing GPG command-line client " + (c != null ? c : '<default: gpg2 or gpg>'));
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                funcname: "Main.init_gpg"
              });
              gpgw.find_and_set_cmd(c, __iced_deferrals.defer({
                assign_fn: (function(__slot_1) {
                  return function() {
                    err = arguments[0];
                    __slot_1._gpg_version = arguments[1];
                    return cmd = arguments[2];
                  };
                })(_this),
                lineno: 237
              }));
              __iced_deferrals._fulfill();
            })(function() {
              if (err != null) {
                err = new E.GpgError(err.message);
              } else if (c != null) {
                log.debug("| Using the supplied GPG cmd: '" + c + "'");
              } else if ((c == null) && cmd) {
                log.debug("| using GPG command: " + cmd);
                env().set_gpg_cmd(cmd);
              }
              log.debug("- tested GPG command-line client -> " + err);
              (function(__iced_k) {
                if (err == null) {
                  (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral,
                      filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                      funcname: "Main.init_gpg"
                    });
                    gpgw.pinentry_init(__iced_deferrals.defer({
                      assign_fn: (function() {
                        return function() {
                          e2 = arguments[0];
                          return tty = arguments[1];
                        };
                      })(),
                      lineno: 247
                    }));
                    __iced_deferrals._fulfill();
                  })(function() {
                    return __iced_k(typeof e2 !== "undefined" && e2 !== null ? log.debug("Warning on pinentry init: " + (e2.toString())) : typeof tty !== "undefined" && tty !== null ? log.debug("Setting GPG_TTY=" + tty) : log.debug("No tty to set"));
                  });
                } else {
                  return __iced_k();
                }
              })(__iced_k);
            });
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    Main.prototype.init_tor = function(cb) {
      var err, px;
      err = null;
      if (tor.enabled()) {
        px = tor.proxy();
        if (this.cmd.needs_cookies() && tor.strict()) {
          err = new E.TorStrictError("Cannot run this command in strict Tor mode");
        } else {
          log.warn("In Tor mode: strict=" + (colors.bold(JSON.stringify(!!tor.strict()))) + "; proxy=" + px.hostname + ":" + px.port);
          log.warn("Tor support is in " + (colors.bold('alpha')) + "; please be careful and report any issues");
        }
      }
      return cb(err);
    };

    Main.prototype.init_proxy_cas = function(cb) {
      var err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
            funcname: "Main.init_proxy_cas"
          });
          proxyca.init(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 272
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    Main.prototype.setup = function(cb) {
      var esc, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "setup");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
            funcname: "Main.setup"
          });
          check_node_async(null, esc(__iced_deferrals.defer({
            lineno: 281
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          init_env();
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
              funcname: "Main.setup"
            });
            _this.parse_args(esc(__iced_deferrals.defer({
              lineno: 284
            })));
            __iced_deferrals._fulfill();
          })(function() {
            env().set_argv(_this.argv);
            _this.config_logger();
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                funcname: "Main.setup"
              });
              _this.load_config(esc(__iced_deferrals.defer({
                lineno: 287
              })));
              __iced_deferrals._fulfill();
            })(function() {
              env().set_config(_this.config);
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                  funcname: "Main.setup"
                });
                _this.init_tor(esc(__iced_deferrals.defer({
                  lineno: 289
                })));
                __iced_deferrals._fulfill();
              })(function() {
                (function(__iced_k) {
                  __iced_deferrals = new iced.Deferrals(__iced_k, {
                    parent: ___iced_passed_deferral,
                    filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                    funcname: "Main.setup"
                  });
                  _this.init_gpg(esc(__iced_deferrals.defer({
                    lineno: 290
                  })));
                  __iced_deferrals._fulfill();
                })(function() {
                  _this.init_keyring();
                  (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral,
                      filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                      funcname: "Main.setup"
                    });
                    _this.init_proxy_cas(esc(__iced_deferrals.defer({
                      lineno: 292
                    })));
                    __iced_deferrals._fulfill();
                  })(function() {
                    (function(__iced_k) {
                      __iced_deferrals = new iced.Deferrals(__iced_k, {
                        parent: ___iced_passed_deferral,
                        filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                        funcname: "Main.setup"
                      });
                      _this.startup_message(esc(__iced_deferrals.defer({
                        lineno: 294
                      })));
                      __iced_deferrals._fulfill();
                    })(function() {
                      (function(__iced_k) {
                        __iced_deferrals = new iced.Deferrals(__iced_k, {
                          parent: ___iced_passed_deferral,
                          filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                          funcname: "Main.setup"
                        });
                        _this.load_db(esc(__iced_deferrals.defer({
                          lineno: 295
                        })));
                        __iced_deferrals._fulfill();
                      })(function() {
                        (function(__iced_k) {
                          __iced_deferrals = new iced.Deferrals(__iced_k, {
                            parent: ___iced_passed_deferral,
                            filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                            funcname: "Main.setup"
                          });
                          _this.cleanup_previous_crash(esc(__iced_deferrals.defer({
                            lineno: 296
                          })));
                          __iced_deferrals._fulfill();
                        })(function() {
                          (function(__iced_k) {
                            __iced_deferrals = new iced.Deferrals(__iced_k, {
                              parent: ___iced_passed_deferral,
                              filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                              funcname: "Main.setup"
                            });
                            _this.load_session(esc(__iced_deferrals.defer({
                              lineno: 297
                            })));
                            __iced_deferrals._fulfill();
                          })(function() {
                            (function(__iced_k) {
                              __iced_deferrals = new iced.Deferrals(__iced_k, {
                                parent: ___iced_passed_deferral,
                                filename: "/Users/max/src/keybase/node-client/src/command/all.iced",
                                funcname: "Main.setup"
                              });
                              _this.cmd.assertions(esc(__iced_deferrals.defer({
                                lineno: 298
                              })));
                              __iced_deferrals._fulfill();
                            })(function() {
                              env().set_session(_this.session);
                              return cb(null);
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        };
      })(this));
    };

    return Main;

  })();

  exports.run = run = function() {
    return (new Main).main();
  };

}).call(this);
