#!/usr/bin/env ruby
# frozen_string_literal: true

# Ruby internal
# Project internal
require 'haiti'
# External
require 'docopt'
require 'paint'

doc = <<~DOCOPT
  #{Paint['HAITI (HAsh IdenTifIer)', '#FF69B4']} v#{Paint[HashIdentifier::VERSION, :bold]}

  #{Paint['Usage:', '#00FFFF']}
    haiti-parsable hc [options] <hash>
    haiti-parsable jtr [options] <hash>
    haiti-parsable -h | --help
    haiti-parsable --version

  #{Paint['Commands:', '#00FFFF']}
    hc             Display hash types matching that have a Hashcat reference
    jtr            Display hash types matching that have a John the Ripper reference

  #{Paint['Parameters:', '#00FFFF']}
    <hash>          Hash string to identify, read from STDIN if equal to "-"

  #{Paint['Options:', '#00FFFF']}
    -e, --extended  List all possible hash algorithms including ones using salt
    --debug         Display arguments
    -h, --help      Show this screen
    --version       Show version

  #{Paint['Examples:', '#00FFFF']}
    haiti-parsable hc -e d41d8cd98f00b204e9800998ecf8427e
    haiti-parsable jtr d41d8cd98f00b204e9800998ecf8427e

  #{Paint['Project:', '#00FFFF']}
    #{Paint['author', :underline]} (https://pwn.by/noraj / https://twitter.com/noraj_rawsec)
    #{Paint['source', :underline]} (https://github.com/noraj/haiti)
    #{Paint['documentation', :underline]} (https://noraj.github.io/haiti)
DOCOPT

def manage_options(args, types)
  types.each do |type|
    next if type.extended && !args['--extended']

    puts "#{type.name} |#{type.hashcat}" if args['hc'] && !type.hashcat.nil?
    puts "#{type.name} |#{type.john}" if args['jtr'] && !type.john.nil?
  end
end

begin
  args = Docopt.docopt(doc, version: HashIdentifier::VERSION)
  puts args if args['--debug']
  # use case 1, using the tool
  if args['<hash>']
    args['<hash>'] = $stdin.read.chomp if args['<hash>'] == '-'
    hi = HashIdentifier.new(args['<hash>'])
    if hi.type.empty?
      puts 'Unknown hash type'
      exit(0)
    end
    manage_options(args, hi.type)
  end
  # use case 2, help: already handled by docopt
  # use case 3, version: already handled by docopt
rescue Docopt::Exit => e
  puts e.message
end
