#!/usr/bin/ruby

# xpkg-install: Package installer for X/Qt project
#
# Copyright (C) 2003-2005 Takuya Murakami
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

$debug = false

$pkglibdir = "/usr/lib/xpkg"
$sysconfdir = "/etc/xpkg"
$version = "1.0.0"

$xpkgtop = nil
$verbose = false

# Ŀեɤ߹
inifile = ENV["HOME"] + "/.xpkg"
if FileTest.exist?(inifile)
    load "~/.xpkg"
end

$LOAD_PATH.push($pkglibdir)
$LOAD_PATH.push($sysconfdir)

# եɤ߹
require "config"

# ٸĿեɤ߹
# (եꤳͥ褹뤿)
if FileTest.exist?(inifile)
    load "~/.xpkg"
end

require "optparse"
require "pkg"
require "install"
require "pkgbuild"
require "ipkg"
require "misc"


class XpkgInstall
    include Misc
    include ExecScript

    # ե륤󥹥ȡ
    def Install(file)
	installer = PkgInstall.new
	installer.SetParamFromDef(@df)

	installer.InstallFileAuto(file)
    end

    # update
    def Update
	installer = PkgInstall.new
	installer.SetParamFromDef(@df)

	p = Packages.new(@pkgdir)
	p.FetchIndex()
	p.LoadIndex()
	p.UpdatePackages(installer)
    end

    # ᥤ
    def main
	# ν
	target, command, files = parse_opt()

	# ǥ쥯ȥ
	setupdirs(target)

	# feed URL ν񤭴
	$feed_url.gsub!(/@target@/, target)


	# եΥ
	pkg = Pkg.new
	pkg.loaddef(nil, target, "", $sysconfdir)

	@df = pkg.df

	# ʬ
	case command
	when "install"
	    files.each do |file|
		Install(file)
	    end

	when "update"
	    Update()

	# not yet...

	else
	    STDERR.puts "Unknown command: #{command}"
	    exit 1
	end
    end

    # ץν
    def parse_opt
	target = ENV["TARGET"]
	if (target == nil || target == "")
	    target = $default_target  # default value
	end

	opt = OptionParser.new
        opt.banner = "xpkg-install version #{$version}\n" +
                 "Copyright (C) 2003-2005 X/Qt Project\n" + 
                 "This program may be freely redistributed under the terms of the GNU GPL\n\n" + 
                 "Usage: xpkg-install [command] [package files...]"
	opt.on_head(" command: install update")

	opt.on("-h", "--help", "Show this message") { puts opt; exit 1; }
	opt.on("-t", "--target=TARGET", String, "Specify target") {|v| target = v }
	opt.on("-v", "--verbose", "Verbose") {$verbose = true}

	opt.parse!(ARGV)
	
	if (ARGV.size < 2)
	    puts opt
	    exit 1
	end

	command = ARGV.shift

	return target, command, ARGV
    end
end

xpkginstall = XpkgInstall.new
xpkginstall.main
