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

'''****************************************************************************
**
** Copyright (C) 2008 Jędrzej 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.
**
****************************************************************************'''

#nautilus script
#wymaga klienta textowego
#instalacja
#mv wklej_to_nautilus_get.py ~/.gnome2/nautilus-scripts/Wklej.to_pobierz
#chmod +x ~/.gnome2/nautilus-scripts/Wklej.to_pobierz


import os,sys
from subprocess import Popen, PIPE,call


plik=os.environ.get("NAUTILUS_SCRIPT_SELECTED_FILE_PATHS")
if not plik:
    call("notify-send -t 5000 -u critical 'Wklej.to: Błąd' 'Wymagane jest podanie pliku'",shell=True)
    sys.exit(1)
else:
    # skopiowane
    uid=Popen('xsel -b',shell=True,stdout = PIPE,stderr = PIPE,close_fds=True)
    if not uid.poll():
        uid=uid.stdout.read()
    else:
        # zaznaczenie
        uid=Popen('xsel -p',shell=True,stdout = PIPE,stderr = PIPE,close_fds=True).wait()
        if not uid.poll():
            uid=uid.stdout.read()
        else:
            Popen("notify-send -t 5000 -u critical 'Wklej.to: Błąd' 'Błąd obsługi schowka'",shell=True)
            sys.exit(1)
    out=Popen('wklej_to -g -u %s -t text'%uid,shell=True,stdout = PIPE,stderr = PIPE,close_fds=True)
    wy,err=out.communicate()
    if err:
        call("notify-send -t 5000 -u critical 'Wklej.to: Błąd' '%s'"%err,shell=True)
        sys.exit(1)
    call("notify-send -i ~/.wklej_to/icons/notify.png -t 5000 'Wykonano' 'W wybranym pliku: %s\nznajduje się zawartość paste: %s.'"%(plik,uid),shell=True)
    f=open(plik,'w')
    f.write(wy)
    f.close()
    sys.exit(0)
