// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var BufferInStream, BufferOutStream, DecryptAndVerifyEngine, E, HKPLoopback, TmpPrimaryKeyRing, TrackSubSubCommand, User, athrow, chain, colors, constants, dict_union, env, fingerprint_to_key_id_64, iced, log, make_esc, parse_signature, session, timeago, urlmod, __iced_k, __iced_k_noop, _ref, _ref1,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  log = require('./log');

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

  TrackSubSubCommand = require('./tracksubsub').TrackSubSubCommand;

  _ref = require('iced-spawn'), BufferOutStream = _ref.BufferOutStream, BufferInStream = _ref.BufferInStream;

  _ref1 = require('iced-error'), chain = _ref1.chain, make_esc = _ref1.make_esc;

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

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

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

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

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

  User = require('./user').User;

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

  timeago = require('timeago');

  urlmod = require('url');

  HKPLoopback = require('./hkp_loopback').HKPLoopback;

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

  colors = require('./colors');

  session = require('./session');

  exports.DecryptAndVerifyEngine = DecryptAndVerifyEngine = (function() {
    DecryptAndVerifyEngine.OPTS = dict_union(TrackSubSubCommand.OPTS, {
      t: {
        alias: "track",
        action: "storeTrue",
        help: "prompt for tracking if necessary"
      },
      I: {
        alias: 'no-id',
        action: 'storeTrue',
        help: "don't try to ID the user"
      }
    });

    function DecryptAndVerifyEngine(_arg) {
      this.argv = _arg.argv;
    }

    DecryptAndVerifyEngine.prototype.try_track = function() {
      return (this.argv.track || this.argv.track_remote || this.argv.track_local) && !this.is_self;
    };

    DecryptAndVerifyEngine.prototype.try_id = function() {
      return !this.is_self && !this.argv.no_id;
    };

    DecryptAndVerifyEngine.prototype.find_signature = function(cb) {
      var err, _ref2;
      log.debug("+ find_signature");
      _ref2 = parse_signature(this.decrypt_stderr.data()), err = _ref2[0], this.signing_key = _ref2[1], this.sig_date = _ref2[2];
      this.found_sig = err == null;
      if ((err instanceof E.NotFoundError) && !this.argv.signed && (this.argv.signed_by == null)) {
        log.debug("| No signature found; but we didn't require one");
        err = null;
      }
      log.debug("- find_signature");
      return cb(err);
    };

    DecryptAndVerifyEngine.prototype.handle_id = function(cb) {
      var err, warnings, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      log.debug("+ handle_id");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.handle_id"
          });
          _this.tssc.check_remote_proofs(false, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return warnings = arguments[1];
              };
            })(),
            lineno: 68
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          log.debug("- handle_id");
          return cb(err);
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.handle_track = function(cb) {
      var accept, esc, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "handle_track");
      log.debug("+ handle track");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.handle_track"
          });
          _this.tssc.all_prompts(esc(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return accept = arguments[0];
              };
            })(),
            lineno: 77
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            if (accept) {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/jacko/node-client/src/dve.iced",
                  funcname: "DecryptAndVerifyEngine.handle_track"
                });
                _this.tssc.save_their_keys(esc(__iced_deferrals.defer({
                  lineno: 78
                })));
                __iced_deferrals._fulfill();
              })(__iced_k);
            } else {
              return __iced_k();
            }
          })(function() {
            log.debug("- handle track");
            return cb(null);
          });
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.handle_signature = function(cb) {
      var a, arg, b, basics, d, date_signed, err, esc, local, remote, time_ago, tracks, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "handle_signature");
      log.debug("+ handle_signature");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.handle_signature"
          });
          _this.check_imports(esc(__iced_deferrals.defer({
            lineno: 87
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          arg = {
            type: constants.lookups.key_fingerprint_to_user,
            name: _this.signing_key.primary
          };
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/home/jacko/node-client/src/dve.iced",
              funcname: "DecryptAndVerifyEngine.handle_signature"
            });
            User.map_key_to_user(arg, esc(__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return basics = arguments[0];
                };
              })(),
              lineno: 91
            })));
            __iced_deferrals._fulfill();
          })(function() {
            _this.username = basics.username;
            (function(__iced_k) {
              if (((a = _this.argv.signed_by) != null) && (a !== (b = _this.username))) {
                err = new E.WrongSignerError("Wrong signer: wanted '" + a + "' but got '" + b + "'");
                (function(__iced_k) {
                  __iced_deferrals = new iced.Deferrals(__iced_k, {
                    parent: ___iced_passed_deferral,
                    filename: "/home/jacko/node-client/src/dve.iced",
                    funcname: "DecryptAndVerifyEngine.handle_signature"
                  });
                  athrow(err, esc(__iced_deferrals.defer({
                    lineno: 96
                  })));
                  __iced_deferrals._fulfill();
                })(__iced_k);
              } else {
                return __iced_k();
              }
            })(function() {
              (function(__iced_k) {
                if (env().is_me(_this.username)) {
                  _this.is_self = true;
                  return __iced_k(log.info("Valid signature from " + (colors.bold('you'))));
                } else {
                  _this.is_self = false;
                  _this.tssc = new TrackSubSubCommand({
                    args: {
                      them: _this.username
                    },
                    opts: _this.argv,
                    tmp_keyring: _this.tmp_keyring,
                    batch: _this.batch,
                    ran_keypull: _this._ran_keypull
                  });
                  (function(__iced_k) {
                    if (session.logged_in()) {
                      (function(__iced_k) {
                        __iced_deferrals = new iced.Deferrals(__iced_k, {
                          parent: ___iced_passed_deferral,
                          filename: "/home/jacko/node-client/src/dve.iced",
                          funcname: "DecryptAndVerifyEngine.handle_signature"
                        });
                        _this.tssc.on_decrypt(esc(__iced_deferrals.defer({
                          lineno: 112
                        })));
                        __iced_deferrals._fulfill();
                      })(function() {
                        var _ref2;
                        _ref2 = _this.tssc.trackw.is_tracking(), remote = _ref2.remote, local = _ref2.local;
                        return __iced_k(tracks = remote ? "tracking remotely & locally" : local ? "tracking locally only" : "not tracking");
                      });
                    } else {
                      (function(__iced_k) {
                        __iced_deferrals = new iced.Deferrals(__iced_k, {
                          parent: ___iced_passed_deferral,
                          filename: "/home/jacko/node-client/src/dve.iced",
                          funcname: "DecryptAndVerifyEngine.handle_signature"
                        });
                        _this.tssc.on_loggedout_verify(esc(__iced_deferrals.defer({
                          lineno: 119
                        })));
                        __iced_deferrals._fulfill();
                      })(function() {
                        return __iced_k(tracks = "not tracking");
                      });
                    }
                  })(function() {
                    return __iced_k(log.info("Valid signature from keybase user " + (colors.bold(basics.username)) + " (" + tracks + ")"));
                  });
                }
              })(function() {
                d = _this.sig_date;
                time_ago = timeago(d);
                date_signed = d.toLocaleString();
                log.info("Signed " + time_ago + " (" + date_signed + ")");
                log.debug("- handle_signature");
                return cb(null);
              });
            });
          });
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.check_imports = function(cb) {
      var b, err, esc, ids, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "Command::check_imports");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.check_imports"
          });
          _this.tmp_keyring.list_keys(esc(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return ids = arguments[0];
              };
            })(),
            lineno: 136
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          err = null;
          if (ids.length === 0) {
            log.debug("| No new keys imported");
          } else if (ids.length > 1 && !env().get_no_gpg_options()) {
            err = new E.CorruptionError("Too many imported keys: " + ids.length);
          } else {
            b = fingerprint_to_key_id_64(_this.signing_key.primary);
            if (!(__indexOf.call(ids, b) >= 0)) {
              err = new E.VerifyError("Bad imported key; wanted " + b + " but couldn't find it");
            } else {
              log.debug("| Found new key in the keyring: " + b);
            }
          }
          return cb(err);
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.do_output = function(o, cb) {
      return cb();
    };

    DecryptAndVerifyEngine.prototype.do_keypull = function(cb) {
      this._ran_keypull = false;
      return cb(null);
    };

    DecryptAndVerifyEngine.prototype.make_gpg_args = function() {
      var args, gargs, o;
      args = ["--status-fd", '2', "--with-colons", "--keyid-format", "long", "--keyserver", this.hkpl.url(), "--keyserver-options", "auto-key-retrieve=1", "--with-fingerprint"];
      if (env().get_debug()) {
        args.push("--keyserver-options", "debug=1");
      }
      if ((o = this.argv.output) != null) {
        args.push("--output", o);
      }
      this.patch_gpg_args(args);
      gargs = {
        args: args
      };
      gargs.stderr = new BufferOutStream();
      if (this.argv.message) {
        gargs.stdin = new BufferInStream(this.argv.message);
      } else if (!this.get_files(args)) {
        gargs.stdin = process.stdin;
        this.batch = true;
      }
      return gargs;
    };

    DecryptAndVerifyEngine.prototype.make_hkp_loopback = function(cb) {
      var err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      this.hkpl = new HKPLoopback();
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.make_hkp_loopback"
          });
          _this.hkpl.listen(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 193
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof err !== "undefined" && err !== null) {
            _this.hkpl = null;
          }
          return cb(null);
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.do_command = function(cb) {
      var err, esc, gargs, out, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "Command::do_command");
      gargs = this.make_gpg_args();
      this.decrypt_stderr = gargs.stderr;
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.do_command"
          });
          _this.tmp_keyring.gpg(gargs, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return out = arguments[1];
              };
            })(),
            lineno: 203
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/home/jacko/node-client/src/dve.iced",
              funcname: "DecryptAndVerifyEngine.do_command"
            });
            _this.do_output(out, __iced_deferrals.defer({
              lineno: 204
            }));
            __iced_deferrals._fulfill();
          })(function() {
            if (typeof err !== "undefined" && err !== null) {
              log.warn(_this.decrypt_stderr.data().toString('utf8'));
            } else if (env().get_debug()) {
              log.debug(_this.decrypt_stderr.data().toString('utf8'));
            }
            return cb(err);
          });
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.setup_tmp_keyring = 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: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.setup_tmp_keyring"
          });
          TmpPrimaryKeyRing.make(__iced_deferrals.defer({
            assign_fn: (function(__slot_1) {
              return function() {
                err = arguments[0];
                return __slot_1.tmp_keyring = arguments[1];
              };
            })(_this),
            lineno: 215
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.run_cleanup = function(cb) {
      var e2, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      (function(_this) {
        return (function(__iced_k) {
          if (env().get_preserve_tmp_keyring()) {
            return __iced_k(log.info("Preserving " + (_this.tmp_keyring.to_string())));
          } else {
            (function(__iced_k) {
              if (_this.tmp_keyring != null) {
                (function(__iced_k) {
                  __iced_deferrals = new iced.Deferrals(__iced_k, {
                    parent: ___iced_passed_deferral,
                    filename: "/home/jacko/node-client/src/dve.iced",
                    funcname: "DecryptAndVerifyEngine.run_cleanup"
                  });
                  _this.tmp_keyring.nuke(__iced_deferrals.defer({
                    assign_fn: (function() {
                      return function() {
                        return e2 = arguments[0];
                      };
                    })(),
                    lineno: 224
                  }));
                  __iced_deferrals._fulfill();
                })(function() {
                  return __iced_k(typeof e2 !== "undefined" && e2 !== null ? log.warn("Error cleaning up temporary keyring: " + e2.message) : void 0);
                });
              } else {
                return __iced_k();
              }
            })(__iced_k);
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb();
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.global_cleanup = 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) {
          if (_this.hkpl) {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/home/jacko/node-client/src/dve.iced",
                funcname: "DecryptAndVerifyEngine.global_cleanup"
              });
              _this.hkpl.close(__iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return err = arguments[0];
                  };
                })(),
                lineno: 233
              }));
              __iced_deferrals._fulfill();
            })(function() {
              return __iced_k(typeof err !== "undefined" && err !== null ? log.warning("Error closing HKP loopback server: " + err) : void 0);
            });
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.global_init = 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: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.global_init"
          });
          _this.make_hkp_loopback(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 241
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    DecryptAndVerifyEngine.prototype.run = function(cb) {
      var esc, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      cb = chain(cb, this.run_cleanup.bind(this));
      esc = make_esc(cb, "DecryptAndVerifyEngine::run");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/dve.iced",
            funcname: "DecryptAndVerifyEngine.run"
          });
          _this.do_keypull(esc(__iced_deferrals.defer({
            lineno: 252
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/home/jacko/node-client/src/dve.iced",
              funcname: "DecryptAndVerifyEngine.run"
            });
            _this.setup_tmp_keyring(esc(__iced_deferrals.defer({
              lineno: 254
            })));
            __iced_deferrals._fulfill();
          })(function() {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/home/jacko/node-client/src/dve.iced",
                funcname: "DecryptAndVerifyEngine.run"
              });
              _this.do_command(esc(__iced_deferrals.defer({
                lineno: 255
              })));
              __iced_deferrals._fulfill();
            })(function() {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/jacko/node-client/src/dve.iced",
                  funcname: "DecryptAndVerifyEngine.run"
                });
                _this.find_signature(esc(__iced_deferrals.defer({
                  lineno: 256
                })));
                __iced_deferrals._fulfill();
              })(function() {
                (function(__iced_k) {
                  if (_this.found_sig) {
                    (function(__iced_k) {
                      __iced_deferrals = new iced.Deferrals(__iced_k, {
                        parent: ___iced_passed_deferral,
                        filename: "/home/jacko/node-client/src/dve.iced",
                        funcname: "DecryptAndVerifyEngine.run"
                      });
                      _this.handle_signature(esc(__iced_deferrals.defer({
                        lineno: 258
                      })));
                      __iced_deferrals._fulfill();
                    })(function() {
                      (function(__iced_k) {
                        if (_this.try_track()) {
                          (function(__iced_k) {
                            __iced_deferrals = new iced.Deferrals(__iced_k, {
                              parent: ___iced_passed_deferral,
                              filename: "/home/jacko/node-client/src/dve.iced",
                              funcname: "DecryptAndVerifyEngine.run"
                            });
                            _this.handle_track(esc(__iced_deferrals.defer({
                              lineno: 260
                            })));
                            __iced_deferrals._fulfill();
                          })(__iced_k);
                        } else {
                          (function(__iced_k) {
                            if (_this.try_id()) {
                              (function(__iced_k) {
                                __iced_deferrals = new iced.Deferrals(__iced_k, {
                                  parent: ___iced_passed_deferral,
                                  filename: "/home/jacko/node-client/src/dve.iced",
                                  funcname: "DecryptAndVerifyEngine.run"
                                });
                                _this.handle_id(esc(__iced_deferrals.defer({
                                  lineno: 262
                                })));
                                __iced_deferrals._fulfill();
                              })(__iced_k);
                            } else {
                              return __iced_k();
                            }
                          })(__iced_k);
                        }
                      })(__iced_k);
                    });
                  } else {
                    return __iced_k();
                  }
                })(function() {
                  return cb(null);
                });
              });
            });
          });
        };
      })(this));
    };

    return DecryptAndVerifyEngine;

  })();

}).call(this);
