#!/usr/bin/env python

"""
Little Python script to aid the deb build process. This script can build one
defined project or build all the projects. I have write this little script to
automate the debian build of my differents applications.

This script is still under development, so still need to work on this
script. There are some little bug that need to be are fixed but the script 
already works right like expected.

On the server side, we make an script to automatically build the packages list.
Create an file in /sbin/mkPackagesList with the following content:

#<COPY_BELOW>
# Generating the Package and Package.gz files for the own deb files.
echo "Generating the packages list file ..."
#
dpkg-scanpackages . /dev/null > /var/www/debs/dists/custom/main/binary-i386/Packages && gzip -9c /var/www/debs/dists/custom/main/binary-i386/Packages > /var/www/debs/dists/custom/main/binary-i386/Packages.gz
# Removing the non-compressed Packages file
rm /var/www/debs/dists/custom/main/binary-i386/Packages

echo "Done ..."
#<END_LINE_ABOVE>
"""

"""
TODO:
- Fixing bug when we build an specifiq package. We need to see again the list
  of package after we have build an specifiq package.
- Add an way so that we can work with an config file. These config file should
  be saved in the home directory and maybe one in the '/etc/...' for an global
  configuration. The config file that are in the home dire override the global
  configurations.
- Add an way that the script stop or pause when one of the packages fails to
  build. So that we know about it. Like actually the build process goes to fast
  and we not see the errors.
"""

__app_name__ = 'py_deb_package_builder'
__author__ = 'David Van Mosselbeen'
__version__ = '0.0.2'
__email__ = "david.van.mosselbeen@telenet.be"
__copyright__ = "2006"
__license__ = "GNU GPL version 2"

# The whole path of the directories to proceed
pathOfPackages = '/home/david/sources/own_packages/'
#pathOfPackages = '/mnt/shfs/sources/own_packages/'

# The directories to exclude
excludeDirs = ['docs', 'fgfs_scenery_downloader', 'pycpu_scaler', 'openttd_full']

import os, sys

def printVersion():
    """Print the version of the program and exit."""
    print "%s: %s   %s" % (__app_name__, __version__, __license__)
    sys.exit()

def printHelp():
    """Print the help of the program and exit."""
    print """
IMPORTANT:
    We need to define the path of the dir containing the packages we want to build.

Usage: %s [options]

[options]
-h     --help
          : Show summary of options and exit.
-v     --version
          : Show version of program and exit.
-s     --show
          : Show the packages we can build and exit.

* Below not yet implemented (still in dev).

-p s   --path s
          : Path containing the packages to build.
-a     --all
          : Build all packages
-b s   --build string
          : Build s package. Where s is the name of the dir to package.
""" % (__app_name__)
    sys.exit()

# We need to get the path of where the script is run. So that we easy
# can go back to that path. Like in the script, we change many times the
# path.

def getListing():
    """Get the directory listing an return only the directories names."""

    # The directories to proceed.
    # Maybe is there an need to automatically get the listing of the directory??
    # Actually not yet working!
    
    files = os.listdir(pathOfPackages)
    items = []
    for item in files:
        if item not in excludeDirs:
            if os.path.isdir(item):
                # Append the item to the dir list
                items.append(item)
    """
    # Oldway, and whe need to statically define the packages we want
    items = ['fluxbox_extra_themes' , 'pystaticgallery', 'pytk_dict', \
            'pytk_diskfree', 'pytk_universal_money_converter', 'pytk_uprecords', \
            'xmms_extra_themes']
    """
    return items

def buildPackage(path):
    """Build the deb package."""
    # Go in the directory of the package
    os.chdir(path)
    # Make the deb package
    os.system("debuild -us -uc -b")

def buildSpecifiqPackage():
    """Build an specific package of the directory."""
    pass

def buildAllPackages():
    """Build all the packages in the differents directories."""
    dirs = getListing()
    nbritems = len(dirs)
    counter = 0 
    dirs = getListing()
    # For each directory there are make an deb package for it
    for item in dirs:
        print "#"*72 # Just for the layout
        print "Processing: %s (%d/%d):" % (item, counter+1, nbritems)
        print "#"*72
        buildPackage(pathOfPackages+dirs[counter]+'/')
        counter = counter + 1
 
def main():
    """The main function of the application."""

    # Ask if we want to build all the packages of build an specific one
    todo = raw_input("Want to build all(A) the packages? Or want to build an specific(S)? Quit(Q): ")

    while todo != 'Q' or todo != 'q':
        # Build only an specific package
        if todo == 'S' or todo == 's':
            # Print first the list of packages with the reference number
            cnt = 0
            dirs = getListing()
            for item in dirs:
                print cnt, item
                cnt = cnt + 1

            choice = input("Which package want you to package? Enter the reference number (Q to quit): ")
            while choice != 'Q' or choice != 'q':
                buildPackage(pathOfPackages+dirs[choice]+"/")

                choice = raw_input("Which package want you to package? Enter the reference number (Q to quit): ")

            # Ask if we want to build all the packages of build an specific one
            #todo = raw_input("Want to build all(A) the packages? Or want to build an specific(S)? Quit(Q): ")

        # Build all the packages
        elif todo == 'A' or todo == 'a':
            buildAllPackages()
            # Ask if we want to build all the packages of build an specific one
            todo = raw_input("Want to build all(A) the packages? Or want to build an specific(S)? Quit(Q): ")

        elif todo == 'Q' or todo == 'q':
            # Asked to quit
            sys.exit()

        else:
            print "You have enter an bad choice!"
            # Ask if we want to build all the packages of build an specific one
            todo = raw_input("Want to build all(A) the packages? Or want to build an specific(S)? Quit(Q): ")

if __name__ == '__main__':
    # Check if there are some arguments provided when launch the app.
    i = 1 # argv counter var
    while i < len(sys.argv):
        arg = sys.argv[i]
        if arg == '-v' or arg == '--version':
            printVersion()
            sys.exit()
        if arg == '-h' or arg == '--help':
            printHelp()
            sys.exit()
        if arg == '-s' or arg == '--show':
            packages = getListing()
            for item in packages:
                print item,
            sys.exit()
        if arg == '-a' or arg == '--all':
            buildAllPackages()
            sys.exit()

    # Run the main app
    main()

