require 'open3'
require 'tmpdir'

def run_command *args
  out, err, status = Open3.capture3 *args
  raise "#{args.first} failed: #{err}" unless status.success?
  out
end

class ResizedFavicon < Jekyll::StaticFile
  attr_reader :size

  def initialize site, name, source, size
    super site, site.source, "images", name
    @source = source
    @size = size
  end

  def path
    @source
  end

  def write dest
    dest_path = destination dest
    Jekyll.logger.info "Resizing:", dest_path
    FileUtils.mkdir_p File.dirname(dest_path)
    run_command "magick", @source, "-filter", "Lanczos", "-resize", "#{@size}x#{@size}", dest_path
    run_command "oxipng", "--quiet", "--opt", "2", "--strip", "all", dest_path
    true
  end
end

class FaviconGenerator < Jekyll::Generator
  # Needs to run after WebfontsGenerator
  priority :low

  def generate site
    Jekyll.logger.info "Favicon:", "Building"

    font_file = site.static_files.find do |f|
      f.is_a?(WebfontFile) && File.basename(f.path) == "Iosevka-Regular.woff2"
    end
    raise "Iosevka-Regular.woff2 not found in site.static_files" unless font_file

    @build_dir = Dir.mktmpdir "sup-favicon"
    at_exit { FileUtils.rm_r @build_dir }

    master_transparent = File.join @build_dir, "favicon-dark-256.png"
    Jekyll.logger.info "Rendering:", master_transparent
    render font_file.path, master_transparent, false

    master_with_tile = File.join @build_dir, "favicon-256.png"
    Jekyll.logger.info "Rendering:", master_with_tile
    render font_file.path, master_with_tile, true

    [16, 32, 48].each do |size|
      site.static_files << ResizedFavicon.new(site, "favicon-#{size}.png", master_with_tile, size)
      site.static_files << ResizedFavicon.new(site, "favicon-dark-#{size}.png", master_transparent, size)
    end
  end

  def render font_path, out_path, background
    # Render a normal fill layer and then two blur layers on top, mimicking the
    # phosphor glow effect from the stylesheet:
    # color #b5e853; text-shadow: 0 0 5px rgba(181,232,83,.5), 0 0 10px rgba(181,232,83,.5)
    text = ">@"
    fg_colour = "#b5e853"
    bg_colour = "#151515"
    args = ["magick", "-size", "256x256"]
    if background
      args += [
        "xc:none",
        "-fill", bg_colour,
        "-draw", "roundrectangle 8,8 247,247 40,40"
      ]
      pointsize = "160"
    else
      args += ["xc:none"]
      pointsize = "220"
    end
    text_layer = [
      "(",
        "-size", "256x256", "xc:none",
        "-font", font_path,
        "-pointsize", pointsize,
        "-fill", fg_colour,
        "-gravity", "center",
        "-annotate", "+0-4", text,
      ")",
    ]
    args += text_layer
    args += [
      "(", "-clone", "1", "-channel", "A", "-evaluate", "multiply", "0.65", "+channel", "-blur", "0x18", ")",
      "(", "-clone", "1", "-channel", "A", "-evaluate", "multiply", "0.75", "+channel", "-blur", "0x10", ")",
      "-delete", "1",
      "-background", "none",
      "-layers", "merge",
      "+repage",
    ]
    args += text_layer
    args += [ "-composite", out_path ]
    run_command *args
  end
end
