<commit_before>require "conjur/debify/version"
require 'docker'
require 'fileutils'
require 'gli'
require 'json'
require 'base64'
require 'tmpdir'

require 'conjur/debify/utils'

require 'active_support'
require 'active_support/core_ext'

include GLI::App

DEFAULT_FILE_TYPE = "deb"

config_file '.debifyrc'

desc 'Set an environment variable (e.g. TERM=xterm) when starting a container'
flag [:env], :multiple => true

desc 'Mount local bundle to reuse gems from previous installation'
default_value true
switch [:'local-bundle']


Docker.options[:read_timeout] = 300

# This is used to turn on DEBUG notices.
module DebugMixin
  DEBUG = ENV['DEBUG'].nil? ? true : ENV['DEBUG'].downcase == 'true'

  def debug *a
    DebugMixin.debug *a
  end

  def self.debug *a
    $stderr.puts *a if DEBUG
  end

  def debug_write *a
    DebugMixin.debug_write *a
  end

  def self.debug_write *a
    $stderr.write *a if DEBUG
  end

  # you can give this to various docker methods to print output if debug is on
  def self.docker_debug *a
    if a.length == 2 && a[0].is_a?(Symbol)
      debug a.last
    else
      a.each do |line|
        begin
          line = JSON.parse(line)
          line.keys.each do |k|
            debug line[k]
          end
        rescue JSON::ParserError
          # Docker For Mac is spitting out invalid JSON, so just print
          # out the line if parsing fails.
          debug line
        end
      end
    end
  end

  DOCKER = method :docker_debug
end

program_desc 'Utility commands for building and testing Conjur appliance Debian packages'

version Conjur::Debify::VERSION

subcommand_option_handling :normal
arguments :strict

def detect_version
  if File.exists?("VERSION") && !(base_commit = `git log --pretty='%h' VERSION | head -n 1`.strip).empty?
    base_version = File.read("VERSION").strip
    commits_since = `git log #{base_commit}..HEAD --pretty='%h'`.split("\n").size
    hash = `git rev-parse --short HEAD`.strip
    [[base_version, commits_since].join('.'), hash].join("-")
  else
    `git describe --long --tags --abbrev=7 --match 'v*.*.*' | sed -e 's/^v//'`.strip.tap do |version|
      raise "No Git version (tag) for project" if version.empty?
    end
  end
end

def git_files
  (`git ls-files -z`.split("\x0") + ['Gemfile.lock']).uniq
end

def login_to_registry(appliance_image_id)
  config_file = File.expand_path('~/.docker/config.json')
  if File.exist? config_file
    json_config = JSON.parse(File.read(config_file))
    registry = appliance_image_id.split('/')[0]

    json_auth = json_config['auths'][registry]['auth']
    if json_auth
      username, password = Base64.decode64(json_auth).split(':')
      Docker.authenticate! username: username, password: password, serveraddress: registry
    end
  end
end

desc "Clean current working directory of non-Git-managed files"
long_desc <<DESC
Reliable builds depend on having a clean working directory.<commit_msg>Make git_files ignore submodule dirs<commit_after>require "conjur/debify/version"
require 'docker'
require 'fileutils'
require 'gli'
require 'json'
require 'base64'
require 'tmpdir'

require 'conjur/debify/utils'

require 'active_support'
require 'active_support/core_ext'

include GLI::App

DEFAULT_FILE_TYPE = "deb"

config_file '.debifyrc'

desc 'Set an environment variable (e.g. TERM=xterm) when starting a container'
flag [:env], :multiple => true

desc 'Mount local bundle to reuse gems from previous installation'
default_value true
switch [:'local-bundle']


Docker.options[:read_timeout] = 300

# This is used to turn on DEBUG notices.
module DebugMixin
  DEBUG = ENV['DEBUG'].nil? ? true : ENV['DEBUG'].downcase == 'true'

  def debug *a
    DebugMixin.debug *a
  end

  def self.debug *a
    $stderr.puts *a if DEBUG
  end

  def debug_write *a
    DebugMixin.debug_write *a
  end

  def self.debug_write *a
    $stderr.write *a if DEBUG
  end

  # you can give this to various docker methods to print output if debug is on
  def self.docker_debug *a
    if a.length == 2 && a[0].is_a?(Symbol)
      debug a.last
    else
      a.each do |line|
        begin
          line = JSON.parse(line)
          line.keys.each do |k|
            debug line[k]
          end
        rescue JSON::ParserError
          # Docker For Mac is spitting out invalid JSON, so just print
          # out the line if parsing fails.
          debug line
        end
      end
    end
  end

  DOCKER = method :docker_debug
end

program_desc 'Utility commands for building and testing Conjur appliance Debian packages'

version Conjur::Debify::VERSION

subcommand_option_handling :normal
arguments :strict

def detect_version
  if File.exists?("VERSION") && !(base_commit = `git log --pretty='%h' VERSION | head -n 1`.strip).empty?
    base_version = File.read("VERSION").strip
    commits_since = `git log #{base_commit}..HEAD --pretty='%h'`.split("\n").size
    hash = `git rev-parse --short HEAD`.strip
    [[base_version, commits_since].join('.'), hash].join("-")
  else
    `git describe --long --tags --abbrev=7 --match 'v*.*.*' | sed -e 's/^v//'`.strip.tap do |version|
      raise "No Git version (tag) for project" if version.empty?
    end
  end
end

def git_files
  files = (`git ls-files -z`.split("\x0") + ['Gemfile.lock']).uniq
  # Since submodule directories are listed, but are not files, we remove them.
  # Currently, `conjur-project-config` is the only submodule in Conjur, and it
  # can safely be removed because it's a developer-only tool.  If we add another
  # submodule in the future needed for production, we'll need to update this
  # code.  But YAGNI for now.
  files.select { |f| File.file?(f) }
end

def login_to_registry(appliance_image_id)
  config_file = File.expand_path('~/.docker/config.json')
  if File.exist? config_file
    json_config = JSON.parse(File.read(config_file))
    registry = appliance_image_id.split('/')[0]

    json_auth = json_config['auths'][registry]['auth']
    if json_auth
      username, password = Base64.decode64(json_auth).split(':')
      Docker.authenticate! username: username, password: password, serveraddress: registry
    end
  end
end

desc "Clean current working directory of non-Git-managed files"
long_desc <<DESC
Reliable builds depend on having a clean working directory.
{'fraction_non_alphanumeric': 0.1145001596933887, 'fraction_numerical': 0.0047908016608112424, 'mean_word_length': 3.3493055555555555, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4185962', 'n_tokens_mistral': 2074, 'n_tokens_neox': 1979, 'n_words': 637}