#!/usr/bin/env python

# This is a part of 'dailyscripts' bundle.
# 'shuffle' restructures files in a foder by giving them a 
# prefix with random sequence number, so file order changes. 
# If prefix already exists, it's changed.

# Why the hell someone would need a program like that?
# The answer is simple. There are certain car audio players
# which lack 'shuffle' or 'random' playback feature. I constantly 
# get bored by the sequence of songs that I have on my USB
# so I want them to get shuffled by having a different random 
# prefix from time to time. 

# 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 os
import sys
import random
import re

class Shuffle(object):

    def main(self, argv):
        args = list(argv)
        if '--help' in args or '-h' in args:
            print 'Usage: shuffle [path]'
            sys.exit(0)

        if len(argv) > 1:
            self.path = argv[1]
        else:   
            self.path = os.curdir
        rand = random.Random()
        rand.seed()
        target_dir = os.path.abspath(self.path)
        files_and_dirs = os.listdir(self.path)
        files = list()
        for file in files_and_dirs:
            if os.path.isfile(target_dir + os.path.sep + file) and not file.startswith('.'):
                files.append(file)
        print 'Are you sure you want to add random prefixes to following files?'
        print ', '.join(files)
        print 'Please confirm random prefix addition [y/N]:'
        confirm = raw_input('> ')
        if confirm != 'y':
            sys.exit(0)
        prefixes = range(0, len(files))
        random.shuffle(prefixes, random.random)
        for file in files:
            pref = '%s-' % prefixes.pop()
            if re.match('^[0-9]+\-.*', file):
                new_file = re.sub('^[0-9]+\-', pref, file)
            else:
                new_file = pref + file
            print 'Renaming %s to %s' % (file, new_file)
            os.rename(target_dir + os.path.sep + file, target_dir + os.path.sep + new_file)
        print 'Done!'

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