# Constructs the hook filename in format: [DIR]_[VERSION].[EXT].
# Where: [DIR] - The directory of the hook, by default it is a module name.
#        [VERSION] - The compatible Stork version.
#        [EXT] - Hook extension: .so
def construct_filename()
    gomod_content = IO.read("go.mod")
    # Finds the row that starts with "replace isc.org/stork",
    # next has "=>" operator delimited by white characters,
    # then the target dependency delimited by white characters,
    # and the version at the end. Captures the version.
    match = gomod_content.match(/^replace isc\.org\/stork\s+=>\s+\S+\s+(\S*)$/)
    version = match[1]

    dir_name = File.basename(Dir.getwd)

    return "#{dir_name}_#{version}.so"
end

desc "Build the hook
    DEBUG - build plugins in debug mode - default: false"
task :build do
    flags = []
    if ENV["DEBUG"] == "true"
        flags.append "-gcflags", "all=-N -l"
    end

    hook_name = construct_filename()
    
    build_dir = "build"
    sh "mkdir", "-p", build_dir

    output_path = File.join(build_dir, hook_name)

    sh "go", "mod", "tidy"
    sh "go", "build", *flags, "-buildmode=plugin", "-o", output_path

    size = File.size output_path
    size /= 1024.0 * 1024.0
    puts "Hook: '#{output_path}' size: #{'%.2f' % size} MiB"
end

desc "Lint the hook"
task :lint do
    sh "go", "vet"
end

desc "Run hook unit tests"
task :unittest do
    sh "go", "test", "-race", "-v", "./..." 
end
