#!/usr/bin/python
'''
    # DESCRIPTION:
    # tool to sync Entropy packages directory with a Gentoo binhost compatible one
    # THIS TOOL: must be used server-side as a cron job

    Copyright (C) 2007 Fabio Erculiani

    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
'''

# FIXME: must be optimized a lot
# FIXME: we need to keep Python 2.3 compatibility

import os

etpPackagesDir = "/home/linuxsabayon/sabayon.org/packages"
gentooPackagesDirs = "/home/linuxsabayon/sabayon.org/binhost"

# if the Gentoo binhost dirs don't exist, create them
archs = os.listdir(etpPackagesDir)
for arch in archs:
    if not os.path.isdir(gentooPackagesDirs+"/"+arch):
        os.makedirs(gentooPackagesDirs+"/"+arch)


# sync directories
for arch in archs:
    
    print "Architecture: "+arch
    
    # get the dir content
    dircontent = os.listdir(etpPackagesDir+"/"+arch)
    
    # filter only .tbz2
    _dircontent = []
    for file in dircontent:
	if file.endswith(".tbz2"):
	    _dircontent.append(file)
    dircontent = _dircontent

    # clean the current content of the gentooPackagesDirs+"/"+arch
    tbremoved = os.listdir(gentooPackagesDirs+"/"+arch)
    for file in tbremoved:
	try:
	    os.remove(gentooPackagesDirs+"/"+arch+"/"+file)
	except:
	    pass

    # move packages files
    for file in dircontent:
	if (not file.endswith("-unstable.tbz2")) and (not file.endswith("-stable.tbz2")):
	    print "<> Copying file "+file
	    os.system("ln -sf "+etpPackagesDir+"/"+arch+"/"+file+" "+gentooPackagesDirs+"/"+arch+"/")
	elif file.endswith("-unstable.tbz2"):
	    # look if there's the same package tagged as stable
	    newfilename = file.split("-unstable.tbz2")[0]+".tbz2"
	    print "<> Copying file "+file
	    os.system("ln -sf "+etpPackagesDir+"/"+arch+"/"+file+" "+gentooPackagesDirs+"/"+arch+"/"+newfilename)
	elif file.endswith("-stable.tbz2"):
	    unstablefilename = file.split("-stable.tbz2")[0]+"-unstable.tbz2"
	    if os.path.isfile(etpPackagesDir+"/"+arch+"/"+unstablefilename):
		# do not copy over, there's an unstable version
		continue
	    # look if there's the same package tagged as stable
	    newfilename = file.split("-stable.tbz2")[0]+".tbz2"
	    print "<> Copying file "+file
	    os.system("ln -sf "+etpPackagesDir+"/"+arch+"/"+file+" "+gentooPackagesDirs+"/"+arch+"/"+newfilename)
	    