// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var ASP, BufferOutStream, E, KeyManager, PackageJson, StatusParser, constants, env, iced, init_env, log, make_esc, make_scrypt_progress_hook, master_ring, __iced_k, __iced_k_noop, _ref;

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

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

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

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

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

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

  BufferOutStream = require('iced-spawn').BufferOutStream;

  ASP = require('pgp-utils').util.ASP;

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

  make_scrypt_progress_hook = require('./util').make_scrypt_progress_hook;

  StatusParser = require('./gpg').StatusParser;

  log = require('./log');

  exports.KeyManager = KeyManager = (function() {
    function KeyManager(_arg) {
      this.username = _arg.username, this.config = _arg.config, this.passphrase = _arg.passphrase, this.ring = _arg.ring, this.tsenc = _arg.tsenc, this.key = _arg.key, this.fingerprint = _arg.fingerprint;
      this.ring || (this.ring = master_ring());
      this.key = null;
      this.lib = {
        KeyManager: require('kbpgp').KeyManager,
        Encryptor: require('triplesec').Encryptor
      };
    }

    KeyManager.generate = function(_arg, cb) {
      var config, err, km, passphrase, ring, username, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      username = _arg.username, config = _arg.config, passphrase = _arg.passphrase, ring = _arg.ring;
      username || (username = env().get_username());
      config || (config = constants.keygen);
      ring || (ring = master_ring());
      km = new KeyManager({
        username: username,
        config: config,
        passphrase: passphrase,
        ring: ring
      });
      (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/keymanager.iced",
            funcname: "KeyManager.generate"
          });
          km._gen(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 33
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof err !== "undefined" && err !== null) {
            km = null;
          }
          return cb(err, km);
        };
      })(this));
    };

    KeyManager.prototype._gen = function(cb) {
      var args, email, err, esc, fingerprint, h, kc, out, script, status_parser, stderr, stdin, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "KeyGen::Gen");
      h = constants.canonical_host;
      email = this.username + ("@" + h);
      script = ["%echo generating", "Key-Type: RSA", "Key-Length: " + this.config.master.bits, "Key-Usage: sign,auth", "Subkey-Type: RSA", "Subkey-Length: " + this.config.subkey.bits, "Subkey-Usage: encrypt", "Name-Real: " + h + "/" + this.username, "Name-Email: " + email, "Expire-date: " + this.config.expire, "Passphrase: " + this.passphrase, "%commit"];
      stdin = script.join("\n");
      args = ["--batch", "--gen-key", "--keyid-format", "long", "--status-fd", '2'];
      stderr = new BufferOutStream();
      (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/keymanager.iced",
            funcname: "KeyManager._gen"
          });
          _this.ring.gpg({
            args: args,
            stdin: stdin,
            stderr: stderr,
            secret: true
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return out = arguments[1];
              };
            })(),
            lineno: 60
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            if (typeof err !== "undefined" && err !== null) {
              return __iced_k(log.warn(stderr.data().toString()));
            } else {
              status_parser = (new StatusParser).parse({
                buf: stderr.data()
              });
              (function(__iced_k) {
                if (((kc = status_parser.lookup('KEY_CREATED')) != null) && kc.length >= 2) {
                  fingerprint = kc[1];
                  _this.key = _this.ring.make_key({
                    fingerprint: fingerprint,
                    secret: true
                  });
                  (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral,
                      filename: "/Users/max/src/keybase/node-client/src/keymanager.iced",
                      funcname: "KeyManager._gen"
                    });
                    _this.key.load(esc(__iced_deferrals.defer({
                      lineno: 68
                    })));
                    __iced_deferrals._fulfill();
                  })(__iced_k);
                } else {
                  return __iced_k(err = new E.GenerateError("Failed to parse output of key generation"));
                }
              })(__iced_k);
            }
          })(function() {
            return cb(err);
          });
        };
      })(this));
    };

    KeyManager.prototype._load = function(cb) {
      var err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      this.key = this.ring.make_key({
        fingerprint: this.fingerprint,
        secret: true
      });
      (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/keymanager.iced",
            funcname: "KeyManager._load"
          });
          _this.key.load(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 77
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    KeyManager.load = function(opts, cb) {
      var err, km, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      km = new KeyManager(opts);
      (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/keymanager.iced",
            funcname: "KeyManager.load"
          });
          km._load(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 84
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof err !== "undefined" && err !== null) {
            km = null;
          }
          return cb(err, km);
        };
      })(this));
    };

    KeyManager.prototype.load_public = function(cb) {
      var err, pubkey, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      pubkey = this.ring.make_key({
        fingerprint: this.key.fingerprint(),
        secret: false
      });
      (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/keymanager.iced",
            funcname: "KeyManager.load_public"
          });
          pubkey.load(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 92
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof err === "undefined" || err === null) {
            _this.pubkey = pubkey;
          }
          return cb(err, pubkey);
        };
      })(this));
    };

    KeyManager.prototype.get_tsenc = function() {
      if (!this.tsenc) {
        this.tsenc = new this.lib.Encryptor({
          key: new Buffer(this.passphrase, 'utf8')
        });
      }
      return this.tsenc;
    };

    KeyManager.prototype.import_from_pgp = function(cb) {
      var err, raw, warnings, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      raw = this.key.key_data().toString('utf8');
      (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/keymanager.iced",
            funcname: "KeyManager.import_from_pgp"
          });
          _this.lib.KeyManager.import_from_armored_pgp({
            raw: raw
          }, __iced_deferrals.defer({
            assign_fn: (function(__slot_1) {
              return function() {
                err = arguments[0];
                __slot_1.km = arguments[1];
                return warnings = arguments[2];
              };
            })(_this),
            lineno: 107
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          _this.warn("Export to P3SKB format", warnings);
          return cb(err);
        };
      })(this));
    };

    KeyManager.prototype.unlock_pgp = function(_arg, cb) {
      var err, esc, passphrase, prompter, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      passphrase = _arg.passphrase, prompter = _arg.prompter;
      esc = make_esc(cb, "KeyManager::unlock_pgp");
      passphrase || (passphrase = this.passphrase);
      (function(_this) {
        return (function(__iced_k) {
          if (_this.km.is_pgp_locked()) {
            (function(__iced_k) {
              if (passphrase == null) {
                (function(__iced_k) {
                  __iced_deferrals = new iced.Deferrals(__iced_k, {
                    parent: ___iced_passed_deferral,
                    filename: "/Users/max/src/keybase/node-client/src/keymanager.iced",
                    funcname: "KeyManager.unlock_pgp"
                  });
                  prompter(esc(__iced_deferrals.defer({
                    assign_fn: (function() {
                      return function() {
                        return passphrase = arguments[0];
                      };
                    })(),
                    lineno: 118
                  })));
                  __iced_deferrals._fulfill();
                })(function() {
                  return __iced_k(_this.passphrase = passphrase);
                });
              } else {
                return __iced_k();
              }
            })(function() {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/Users/max/src/keybase/node-client/src/keymanager.iced",
                  funcname: "KeyManager.unlock_pgp"
                });
                _this.km.unlock_pgp({
                  passphrase: passphrase
                }, __iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      return err = arguments[0];
                    };
                  })(),
                  lineno: 120
                }));
                __iced_deferrals._fulfill();
              })(__iced_k);
            });
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    KeyManager.prototype.sign_and_export = 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, "KeyManager::sign_and_export");
      (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/keymanager.iced",
            funcname: "KeyManager.sign_and_export"
          });
          _this.km.sign({}, esc(__iced_deferrals.defer({
            lineno: 127
          })));
          __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/keymanager.iced",
              funcname: "KeyManager.sign_and_export"
            });
            _this.km.export_private_to_server({
              tsenc: _this.get_tsenc()
            }, esc(__iced_deferrals.defer({
              assign_fn: (function(__slot_1) {
                return function() {
                  return __slot_1.p3skb = arguments[0];
                };
              })(_this),
              lineno: 128
            })));
            __iced_deferrals._fulfill();
          })(function() {
            return cb(null);
          });
        };
      })(this));
    };

    KeyManager.prototype.export_to_p3skb = function(_arg, cb) {
      var esc, prompter, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      prompter = _arg.prompter;
      esc = make_esc(cb, "KeyManager::encrypt_to_p3skb");
      (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/keymanager.iced",
            funcname: "KeyManager.export_to_p3skb"
          });
          _this.import_from_pgp(esc(__iced_deferrals.defer({
            lineno: 135
          })));
          __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/keymanager.iced",
              funcname: "KeyManager.export_to_p3skb"
            });
            _this.unlock_pgp({
              prompter: prompter
            }, esc(__iced_deferrals.defer({
              lineno: 136
            })));
            __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/keymanager.iced",
                funcname: "KeyManager.export_to_p3skb"
              });
              _this.sign_and_export(esc(__iced_deferrals.defer({
                lineno: 137
              })));
              __iced_deferrals._fulfill();
            })(function() {
              return cb(null, _this.p3skb);
            });
          });
        };
      })(this));
    };

    KeyManager.prototype.set_passphrase = function(p) {
      this.passphrase = p;
      return this.tsenc = null;
    };

    KeyManager.import_from_p3skb = function(_arg, cb) {
      var err, km, passphrase, prompter, raw, ring, tsenc, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      raw = _arg.raw, ring = _arg.ring, tsenc = _arg.tsenc, passphrase = _arg.passphrase, prompter = _arg.prompter;
      km = new KeyManager({
        ring: ring,
        tsenc: tsenc,
        passphrase: passphrase
      });
      (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/keymanager.iced",
            funcname: "KeyManager.import_from_p3skb"
          });
          km._import_from_p3skb({
            raw: raw,
            prompter: prompter
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 150
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof err !== "undefined" && err !== null) {
            km = null;
          }
          return cb(err, km);
        };
      })(this));
    };

    KeyManager.prototype.warn = function(what, warnings) {
      var w, _i, _len, _ref1, _results;
      if (warnings != null) {
        _ref1 = warnings.warnings();
        _results = [];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          w = _ref1[_i];
          _results.push(log.warn("" + what + ": " + w));
        }
        return _results;
      }
    };

    KeyManager.prototype.save_to_ring = function(_arg, cb) {
      var esc, key_data, passphrase, ring, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      passphrase = _arg.passphrase, ring = _arg.ring;
      esc = make_esc(cb, "KeyManager::save_to_ring");
      if (ring != null) {
        this.ring = ring;
      }
      if (passphrase != null) {
        this.set_passphrase(passphrase);
      }
      (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/keymanager.iced",
            funcname: "KeyManager.save_to_ring"
          });
          _this.km.sign({}, esc(__iced_deferrals.defer({
            lineno: 167
          })));
          __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/keymanager.iced",
              funcname: "KeyManager.save_to_ring"
            });
            _this.km.export_pgp_private_to_client({
              passphrase: _this.passphrase
            }, esc(__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return key_data = arguments[0];
                };
              })(),
              lineno: 168
            })));
            __iced_deferrals._fulfill();
          })(function() {
            _this.key = _this.ring.make_key({
              key_data: key_data,
              fingerprint: _this.km.get_pgp_fingerprint().toString('hex'),
              secret: true
            });
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/keymanager.iced",
                funcname: "KeyManager.save_to_ring"
              });
              _this.key.save(esc(__iced_deferrals.defer({
                lineno: 174
              })));
              __iced_deferrals._fulfill();
            })(function() {
              return cb(null);
            });
          });
        };
      })(this));
    };

    KeyManager.prototype._import_from_p3skb = function(_arg, cb) {
      var asp, err, esc, prompter, raw, warnings, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      raw = _arg.raw, prompter = _arg.prompter;
      esc = make_esc(cb, "KeyManager::_import_from_p3skb");
      err = null;
      (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/keymanager.iced",
            funcname: "KeyManager._import_from_p3skb"
          });
          _this.lib.KeyManager.import_from_p3skb({
            raw: raw
          }, esc(__iced_deferrals.defer({
            assign_fn: (function(__slot_1) {
              return function() {
                __slot_1.km = arguments[0];
                return warnings = arguments[1];
              };
            })(_this),
            lineno: 182
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          _this.warn("Import from P3SKB format", warnings);
          (function(__iced_k) {
            if (_this.km.is_p3skb_locked()) {
              (function(__iced_k) {
                if ((_this.passphrase == null) && (prompter != null)) {
                  (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral,
                      filename: "/Users/max/src/keybase/node-client/src/keymanager.iced",
                      funcname: "KeyManager._import_from_p3skb"
                    });
                    prompter(esc(__iced_deferrals.defer({
                      assign_fn: (function(__slot_1) {
                        return function() {
                          return __slot_1.passphrase = arguments[0];
                        };
                      })(_this),
                      lineno: 186
                    })));
                    __iced_deferrals._fulfill();
                  })(__iced_k);
                } else {
                  return __iced_k();
                }
              })(function() {
                (function(__iced_k) {
                  if (!_this.passphrase) {
                    return __iced_k(err = new E.MissingPwError("No passphrase given"));
                  } else {
                    asp = new ASP({
                      progress_hook: make_scrypt_progress_hook()
                    });
                    (function(__iced_k) {
                      __iced_deferrals = new iced.Deferrals(__iced_k, {
                        parent: ___iced_passed_deferral,
                        filename: "/Users/max/src/keybase/node-client/src/keymanager.iced",
                        funcname: "KeyManager._import_from_p3skb"
                      });
                      _this.km.unlock_p3skb({
                        asp: asp,
                        tsenc: _this.get_tsenc()
                      }, esc(__iced_deferrals.defer({
                        lineno: 191
                      })));
                      __iced_deferrals._fulfill();
                    })(__iced_k);
                  }
                })(__iced_k);
              });
            } else {
              return __iced_k();
            }
          })(function() {
            return cb(err);
          });
        };
      })(this));
    };

    return KeyManager;

  })();

}).call(this);
