#!/usr/bin/env python
#
################################################################################
#  Copyright (C) 2010
#  
#  Douglas Schilling Landgraf <dougsland@redhat.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, version 2 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.

import sys
import commands

# TODO: 
# 	- use options like -v (version), -c (changelog) -k (kernel)
#	- -f (from version) -t (to version) -u (untar)
#
#	- use md5 to check if the kernel was already downloaded and avoid download again
#
#	- avoid download kernel already downloaded
def main():

	downloader = "wget"
	url_kernel = "http://www.kernel.org/pub/linux/kernel/v2.6/"
	kernel_min_version = 18

	while True:
		# Downloading ChangeLog
		cmd = downloader + " " + url_kernel + "ChangeLog-2.6." + str(kernel_min_version)

		print "Executing " + str(cmd)
		ret = commands.getstatusoutput(cmd)
		if ret[0] != 0:
			print "There is no changelog/kernel for release 2.6." + str(kernel_min_version)
			sys.exit(0)

		# Downloading kernel
		cmd = downloader + " " + url_kernel + "linux-2.6." + str(kernel_min_version) + ".tar.bz2"
		print "Executing " + str(cmd)
		ret = commands.getstatusoutput(cmd)
		if ret[0] != 0:
			print "Error downloading the source code, please try again."
			sys.exit(0)

		# untar 
		cmd = "tar jxvf " + "linux-2.6." + str(kernel_min_version) + ".tar.bz2"
		print "Executing " + str(cmd)
		ret = commands.getstatusoutput(cmd)
		if ret[0] != 0:
			print "Error executing tar jxvf in source code."
			sys.exit(0)

		kernel_min_version = kernel_min_version + 1
main()

