#!/usr/bin/env python2

import argparse
import json
import os
import urllib2
import urllib
import sys

from subprocess import Popen, PIPE


def get_ext(path):
    name, ext = os.path.splitext(path)
    return ext

def save_in_clipboard(string):
    # credits to github.com/Raynes/rapture
    if sys.platform == 'darwin':
        cmd = 'pbcopy'
    elif 'linux' in sys.platform:
        cmd = 'xclip -selection clipboard'
    else:
        raise NotImplementedError("Platform not supported.")

    p = Popen([cmd], stdin=PIPE)
    p.communicate(input=string)

def sanity_check(args):
    if args.username and not args.token:
        print "Token not provided (--token)."
        sys.exit(1)

def main():
    parser = argparse.ArgumentParser(description="Paste some stuff.")
    parser.add_argument('path',
                        nargs='?', default=None,
                        help="Path for file to paste.")
    parser.add_argument('--language', '-l',
                        dest='language', default=None,
                        help="Language for syntax highlighting. You can omit \
                              this and will try to infer from the file ext.")
    parser.add_argument('--private', '-p',
                        dest='private', default=False,
                        help="Whether to make the paste private")
    parser.add_argument('--no-clipboard', '-n', action='store_true',
                        dest='no_clipboard', default=False,
                        help="If you don't want the URL in the clipboard")
    parser.add_argument('--username', '-u',
                        dest='username', default=None,
                        help="Username to associate paste with. Needs token!")
    parser.add_argument('--token', '-t',
                        dest='token', default=None,
                        help="Token to verify username")

    args = parser.parse_args()
    sanity_check(args)

    data = {}
    data['private'] = args.private

    if args.username:
        data['username'] = args.username
        data['token'] = args.token

    if args.path:
        with open(args.path, 'r') as f:
            data['contents'] = f.read()
        data['language'] = args.language if args.language else get_ext(args.path)
    else:
        data['contents'] = sys.stdin.read()
        data['language'] = args.language if args.language else 'Plain Text'

    req = None
    try:
        req = urllib2.urlopen("https://www.refheap.com/api/paste",
                              data=urllib.urlencode(data))
    except urllib2.HTTPError:
        print "Bad request. Wrong user & token, maybe?"
        sys.exit(1)

    response = json.loads(req.read())
    url = response['url']

    if args.no_clipboard:
        print "Pasted at %s." % url
    else:
        try:
            save_in_clipboard(url)
        except NotImplementedError:
            print "Don't know how to save to clipboard on your platform."
            print "Pasted at %s." % url
        else:
            print "Saved %s in your clipboard." % url


if __name__ == '__main__':
    main()

@@ -132,16 +132,107 @@
 , PIPE%0A%0A
+CONFIG_FILE = '.refpaste'%0ACONFIG_PATH = os.path.join(os.path.expanduser('~'), CONFIG_FILE)%0A
 %0Adef get
@@ -775,16 +775,460 @@
 xit(1)%0A%0A
+def extract_creds():%0A    #try:%0A    with open(CONFIG_PATH, 'r') as f:%0A        userdata = json.load(f)%0A        if 'username' not in userdata and 'token' not in userdata:%0A            print %22Need both username and token %5C%0A                   in config file, ignoring it.%22%0A            return None%0A        return userdata%0A    #except OSError:%0A        #pass%0A    #except ValueError:%0A        #print %22Malformed config file, ignoring it.%22%0A    return None%0A%0A
 def main
@@ -2496,16 +2496,95 @@
 rivate%0A%0A
+    userdata = extract_creds()%0A    if userdata:%0A        data.update(userdata)%0A%0A
     if a

add support for rc file