#!/usr/bin/env python
# -*- coding: utf-8 -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

import os, sys, string
from os import path
from sys import stdin, stdout, exit, argv
from string import join, strip, atoi
try: from random import choice
except: from whrandom import choice

from ulib.all import uprint

def quote_maybe(str, quote=True):
    if quote: str = "'%s'" % str.replace("'", "'\\''")
    return str

def run_urandomize():
    global argv

    if len(argv) == 2 and argv[1] in ('--help', ):
        progname = path.split(argv[0])[1]
        uprint(u"""%(progname)s -- Mélanger des lignes de façon aléatoire

    USAGE
        %(progname)s [-j | -J size]

    OPTIONS
        -j, -J size
            Fusionner les lignes pour en faire des lignes de taille maximum $size
            octets (920 par défaut. Utiliser -1 pour pas de limite.)
        -q  Mettre les valeurs entre quotes
    """ % vars())
        exit(0)

    DEFAULT_SIZE = 920
    size = None
    quote = False

    argv = argv[1:]
    while argv:
        if argv[0][:1] == '-':
            opt = argv[0][:2]
            if opt == '-j':
                size = DEFAULT_SIZE

            elif opt == '-J':
                if not argv[0][2:]:
                    if not argv[1:2]:
                        raise ValueError, "-J attend un argument"
                    else:
                        arg = argv[1]
                        argv = argv[1:]
                else:
                    arg = argv[0][2:]
                size = atoi(arg)

            elif opt == '-q':
                quote = True

            elif opt == '--':
                break

            else:
                raise ValueError, "Option invalide"
        else:
            break
        argv = argv[1:]

    if argv:
        # 'lignes' données en ligne de commande
        input = argv
    else:
        input = []
        while 1:
            line = stdin.readline()
            if not line: break
            while line[ - 1:] in ('\n', '\r'):
                line = line[: - 1]
            input.append(line)

    if size:
        # Il faut fusionner les lignes
        # On en profite pour les striper
        output = []
        line = ''
        while input:
            item = choice(input)
            input.remove(item)

            if line: line = line + ' '
            line = line + strip(quote_maybe(item, quote))

            if size != - 1 and len(line) >= size:
                output.append(line)
                line = ''
        if line:
            output.append(line)

    else:
        # On se contente de randomiser les lignes
        output = []
        while input:
            item = choice(input)
            input.remove(item)
            output.append(quote_maybe(item, quote))

    for item in output:
        stdout.write(item + '\n')

if __name__ == '__main__':
    run_urandomize()
