// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var ArgumentParser, CodeSign, Main, PackageJson, constants, from_md, fs, iced, item_type_names, log, path, tablify, to_md, utils, vc, __iced_k, __iced_k_noop, _ref,
    __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() {};

  fs = require('fs');

  ArgumentParser = require('argparse').ArgumentParser;

  tablify = require('tablify');

  path = require('path');

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

  CodeSign = require('./codesign').CodeSign;

  constants = require('./constants');

  _ref = require('./markdown'), to_md = _ref.to_md, from_md = _ref.from_md;

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

  utils = require('./utils');

  log = require('iced-logger');

  vc = constants.verify_codes;

  Main = (function() {
    function Main() {
      this.pkjson = new PackageJson();
      this.args = null;
      this.init_parser();
    }

    Main.prototype.exit_err = function(e) {
      log.error(e.toString());
      return process.exit(1);
    };

    Main.prototype.init_parser = function() {
      var sign, subparsers, tojson, verify;
      this.ap = new ArgumentParser({
        addHelp: true,
        version: this.pkjson.version(),
        description: 'keybase.io directory codesign',
        prog: this.pkjson.bin()
      });
      subparsers = this.ap.addSubparsers({
        title: 'subcommands',
        dest: 'subcommand_name'
      });
      sign = subparsers.addParser('sign', {
        addHelp: true
      });
      verify = subparsers.addParser('verify', {
        addHelp: true
      });
      tojson = subparsers.addParser('tojson', {
        addHelp: true
      });
      sign.addArgument(['-o', '--output'], {
        action: 'store',
        type: 'string',
        help: 'output to a specific file'
      });
      sign.addArgument(['-p', '--presets'], {
        action: 'store',
        type: 'string',
        help: 'specify ignore presets, comma-separated',
        defaultValue: 'git,dropbox,kb'
      });
      sign.addArgument(['dir'], {
        nargs: '?',
        action: 'store',
        type: 'string',
        help: 'the directory to sign',
        defaultValue: '.'
      });
      sign.addArgument(['-q', '--quiet'], {
        action: 'storeTrue',
        help: 'withhold output unless an error'
      });
      verify.addArgument(['-i', '--input'], {
        action: 'store',
        type: 'string',
        help: 'load a specific signature file'
      });
      verify.addArgument(['dir'], {
        nargs: '?',
        action: 'store',
        type: 'string',
        help: 'the directory to verify',
        defaultValue: '.'
      });
      verify.addArgument(['-q', '--quiet'], {
        action: 'storeTrue',
        help: 'withhold output unless an error'
      });
      verify.addArgument(['-s', '--strict'], {
        action: 'storeTrue',
        help: 'fail on warnings (typically cross-platform problems)'
      });
      return tojson.addArgument(['-i', '--input'], {
        action: 'store',
        type: 'string',
        help: 'load a specific signature file to convert to JSON'
      });
    };

    Main.prototype.valid_presets = function() {
      var k, _results;
      _results = [];
      for (k in constants.presets) {
        _results.push(k.toLowerCase());
      }
      return _results;
    };

    Main.prototype.get_preset_list = function() {
      var k, presets, _i, _len;
      if (this.args.presets == null) {
        return this.exit_err("Expected comma-separated list of presets (valid values=" + (this.valid_presets().join(',')) + ")");
      } else {
        presets = this.args.presets.split(',');
        for (_i = 0, _len = presets.length; _i < _len; _i++) {
          k = presets[_i];
          if (!(__indexOf.call(this.valid_presets(), k) >= 0)) {
            this.exit_err("Unknown preset " + k + " (valid values=" + (this.valid_presets().join(',')) + ")");
          }
        }
        return presets;
      }
    };

    Main.prototype.get_ignore_list = function(output, cb) {
      var ignore, rel_ignore;
      rel_ignore = path.relative(this.args.dir, output).split(path.sep).join('/');
      ignore = rel_ignore.slice(0, 2) !== '..' ? ["/" + rel_ignore] : [];
      return cb(ignore);
    };

    Main.prototype.sign = function() {
      var err, ignore, o, output, summ, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      output = this.args.output || path.join(this.args.dir, constants.defaults.FILENAME);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/codesign/src/main.iced",
            funcname: "Main.sign"
          });
          _this.get_ignore_list(output, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return ignore = arguments[0];
              };
            })(),
            lineno: 89
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          summ = new CodeSign(_this.args.dir, {
            ignore: ignore,
            presets: _this.get_preset_list()
          });
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/max/src/keybase/codesign/src/main.iced",
              funcname: "Main.sign"
            });
            summ.walk(__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return err = arguments[0];
                };
              })(),
              lineno: 91
            }));
            __iced_deferrals._fulfill();
          })(function() {
            if (typeof err !== "undefined" && err !== null) {
              _this.exit_err(err);
            }
            summ.attach_sig("https://keybase.io/chris", "cbleahbleahbleah\nfooobar");
            summ.attach_sig("https://keybase.io/max", "mbleahbleahbleah\nbarrrrr");
            o = summ.to_json_obj();
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/codesign/src/main.iced",
                funcname: "Main.sign"
              });
              fs.writeFile(output, to_md(o) + "\n", {
                encoding: 'utf8'
              }, __iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return err = arguments[0];
                  };
                })(),
                lineno: 96
              }));
              __iced_deferrals._fulfill();
            })(function() {
              if (typeof err !== "undefined" && err !== null) {
                _this.exit_err(err);
              }
              if (!_this.args.quiet) {
                return log.info("Success! Output: " + output);
              }
            });
          });
        };
      })(this));
    };

    Main.prototype.run = function() {
      this.args = this.ap.parseArgs();
      switch (this.args.subcommand_name) {
        case 'sign':
          return this.sign();
        case 'verify':
          return this.verify();
        case 'tojson':
          return this.to_json();
      }
    };

    Main.prototype.to_json = function() {
      var body, err, input, json_obj, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      input = this.args.input || constants.defaults.FILENAME;
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/codesign/src/main.iced",
            funcname: "Main.to_json"
          });
          fs.readFile(input, 'utf8', __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return body = arguments[1];
              };
            })(),
            lineno: 115
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof err !== "undefined" && err !== null) {
            _this.exit_err("Couldn't open " + input + "; if using another filename pass with -i <filename>");
          }
          json_obj = from_md(body);
          if (json_obj == null) {
            return _this.exit_err("Failed to parse/load " + input);
          } else {
            return log.console.log(JSON.stringify(json_obj, null, 2));
          }
        };
      })(this));
    };

    Main.prototype.verify = function() {
      var body, err, err_table, input, json_obj, p, probs, summ, warn_table, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      input = this.args.input || path.join(this.args.dir, constants.defaults.FILENAME);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/codesign/src/main.iced",
            funcname: "Main.verify"
          });
          fs.readFile(input, 'utf8', __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return body = arguments[1];
              };
            })(),
            lineno: 130
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (typeof err !== "undefined" && err !== null) {
            _this.exit_err("Couldn't open " + input + "; if using another filename pass with -i <filename>");
          }
          json_obj = from_md(body);
          if (json_obj == null) {
            _this.exit_err("Failed to parse/load " + input);
          }
          summ = new CodeSign(_this.args.dir, {
            ignore: json_obj.ignore,
            presets: json_obj.presets
          });
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/max/src/keybase/codesign/src/main.iced",
              funcname: "Main.verify"
            });
            summ.walk(__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return err = arguments[0];
                };
              })(),
              lineno: 139
            }));
            __iced_deferrals._fulfill();
          })(function() {
            if (typeof err !== "undefined" && err !== null) {
              _this.exit_err(err);
            }
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/codesign/src/main.iced",
                funcname: "Main.verify"
              });
              summ.compare_to_json_obj(json_obj, __iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return probs = arguments[0];
                  };
                })(),
                lineno: 143
              }));
              __iced_deferrals._fulfill();
            })(function() {
              var _i, _j, _len, _len1, _ref1, _ref2;
              err_table = (function() {
                var _i, _len, _results;
                _results = [];
                for (_i = 0, _len = probs.length; _i < _len; _i++) {
                  p = probs[_i];
                  if ((p[0] >= 100) || this.args.strict) {
                    _results.push(p);
                  }
                }
                return _results;
              }).call(_this);
              warn_table = (function() {
                var _i, _len, _results;
                _results = [];
                for (_i = 0, _len = probs.length; _i < _len; _i++) {
                  p = probs[_i];
                  if ((p[0] < 100) && (!this.args.strict) && (!this.args.quiet)) {
                    _results.push(p);
                  }
                }
                return _results;
              }).call(_this);
              if (warn_table.length) {
                for (_i = 0, _len = warn_table.length; _i < _len; _i++) {
                  p = warn_table[_i];
                  log.warn("" + p[0] + "\t" + (((_ref1 = p[1].expected) != null ? _ref1.path : void 0) || p[1].got.path) + ":  " + p[1].msg);
                }
              }
              if (err_table.length) {
                for (_j = 0, _len1 = err_table.length; _j < _len1; _j++) {
                  p = err_table[_j];
                  log.error("" + p[0] + "\t" + (((_ref2 = p[1].expected) != null ? _ref2.path : void 0) || p[1].got.path) + ":  " + p[1].msg);
                }
                log.error("Exited after " + err_table.length + " error(s)");
                return process.exit(1);
              } else {
                if (!_this.args.quiet) {
                  log.info("Success! " + json_obj.found.length + " items checked" + (warn_table.length ? ' with ' + warn_table.length + ' warning(s); pass --strict to prevent success on warnings; --quiet to hide warnings' : ''));
                  log.info(json_obj.signatures.length + " signatures found:");
                  return log.info(JSON.stringify(json_obj.signatures));
                }
              }
            });
          });
        };
      })(this));
    };

    return Main;

  })();

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

}).call(this);
