require 'hpricot'
require 'open-uri'
require 'zlib'
require 'archive/tar/minitar'
require 'find'
require 'fileutils'
require 'tempfile'
require 'zip/zip'
require 'highline'

require 'iconv'

def utf8lize(str)
  Iconv.new("utf-8", "cp949").iconv str
end

if RUBY_PLATFORM =~ /win/
  CONV = Iconv.new "cp949", "utf-8"
  def puts(*args)
    args = args.collect {|arg| CONV.iconv arg}
    super *args
  end

  def encoding_fix(name)
    name
  end
else
  CONV = Iconv.new "utf-8", "cp949"
  def encoding_fix(name)
    CONV.iconv name
  end
end

def debug
  ret = yield
  puts ret if ret.instance_of? String
end

WORKING_DIR = $tmp_working ? Dir::tmpdir + "/free_fonts" : "."

module NForgeDownloader
  def download
    debug { "Download #{@project} latest version." }

    doc = open("http://#{@site}/projects/#{@project}/download") do |f|
      ret = ''
      until f.eof?
        ret.concat f.read
      end
      Hpricot.parse ret
    end

    links = (doc/'#project_content'/'.file'/:a)

    link = links.find &method(:get_preferred_item)
    if link.nil?
      debug { " Cannot find prefered item! Download first item. " }
      link = links[0]
    end

    debug { " Download page: #{link[:href]}" }
    debug { " File name: #{link[:title]}" }

    doc = open("http://#{@site}" + link[:href], "r") do |f|
      ret = ''
      until f.eof?
        ret.concat f.read
      end
      Hpricot.parse ret
    end

    target = doc.get_element_by_id 'file_download'

    debug { " Target link: #{target[:src]}" }

    debug { " Download start..." }
    filename = WORKING_DIR + "/" + link[:title]
    open("http://#{@site}" + target[:src], "rb") do |src|
      open(filename, "wb") do |dst|
        until src.eof?
          dst.write src.read
        end
      end
    end
    debug { " Download complete!" }

    @downloaded = filename
  end

  protected
  def get_preferred_item(link)
    true
  end

  protected
  def initialize_downloader(site, project)
    @site = site
    @project = project
  end
end

module TarGzDistribution
  def extract
    if @downloaded.nil?
      debug { "You must download first!" }
      return nil 
    end

    debug { "Start unpacking..." }
    Archive::Tar::Minitar.unpack Zlib::GzipReader.new(File.open(@downloaded, 'rb')), Dir::tmpdir + '/work'

    debug { "Copying font files and copyright files..." }

    working_dir = WORKING_DIR + "/" + self.class.to_s.sub(/:.*$/, '')
    begin
      Dir.mkdir working_dir
    rescue Errno::EEXIST
    end
    Find.find Dir::tmpdir + '/work' do |filename|
      if filename =~ /\.ttf$|\.ttc$|COPYRIGHT|COPYING/i
        debug { " #{filename} is copying..." }
        FileUtils.mv filename, working_dir + "/" + filename[/[^\/]+$/]
      end
    end

    debug { "Copying finished." }

    FileUtils.rm_rf Dir::tmpdir + '/work'
    debug { "Working directory is cleaned." }
  end

  protected
  def get_preferred_item(link)
    link[:title] =~ /\.tar\.gz$|\.tgz$/
  end
end

module ZipDistribution
  def extract
    if @downloaded.nil?
      debug { "You must download first!" }
      return nil 
    end

    debug { "Start unpacking..." }

    working_dir = WORKING_DIR + "/" + self.class.to_s.sub(/:.*$/, '')
    begin
      Dir.mkdir working_dir
    rescue Errno::EEXIST
    end
    Zip::ZipInputStream::open(@downloaded) do |io|
      while entry = io.get_next_entry
        if entry.name =~ /\.ttf$|\.ttc$|COPYRIGHT|COPYING|\.exe$/i
          open("#{working_dir}/#{encoding_fix entry.name}", "wb") do |file|
            file.write io.read
          end
        end
      end
    end
  end

  def copyright
    :OFL
  end

  protected
  def get_preferred_item(link)
    link[:title] =~ /\.zip$/
  end
end

class Baekmuk
  include NForgeDownloader
  include TarGzDistribution

  def initialize
    self.initialize_downloader 'kldp.net', 'baekmuk'
  end

  def copyright
    :BSD
  end
end

class Unfonts
  class UnfontsCommon
    include NForgeDownloader
    include TarGzDistribution

    private
    def initialize(prefer)
      self.initialize_downloader 'kldp.net', 'unfonts'
      @prefer = prefer
    end

    def get_preferred_item(link)
      super(link) and link[:title] =~ @prefer
    end
  end

  class UnfontsCore < UnfontsCommon
    private
    def initialize
      super /core/
    end
  end

  class UnfontsExtra < UnfontsCommon
    private
    def initialize
      super /extra/
    end
  end

  def initialize
    @downloaders = [ UnfontsCore.new, UnfontsExtra.new ]
  end

  def copyright
    :GPL
  end

  [ :download, :extract ].each {|operation| eval "def #{operation}; @downloaders.collect {|downloader| downloader.#{operation}}; end"}
end

class Lexifont
  include NForgeDownloader

  def initialize
    self.initialize_downloader 'kldp.net', 'linuxlexifont'
  end

  def extract
    debug { "Done!" }
  end

  def copyright
    :GPL
  end

  protected
  def get_preferred_item(link)
    link[:title] =~ /\.ttf$/
  end
end

class NanumfontCoding
  include NForgeDownloader
  include ZipDistribution

  def initialize
    self.initialize_downloader 'dev.naver.com', 'nanumfont'
  end
end

class Arita
  include ZipDistribution

  def download
    debug { "Arita: Parsing font download page..." }

    doc = Hpricot.parse open('http://www.amorepacific.co.kr/company/ci/font.jsp') {|f| f.read}

    link = (doc/"#ContPrt"/".BtnCtr"/:a).find {|link| link[:href] =~ /win/}

    debug { " Target file: #{link[:href]}" }

    debug { " Download start..." }
    open("http://www.amorepacific.co.kr" + link[:href], "rb") do |src|
      open(WORKING_DIR + "/" + link[:href][/[^\/]*$/], "wb") do |dst|
        until src.eof?
          dst.write src.read
        end
      end
    end
    debug { " Download complete!" }

    @downloaded = WORKING_DIR + "/" + link[:href][/[^\/]*$/]
  end

  def copyright
    doc = Hpricot.parse open('http://www.amorepacific.co.kr/company/ci/font.jsp') {|f| f.read}

    { :url => "http://www.amorepacific.co.kr/company/ci/" + (doc/"#Fnt2"/:img)[2][:src], :text => <<END_OF_LICENSE
01 아리따체의 지적재산권은 아모레퍼시픽에 있습니다.
02 아리따체는 개인 및 기업사용자에게 무료로 제공되며, 사용자들도 다른 이에게 자유롭게 배포할 수 있습니다. 단, 이 과정에서 어떠한 이유로든 복사 및 배포의 대가로 요금을 부과할 수 없습니다,
03 아리따체는 어떠한 이유로도 지적 재산권자 이외의 사용자가 수정, 판매할 수 없으며, 배포되는 형태 그대로 사용해야 합니다.
04 아리따체를 사용해 출판물을 낼 경우 글꼴 출처를 표시해야 합니다.
END_OF_LICENSE
    }
  end
end

class Daum
  include ZipDistribution

  def download
    debug { "Daum: Parsing font download page..." }

    doc = Hpricot.parse open('http://fontevent.daum.net/') {|f| f.read}

    target_file = (doc/"#Map"/:area)[1][:href]

    debug { " Target file: #{target_file}" }

    debug { " Download start..." }
    open(target_file, "rb") do |src|
      open(WORKING_DIR + "/" + target_file[/[^\/]*$/], "wb") do |dst|
        until src.eof?
          dst.write src.read
        end
      end
    end
    debug { " Download complete!" }

    @downloaded = WORKING_DIR + "/" + target_file[/[^\/]*$/]
  end

  def copyright
    { :url => 'http://imgsrc.search.hanmail.net/event/0912_hangul/han_img22.jpg', :text => 'Daum체는 상업적인 목적으로 사용할 수 없습니다.' }
  end
end

class Nanumfonts
  include ZipDistribution

  def download
    debug { "Nanumfonts: Parsing font download page..." }

    doc = Hpricot.parse open('http://hangeul.naver.com/share.nhn') {|f| f.read}

    link = (doc/"#content"/".share_area"/:dd/:a).find {|link| link[:onclick] =~ /zip/}

    debug { " Target file: #{link[:href]}" }

    debug { " Download start..." }
    open(link[:href], "rb") do |src|
      open(WORKING_DIR + "/" + link[:href][/[^\/]*$/], "wb") do |dst|
        until src.eof?
          dst.write src.read
        end
      end
    end
    debug { " Download complete!" }

    @downloaded = WORKING_DIR + "/" + link[:href][/[^\/]*$/]
  end

  def copyright
    doc = Hpricot.parse open('http://hangeul.naver.com/share.nhn') {|f| f.read}
    { :url => 'http://hangeul.naver.com/share.nhn', :text => (doc/"#tip3").inner_text }
  end
end

class Jeollabukdo
  def download
    debug { "Jeollabukdo: Parsing font download page..." }

    doc = Hpricot.parse open('http://www.jeonbuk.go.kr/01kr/06governor/05jb_symbol/04font/index.jsp', 'User-Agent' => 'ruby', 'Host' => '127.0.0.1') {|f| f.read}
    links = (doc/:a).find_all {|link| link[:href] =~ /\.ttf$/i}

    debug { " Target files: #{links.collect {|link| link[:href]}.inspect}" }

    debug { " Making working directory..." }
    working_dir = WORKING_DIR + "/Jeollabukdo"
    begin
      Dir.mkdir working_dir
    rescue Errno::EEXIST
    end
    debug { " Download start..." }
    links.each do |link|
      debug { " Download #{link[:href]}..." }
      open("http://www.jeonbuk.go.kr" + link[:href], "rb", 'User-Agent' => 'ruby', 'Host' => '127.0.0.1') do |src|
        open(working_dir + "/" + link[:href][/[^\/]*$/], "wb") do |dst|
          until src.eof?
            dst.write src.read
          end
        end
      end
      debug { " Done!" }
    end
    debug { " Download complete!" }
  end

  def extract
    debug { "Done!" }
  end

  def copyright
    { :url => 'http://www.jeonbuk.go.kr/01kr/06governor/05jb_symbol/04font/index.jsp', :text => <<END_OF_LICENSE
* 서 체 명 : 전라북도체M, 전라북도체L(2종)
* 제작 및 배포 : 전라북도
* 소 유 권 : 전라북도
* 연 락 처 : Tel.063-280-2111 Fax. 063-280-2119 (http://www.jeonbuk.go.kr)
END_OF_LICENSE
}
  end
end

class NaverDic
  include TarGzDistribution

  def download
    debug { "NaverDic: Parsing font download page..." }

    doc = Hpricot.parse open('http://cndic.naver.com/static/fontInstall') {|f| f.read}

    link = (doc/"#content"/:a).find {|link| link[:href] =~ /\.tgz$/}

    debug { " Target file: #{link[:href]}" }

    debug { " Download start..." }
    open(link[:href], "rb") do |src|
      open(WORKING_DIR + "/" + link[:href][/[^\/]*$/], "wb") do |dst|
        until src.eof?
          dst.write src.read
        end
      end
    end
    debug { " Download complete!" }

    @downloaded = WORKING_DIR + "/" + link[:href][/[^\/]*$/]
  end

  def copyright
    { :url => 'http://cndic.naver.com/static/fontInstall', :text => "네이버 사전을 사랑해 주시는 이용자 여러분의 기대에 부응하기 위해 한양정보통신과 제휴하여 '네이버사전체'를 이용자 여러분께 무상으로 제공해 드립니다." }
  end
end

class SeoulFonts
  include ZipDistribution

  def download
    debug { "SeoulFonts: Parsing font download page..." }

    doc = Hpricot.parse open('http://design.seoul.go.kr/dscontent/designseoul.php?MenuID=490&pgID=237') {|f| f.read}

    target = (doc/'#mainColumn'/'.dlCont1'/:a)[0][:href]

    debug { " Target file: #{target}" }

    debug { " Download start..." }
    resp = Net::HTTP.get_response('design.seoul.go.kr', target)
    downloaded = WORKING_DIR + "/" + encoding_fix(resp['content-disposition']).sub(/^.*filename=([^;]*).*$/, '\1')
    open(downloaded, "wb") do |dst|
      dst.write resp.body
    end
    debug { " Download complete!" }

    @downloaded = downloaded
  end

  def extract
    debug { " Unfortunately, SeoulFonts supports only WindowsInstaller." }

    super
  end

  def copyright
    { :url => 'http://design.seoul.go.kr/dscontent/designseoul.php?MenuID=490&pgID=237', :text => <<END_OF_LICENSE
서울서체
- 서울시는 서울의 고유글꼴로 널리 활용되며 도시정체성과 브랜드 가치를 높여줄 서울서체로 명조계열인
서울한강체 2종(Light, Medium)과 고딕계열인 서울남산체(Light, Medium, Bold, Extra Bold)4종,
세로쓰기1종 등 총 7종을 개발했다. 서울서체는 강직한 선비정신과 단아한 여백을 담고 있으며
조형적으로는 한옥의 열림과 기와의 곡선미를 표현하였다. 또한 이름으로는 서울의 대표적인 자산인
'한강'과 '남산'을 응용한 서울서체는 우리민족 고유의 아름다운 언어인 한글의 문화적 자긍심을
더욱 높일 것 이다.
END_OF_LICENSE
}
  end
end

class AuctionGothic
  include ZipDistribution

  def download
    debug { "AuctionGothic: Parsing font download page..." }

    doc = Hpricot.parse open('http://event.auction.co.kr/event2008/12/GoodBye2008/?frm=widescreen8') {|f| f.read}

    area = (doc/"#sd_Map"/:area).find {|area| area[:href] !~ /Install/i}

    debug { " Target file: #{area[:href]}" }

    debug { " Download start..." }
    open(area[:href], "rb") do |src|
      open(WORKING_DIR + "/" + area[:href][/[^\/]*$/], "wb") do |dst|
        until src.eof?
          dst.write src.read
        end
      end
    end
    debug { " Download complete!" }

    @downloaded = WORKING_DIR + "/" + area[:href][/[^\/]*$/]
  end

  def copyright
    { :url => "http://eventimg.auction.co.kr/PD/BX/event/goodbye2008/003.gif", :text => <<END_OF_LICENSE
옥션고딕의 지적재산권은 (주)옥션에 있으며, 이에 대한 모든 권리는 옥션에 있습니다. 옥션 고딕은 개인에게 무료로 제공되지만 옥션고딕의 형태를 변형해서 이용하거나, 당사의 허락 없이 상업적인 용도로 사용하실 수 없습니다.
END_OF_LICENSE
    }
  end
end

class YonseiFonts
  def download
    debug { "YonseiFonts: Parsing font download page..." }

    doc = Hpricot.parse open('http://www.yonsei.ac.kr/contents/intro/font.html') {|f|f.read}

    list = (doc/".this_LP"/:a).collect {|link| link[:href]}.delete_if{|link| link !~ /\.exe$|\.ttf$/i}

    debug { " Target files: #{list.inspect}" }

    working_dir = WORKING_DIR + "/YonseiFonts"
    begin
      Dir.mkdir working_dir
    rescue Errno::EEXIST
    end

    debug { " Download start..." }
    list.each do |link|
      debug { " Download #{link}... " }
      open("http://www.yousei.ac.kr" + link) do |src|
        open(working_dir + "/" + link[/[^\/]*$/]) do |dst|
          until src.eof?
            dst.write src.read
          end
        end
      end
      debug { " Done!"}
    end
    debug {" Download Finished!" }
  end

  def extract
    debug { "Unfortunately, YonseiFonts provided in Win32 EXE format only." }
  end

  def copyright
    { :text => <<END_OF_LICENSE
소프트웨어 사용계약서


사용자가 본 소프트웨어를 설치하는 행위는 본 사용계약서 내용에 동의하는 것으로간주되며, 모든 계약 내용을 지켜야 합니다. 만약 이 계약서 내용에 동의하지 않을경우, 제품 설치를 중지하여 주십시오 . 

1. 계약 내용

가. 사용권 제공
|주|윤디자인연구소(공급자)는 사용자에게 본 패키지에 포함된 소프트웨어를 사용할 수 있는 권리를 드립니다. 이는 소프트웨어의 소유권에 대한 계약이 아니며,사용권에 대한 계약입니다. 

나. 저작권 안내
본 패키지에 포함된 소프트웨어와 모든 부속물에 대한 저작권과 지적소유권은 모두 |주|윤디자인연구소가 보유하고 있으며, 대한민국 저작권법과 국제 저작권 협약에 의해 보호받고 있습니다.
저작권자의 사전 승인없이 DTP(전자출판) 이외의 용도 변경(PDF 임베이딩등)의 사용을 금합니다.

다. 복제의 허용과 제한
저작권자의 사전 서면 승인없이는 소프트웨어와 부속 인쇄물에 대한 수정, 변형,복사, 대여, 임대, 재판매, 배포를 할 수 없습니다.

라. 기능과 효과 
본 제품은 일반적인 환경을 기준으로 하기 때문에 모든 환경에서 완벽할 수는 없습니다. 따라서 개인의 특수한 환경에서는 완벽하게 동작하지 않을 수도 있습니다. 
사용자가 사용상의 문제점을 의뢰하실 경우 사용자의 불편을 최대한 해결해 드리겠습니다. 

마. 설치
본 소프트웨어는 10대의 컴퓨터에서만 실행해야 합니다. 서버나 네트웍에 연결된 컴퓨터에 설치한 후 다른 컴퓨터에서 이에 접속하여 사용하거나 실행해서는 안됩니다.

2. 보증의 한계

본 제품에 포함된 소프트웨어와 부속물의 내용이나 기능의 완벽성에 대한 보증은 해드리지 못합니다. 개발자 및 공급자는 정상적인 사용환경에서 사용하는 통상적인 사용자들이 무리없이 사용할 수 있도록 본 제품을 개발하고 테스트하였으나, 사용자 개개인의 특수한 사용환경, 사용자의 사용 경험과 능력, 현재 또는 미래의 모든 사용환경 등에서 항상 완벽하게 동작한다는 보증을 해드리지 못함을 양해해 주시기 바랍니다. 하지만, 사용자가 사용상 문제점을 발견 보고하게 될 경우, 당사는 그 문제 해결에 최선을 다해 사용자의 불편을 신속히 해결하도록 노력할 것을 약속합니다.


⒞ |주|윤디자인연구소, 1989~2004

서울시 서초구 잠원동 29-22  윤디자인빌딩
전화: (02) 516-6040~1     팩스: 543-3864
END_OF_LICENSE
    }
  end
end

module LoginRequired
  def login(id, pass)
    @id = id
    @pass = pass
  end
end

require 'net/https'
class ::Net::HTTP
  alias verify_mode_orig= verify_mode=

  def verify_mode=(x)
    verify_mode_orig = OpenSSL::SSL::VERIFY_NONE
  end
end

class MokpanFonts
  include LoginRequired
  include ZipDistribution

  def download
    debug { "MokpanFonts: Parse font download page" }

    debug { " Login..." }
    http = Net::HTTP.new "www.mokpan.com", 443
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    resp = http.get "/Member/login.asp"
    cookies = []
    resp['set-cookie'].each {|cookie| cookies.push cookie[/^[^;]*/]}

    doc = Hpricot.parse resp.body

    resp = http.request_post "/Member/" + (doc/:form)[0][:action], "mem_id=#{@id}&mem_pass=#{@pass}", 'Cookie' => cookies.join('; ')

    doc = Hpricot.parse open("https://www.mokpan.com/Gift/font.asp", 'Cookie' => cookies.join('; ')) {|f|f.read}
    target = doc.get_element_by_id('down1').parent[:href]
    
    debug { " Target file: #{target}" }

    debug { " Download start..." }
    open("https://www.mokpan.com" + target, "rb") do |src|
      open(WORKING_DIR + "/" + target[/[^\/]*$/], "wb") do |dst|
        until src.eof?
          dst.write src.read
        end
      end
    end
    debug { " Download Complete!" }

    @downloaded = WORKING_DIR + "/" + target[/[^\/]*$/]
  end

  def copyright
    { :url => "https://www.mokpan.com/Gift/font.asp", :text => <<END_OF_LICENSE
이 글꼴은 아래에 정한 '무료 사용의 대상과 범위'에 한해서만 사용할 수 있으며, 여기서 정하지 않은 다른 모든 경우에
사용할 때에는 반드시 정품을 구매해서 사용하셔야 합니다.

무료 사용의 대상과 범위

- 비영리 목적의 개인사용 : 개인 홈페이지ㆍ블로그ㆍ미니홈피, 가족신문, 동아리 유인물, 논문집의 표지 등
- 비영리 목적의 공공사용 : 초ㆍ중ㆍ고교의 학급문집ㆍ교지ㆍ교내 게시물
END_OF_LICENSE
    }
  end
end

class YoondesignFonts
  include LoginRequired

  def download
    debug { "YoondesignFonts: Parse font download page" }

    debug { " Login..." }
    f = open "http://yoonfont.co.kr/login/login.asp"
    cookies = f.meta['set-cookie'].collect {|cookie| cookie[/^[^;]*/]}
    doc = Hpricot.parse f.read
    f.close!

    form = (doc/:form).find {|form| form[:name] == 'frm'}
    uri = URI.parse form[:action]
    http = Net::HTTP.new uri.host, uri.port
    if uri.class == URI::HTTPS
      http.use_ssl = true
      http.verify_mode_orig = OpenSSL::SSL::VERIFY_NONE
    end
    resp = http.request_post(uri.path, "userid=#{@id}&password=#{@pass}", 'Cookie' => cookies.join('; ')).header
    cookies.concat resp['set-cookie'].collect {|cookie| cookie[/^[^;]*/]}

    doc = Hpricot.parse open("http://yoonfont.co.kr/customer/download_list.asp?code=03", 'Cookie' => cookies.join('; ') + "; userid=#{@id}") {|f| f.read}

    targets = (doc/:a).find_all{|link| link[:href] =~ /os=3/}.collect{|link| (link.parent.parent/:a)[1][:href]}

    debug { " Target files: #{targets.inspect}" }

    working_dir = WORKING_DIR + "/YoondesignFonts"
    begin
      Dir.mkdir working_dir
    rescue Errno::EEXIST
    end

    debug { " Download start..." }
    targets.each do |target|
      debug { " Download #{target}..." }
      open("http://yoonfont.co.kr/customer/" + target, "rb") do |src|
        open(working_dir + "/" + target[/[^=]*$/], "wb") do |dst|
          until src.eof?
            dst.write src.read
          end
        end
      end
      debug { " Done!" }
    end

    debug { " Download Completed!" }
  end

  def extract
    debug { " Unfortunately, this font only support Win32 EXE format." }
  end

  def copyright
    { :url => 'http://yoonfont.co.kr/customer/download_list.asp?code=03', :text => <<END_OF_LICENSE
독도체의 저작권 및 소유권등의 제반관리는 (주)윤디자인연구소에 규속되어 있습니다. 상업적 목적의 사용과 수정 및 개작, 개명을 통한 사용을 금하며, (주)윤디자인연구소와 협의 없이 재배포할 수 없습니다.
손글씨공모전당선서체의 저작권 및 소유권등의 제반관리는 (주)윤디자인연구소에 규속되어 있습니다. 상업적 목적의 사용과 수정 및 개작, 개명을 통한 사용을 금하며, (주)윤디자인연구소와 협의 없이 재배포할 수 없습니다.
웹돋움웹폰트의 저작권 및 소유권등의 제반관리는 (주)윤디자인연구소에 규속되어 있습니다. 상업적 목적의 사용과 수정 및 개작, 개명을 통한 사용을 금하며, (주)윤디자인연구소와 협의 없이 재배포할 수 없습니다.
웹바탕웹폰트의 저작권 및 소유권등의 제반관리는 (주)윤디자인연구소에 규속되어 있습니다. 상업적 목적의 사용과 수정 및 개작, 개명을 통한 사용을 금하며, (주)윤디자인연구소와 협의 없이 재배포할 수 없습니다.
END_OF_LICENSE
    }
  end
end

module URI
  class << self
    private
    alias split_orig split
 
    public
    def split(uri)
      split_orig uri.gsub(/[\x7f-\xff]/) {|x| sprintf "%%%02x", x[0]}
    end
  end
end

require 'cgi'

class AsiaFonts
  include LoginRequired

  class UnZipper
    include ZipDistribution

    def target=(target)
      @downloaded = target
    end
  end

  def initialize
    @downloaded = []
  end

  def download
    @downloaded = []
    debug { "AsiaFonts: Parse font download page" }

    debug { " Login..." }
    f = open "http://asiafont.com/asia2009/m_login.php"
    cookies = f.meta['set-cookie'].collect {|cookie| cookie[/^[^;]*/]}
    doc = Hpricot.parse f.read
    f.close

    form = (doc/:form)[0]
    Net::HTTP.start("asiafont.com", 80) {|http| http.post("/asia2009/" + form[:action], "login_id=#{@id}&login_pass=#{@pass}", 'Cookie' => cookies.join('; '))}

    doc = Hpricot.parse open("http://asiafont.com/asia2009/m_board.php?ps_db=downwin", 'Cookie' => cookies.join('; ')){|f| f.read}
    pages = (doc/:a).find_all {|link| link[:href] =~ /ps_boid/}

    debug { " Target files: #{pages.collect{|page| utf8lize page.inner_text}.join ', '}" }
    working_dir = WORKING_DIR + "/" + self.class.to_s.sub(/:.*$/, '')
    begin
      Dir.mkdir working_dir
    rescue Errno::EEXIST
    end

    debug { " Download start..." }
    pages.each do |page|
      unless page.inner_text.gsub(/^\s+|\s+$/, '') == ''
        debug { " Download #{utf8lize page.inner_text}..." }
        doc = Hpricot.parse open("http://asiafont.com/asia2009/" + page[:href], 'Cookie' => cookies.join('; ')){|f|f.read}
        link = (doc/:a).find {|link| link[:href] =~ /download/i}[:href]

        open("http://asiafont.com/asia2009/" + link, "rb", 'Cookie' => cookies.join('; ')) do |src|
          open(working_dir + "/" + encoding_fix(CGI.unescape(src.base_uri.path[/[^\/]*$/])), "wb") do |dst|
            until src.eof?
              dst.write src.read
            end
          end
          @downloaded.push working_dir + "/" + encoding_fix(CGI.unescape(src.base_uri.path[/[^\/]*$/]))
        end
        debug { " Done!" }
      end
    end
    debug { " Download Complete!" }
  end

  def extract
    debug { " Unfortunately, this font provides only Win32 EXE format" }
    unzipper = UnZipper.new
    @downloaded.find_all{|dn| dn =~ /\.zip$/i}.each {|dn| unzipper.target = dn; unzipper.extract }
    debug { " Done!" }
  end

  def copyright
    { :url => 'http://asiafont.com/asia2009/m_view.php?ps_db=downwin&ps_boid=33', :text => <<END_OF_LICENSE
⊙ (주)아시아소프트에서 제공되는 글꼴과 소프트웨어 및 기록 매체에 대한 저작권, 배포권 등의
　 일체의 권리는 (주)아시아소프트의 소유 입니다.
⊙ (주)아시아소프트의 허락을 득하지 않고 제품 변형이나 무단복제, 재배포, 판매를 금하고 있으며
　 방송자막, 출판물 및 제작물을 만들거나 기업 CI, BI에 사용하시려면 반드시 당사의 서면
　 승인을 (라이센스) 받으셔야 합니다. 
END_OF_LICENSE
    }
  end
end

SUPPORTED_FONTS = {
  :baekmuk => Baekmuk,
  :unfonts => Unfonts,
  :lexifont => Lexifont,
  :nanum_gothic_coding => NanumfontCoding,
  :arita => Arita,
  :daum => Daum,
  :nanumfonts => Nanumfonts,
  :jeollabukdo => Jeollabukdo,
  :naver_dic => NaverDic,
  :seoul_fonts => SeoulFonts,
  :auction_gothic => AuctionGothic,
  :mokpan => MokpanFonts,
  :yonsei_fonts => YonseiFonts,
  :yoondesign => YoondesignFonts,
  :asiafonts => AsiaFonts
}

HighLine.track_eof = false
SUPPORTED_FONTS.each do |key, value|
  puts
  installer = value.new
  case installer.copyright
  when :BSD
    puts "License: BSD"
  when :GPL
    puts "License: GPL"
  when :OFL
    puts "License: OFL"
  else
    puts "License"
    puts " URL: #{installer.copyright[:url]}"
    puts installer.copyright[:text]
  end
  prompter = HighLine.new

  answer = prompter.ask("Do you want to download #{key}?[y/n] ") {|q| q.validate =  /y|n/}
  if answer == 'y'
    if installer.class.include? LoginRequired
      id = prompter.ask("Enter your id for #{key}: ")
      pass = prompter.ask("Enter your password for #{key}: ") {|q| q.echo = '*'}
      installer.login id, pass
    end
    begin
      installer.download
      installer.extract
    rescue
      puts "There's some error: #{$!}"
    end
  end
end

puts "Gathering results..."

begin
Dir.mkdir "./fonts"
rescue Errno::EEXIST
end

begin
Dir.mkdir "./installer"
rescue Errno::EEXIST
end

Find.find(".") do |fn|
  Find.prune if fn =~ /^\.\/fonts|^\.\/installer/
  if fn =~ /\.ttf$|\.ttc$/i
    FileUtils.cp fn, "fonts/" + fn[/[^\/]*$/]
  elsif fn =~ /\.exe$|\.fdt$/i
    FileUtils.cp fn, "installer/" + fn[/[^\/]*$/]
  end
end

puts "Done!\nFont files are in 'fonts', Win32 EXE installers are in 'installer'.\nHappy shoveling;)"

