#!/usr/bin/env ruby
#--
# Copyright (C) 2008 Harald Sitter <apachelogger@ubuntu.com>
#
# 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) version 3 or any later version
# accepted by the membership of KDE e.V. (or its successor approved
# by the membership of KDE e.V.), which shall act as a proxy
# defined in Section 14 of version 3 of the license.
#
# 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, see <http://www.gnu.org/licenses/>.
#--

require 'fileutils'
include FileUtils

def pt(s)
    puts(".!!!~~~~>Bat getorig: #{s}")
end

def dir_revive(dir,enter=false)
    FileUtils.rm_rf(dir)
    Dir.mkdir(dir)
    Dir.chdir(dir) if enter
end

file = "#{ENV['HOME']}/.batgetorigrc"
unless File.exist?(file)
    pt("#{file} not found :-(")
    exit 1
end

KDEVER          = IO.readlines(file)[0].chomp
JOINEDVER       = IO.readlines(file)[0].chomp.gsub!(".","")
RDIR            = IO.readlines(file)[1].chomp
BDIR            = "#{IO.readlines(file)[2].chomp}/.kd#{JOINEDVER}"
dir             = "tarballs"

if $*[0] != nil
    puts("batgetorig [ package | extragear | extragear/package ]")
elsif $*[0] == ("extragear")
    pkg = "extragear/"
elsif $*[0]
    pkg = $*[0]
else
    pkg = ""
end

if pkg.include?("extragear")
    dir = "tarballs/extragear"
end

pt("entering #{BDIR}")
Dir.chdir(BDIR)
if pkg == "" or pkg.split("/").join == "extragear" #extragear/package will fail
    pt("remove, recreate and enter #{dir}")
else
    Dir.chdir(dir)
end

pt("running scp #{RDIR}/#{KDEVER}/src/#{pkg}*bz2 .")
%x[scp #{RDIR}/#{KDEVER}/src/#{pkg}*bz2 .]

pt("bunzipping")
%x[bunzip2 *bz2]

pt("gzipping")
%x[gzip -9fn *tar]

pt("renaming")
Dir.foreach(".") {|f|
    next if f == '.' or f == '..' or not f.include?(".tar.gz") or f.include?(".orig.tar.")

    case f
    when /kdelibs-([\d\.]+)/ then
        n = "kde4libs"
    when /kdewebdev-([\d\.]+)/ then
        n = "kdewebdev-kde4"
    else
        n = f.split("-")[0..-2].join("-")
    end
    v = f.split("-")[-1].split(".tar.gz")[0]

    mv(f, "#{n}_#{v}.orig.tar.gz")
}
