#!/usr/bin/ruby
#
# splitmime - MIME multipart splitter
#
# License: GPL2
# Author: Tatsuki Sugiura <sugi@nemui.org>
#

$VERSION  = 0.2
$SELFNAME = File.basename($0)

require 'getoptlong'
require 'nkf'
require 'tmail'

def version
  puts "#{$SELFNAME} version #{$VERSION}."
end

def usage
  STDERR.print <<EOU
#{$0} [-lph] [file]
Options:
-h,  --help            print this message
-V,  --version         print version number
-l,  --list            list each part
-p,  --part            print specific part (default=0)
EOU
#2345678901234567890123456789012345678901234567890123456789012345678901234567890
end

def list(tmail, nest=[])
  tmail.parts.each_with_index do |part, idx|
    info = Array.new

    info.push(part.charset) if part.charset
    info.push(part.encoding) if part.encoding
    if part["Content-Type"].to_s =~ /name=(\S+)/
      info.push(NKF.nkf('-me', $1))
    end
    print nest.join("."), "." if nest.length != 0
    print idx, ": ", part.main_type, "/", part.sub_type
    print " (" + info.join("; ") + ")" if info.length != 0
    print "\n"

    if part.multipart?
      next_nest = nest.clone;
      next_nest.push(idx)
      list(part, next_nest)
    end
  end
end

def getpart(tmail, index)
  if tmail.parts.length <= index[0].to_i
    STDERR.puts "#{$0}: Part number exceeded. Abort!"
    return false
  end
  if index.length > 1
    getpart(tmail.parts[index[0].to_i], index[1, index.length-1])
  else
    tmail.parts[index[0].to_i]
  end
end


### main ###

getopt = GetoptLong.new
getopt.set_options(
		   ['--help', '-h',	GetoptLong::NO_ARGUMENT],
		   ['--version', '-V',	GetoptLong::NO_ARGUMENT],
		   ['--list', '-l',	GetoptLong::NO_ARGUMENT],
		   ['--with-header', '-H', GetoptLong::NO_ARGUMENT],
		   ['--part', '-p',	GetoptLong::REQUIRED_ARGUMENT]
		)
opt = Hash.new
begin
  getopt.each_option do |name, arg|
    eval "opt['#{name.sub(/^--/, '').gsub(/-/, '_')}'] = '#{arg}'"
  end
rescue
  usage
  exit 1
end

if opt["help"] || opt["version"]
  opt["help"]    and usage
  opt["version"] and version
  exit 0
end

begin
  tmail = TMail::Mail.parse(ARGF.read)
rescue
  STDERR.puts "#{$0}: Parse Error. Abort!"
  exit 1
end

unless tmail.multipart?
  tmail.parts[0] = tmail
end

if opt["list"]
  list(tmail)
else
  partno = opt["part"] || 0
  part   = getpart(tmail, partno.to_s.split(".")) or exit 1
  if opt["with_header"]
    #print part.each_header{|h, v| puts "#{h.to_s}: #{v}" }
    #print part.encoded
  end
  print part.preamble
end
