# encoding: utf-8
# api: fpm
# title: pip/python package
# description: Generates a setup.py for packaging Python modules
# version: 0.1
#
# Just generates a bland "setup.py" for all files assembled per
# input modules.
#
# Counterpart to `-s python` module. Will probably be merged later.
#

require "erb"
#require "backports" # gem backports
require "fpm/package"
#require "fpm/package/dir"
require "fpm/util"
#require "fileutils"
require "json"


# Output only
class FPM::Package::Pip < FPM::Package

  # Run bdist_wheel
  def output(output_path)
    output_check(output_path)
    pipfn = File.absolute_path(output_path)
    
    # Let setuptools/wheel build it
    ::Dir::chdir(staging_path) do
      basedir()
      stubs()
      attrs()
      setup_py()
      edit_file("setup.py") if attributes[:edit?]
      safesystem("python", "setup.py", "bdist_wheel", "-d", build_path)
    end
    
    # Find and move output package
    files = ::Dir.glob(build_path+"/*.whl")
    if files.length() != 1
      logger.error("More than one output file!", files)
    else
      safesystem("mv", files[0], ".")
      logger.warn("Output filename", {:files => File.basename(files[0])})
    end
  end # def output

  # Make package basedir if none exists
  def basedir()
    if not File.exists?(name)
      safesystem("mkdir", name)
      `mv * #{name}`
    end
  end

  # split some attributes
  def attrs()
    if maintainer =~ /<?(\S+?@\S+(?<!>))>?/
      @author_email = $1
    else
      @author_email = 'nobody@example.org'
    end
    @author = maintainer.sub(/\s*\S+@\S+/, '')
    if not @author.length()
      @author = @author_email.sub(/@.+/, "")
    end
  end

  # setup_py
  def setup_py()
    if not File.exists?("setup.py")
      File.open("setup.py", "w") do |f|
        f.write template("pip.erb").result(binding)
      end
    end
    if not File.exists?("setup.cfg")
      File.open("setup.cfg", "w") do |f|
        f.write "[bdist_wheel]\nuniversal=1\n"
      end
    end
  end

  # empty files
  def stubs()
    for fn in ["README.rst", "README.txt", "MANIFEST.in", "setup.cfg", name+"/__init__.py"]
      if not File.exists?(fn)
        File.open(fn, "w") do |f|
          f.write ""
        end
      end
    end
  end

end # class FPM::Package::Pip
