#!/usr/bin/env python

# This is a part of 'dailyscripts' bundle.
# 'flatten' gathers all files in underlying directories and moves them
# to topmost one.

# Copyright (C) 2010, Tomas Varaneckas 
# http://www.varaneckas.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 3 of the License, or
# (at your option) any later version.

import sys
import os

class Flatten(object):

    def main(self, argv):
        args = list(argv)
        if '--help' in args or '-h' in args:
            print 'Usage: flatten [path]'
            sys.exit(0)
    
        if len(args) > 1:
            self.path = argv[1]
        else:
            self.path = os.curdir
        target_dir = os.path.abspath(self.path)
        if not os.path.exists(target_dir):
            print 'Target directory does not exist: %s' % target_dir
            sys.exit(1)
        print 'Are you sure you want to flatten all files in %s?' % target_dir
        print ', '.join(os.listdir(target_dir))
        print 'Please confirm flatten operation [y/N]:'
        confirm = raw_input('> ')
        if confirm != 'y':
            sys.exit(0)
        print 'Flattening file hierarchy in %s' % target_dir
        self.process_dir(target_dir, target_dir, 10)
        print 'Done.'
    
    def process_dir(self, dir, top, depth):
        print 'Processing dir: %s' % dir
        for file in os.listdir(dir):
            old_file = dir + os.path.sep + file
            new_file = top + os.path.sep + file
            if os.path.isdir(old_file):
                if file.startswith('.'):
                    continue
                if depth > 0:
                    self.process_dir(old_file, top, depth - 1)
            else:
                if old_file == new_file:
                    continue
                while os.path.exists(new_file):
                    base, ext = os.path.splitext(new_file)
                    base = base + "_1"
                    new_file = top + os.path.sep + base + ext
                print 'Moving %s to %s' % (file, top)
                os.rename(old_file, new_file)
        if dir != top:
            print 'Removing %s' % dir
            os.removedirs(dir)

if __name__ == '__main__':
    program = Flatten()
    program.main(sys.argv)
