#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''****************************************************************************
**
** Copyright (C) 2008 Jedrzej Nowak <me@pigmej.eu>
** 
** This file may be used under the terms of the GNU General Public License
** version 2 as published by the Free Software Foundation and appearing in the
** file GPL.txt included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************'''

client_ver=0.96

#maxymalna wielkosc pliku w kilobajtach
#zmieniac tylko w uzasadnionych przypadkach
#dymyslnie 1MB = 1024 KB
max_file_size=1024.0

import xmlrpclib,sys
from optparse import OptionParser
from os.path import getsize,split as split_dir
from urllib import unquote_plus
from base64 import b64decode


err=sys.stderr

usage = u"uzywac: %prog [options]\nWiecej informacji: http://wklej.to/klienty"

# opcje parsera
parser = OptionParser(usage)
parser.add_option('-c','--create',action="store_true",dest="create",default=False,help=u'Do tworzenia paste')
parser.add_option('-g','--get',action="store_true",dest="get",default=False,help=u'Do pobierania paste')
parser.add_option('-r','--remove',action="store_true",dest="remove",default=False,help=u'Do usuniecia paste')
parser.add_option('-f','--file',dest='file',default='',help=u'Nazwa pliku, wymagany parametr przy okreslaniu kolorowania wg typu plik')
parser.add_option('-t','--type',dest='type',default='',help=u'Okresla typ kolorowania,lub typ wyjscia w zaleznosci od podjetej akcji')
parser.add_option('--types',dest='types',action="store_true",default=False,help=u'Pobiera dostepne typy kolorowania')
parser.add_option('-p','--password',dest='password',default='',help=u'Ustawia haslo na usuniecie paste')
parser.add_option('-u','--uid',dest='uid',default='',help="Okresla uid paste do pobrania, mozna podac caly url")
parser.add_option('-i','--input',dest='input_file',default=False,help="Sciezka do pliku do wklejenia")
parser.add_option('-e','--escaped',action="store_true",dest='escaped',default=False,help="Konieczne do podania jesli wejscie jest w formacie rfc2396 ( uri ) format z plusem dla spacji")
parser.add_option('-v','--ver',action="store_true",dest='ver',default=False,help="Pobiera wersje serwera, wyswietla wersje klienta")
parser.add_option('-H','--hash','--HASH',dest='hash',default='',help=u'Umozliwia podanie hasha dla paste')
parser.add_option('--force',action="store_true",dest='force',default=False,help="Omija sprawdzenie wersji klienta, uzywac w ostatecznosci")

def get_uid(source):
    """
    funkcja pobierajaca uid paste
    """
    try:
        uid=source[source.rindex('/')+1:]
    except ValueError:
        uid=source
    return uid


def client():
    """
    wlasciwa czesc klienta
    """
    (opt,args)=parser.parse_args() # parsowanie wejscia
    srv = xmlrpclib.ServerProxy("https://wklej.to:8008") # polaczenie z serwerem
    if opt.force:
        ver=0
    else:
        ver=client_ver
    if opt.create:
        # jesli okreslono plik wejscia
        if opt.input_file:
            try:
                f=open(opt.input_file,'r')
            except:
                err.write('Plik nie zostal odnaleziony\n')
                sys.exit(1)
            else:
                if (getsize(opt.input_file)/1024.0)>max_file_size:
                    err.write('Plik jest zbyt duzy ( %0.1f KB), limit to %0.1f KB'%((getsize(opt.input_file)/1024.0),max_file_size))
                    sys.exit(1)
                else:
                    content=f.read()
                    f.close()
                    if not opt.type:
                        opt.file=split_dir(opt.input_file)[::-1][0]
        else:
            if args:
                content=' '.join(args)
            else:
                err.write('Nalezy podac zawartosc\n')
                sys.exit(1)
        # jesli wejscie jest w postaci zgodnej z rfc2396
        if opt.escaped:
            content=unquote_plus(content)
        #na unicod jesli sie uda
        try:
            content=unicode(content)
        except:
            None
        # wyslanie polecenia do serwera
        out = srv.create_paste(opt.type,content,opt.password,opt.file,opt.hash,ver)
    elif opt.ver:
        out = srv.server_ver()
        #dla zachowania zgodnosci
        if out[0]!=0:
            out = 1,'Wersja serwera: %s\nWersja klienta: %s'%(out[1],ver)
    elif opt.get:
        if not opt.uid:
            err.write('Nalezy okreslic uid paste\n')
            sys.exit(1)
        if not opt.type:
            opt.type='text'
        out = srv.get_paste(get_uid(opt.uid),opt.type,opt.hash,ver)
        if opt.type=='pdf' and out[0]==1:
            out=1,b64decode(out[1])
    elif opt.remove:
        if not opt.uid:
            err.write('Nalezy podac uid paste')
            sys.exit(1)
        out = srv.remove_paste(get_uid(opt.uid),opt.password,ver)
    elif opt.types:
        out = srv.types()
    else:
        err.write("Okresl rodzaj akcji, -h/--help dla pomocy\n")
        sys.exit(1)
    if out[0]==0:
        err.write(out[1].encode('utf-8'))
        sys.exit(1)
    if opt.type=='pdf':
        print out[1]
    else:
        print out[1].encode('utf-8')
    
    
    
if __name__=="__main__":
    client()
