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


""" Use in i3wm with:
Save as screeshot.py somewhere into your PATH
bindsym --release Print exec --no-startup-id screenshot.py [-s|-u]
"""


import sys
import os
from subprocess import Popen, PIPE
from tempfile import NamedTemporaryFile


SCREENSHOT_UTILITY = '/usr/bin/scrot' # /usr/bin/import


def feed_xclipboard(bytes_screenshot):
    pipe = Popen("xclip -sel clip", shell=True, stdin=PIPE).stdin
    pipe.write(bytes_screenshot)
    pipe.close()


def import_screenshot(opt):
    filename = NamedTemporaryFile(
        suffix='.png',
        prefix='screenshot_',
        dir = os.path.expanduser('~/Dropbox/screenshots'),
        delete=True).name
    p = Popen(SCREENSHOT_UTILITY + " " + opt + " " + filename, shell=True)
    sts = os.waitpid(p.pid, 0)[1]
    return filename


if __name__ == '__main__':
    if len(sys.argv) > 1:
        screenshot = import_screenshot(sys.argv[1])
    else:
        screenshot = import_screenshot(" ")
    bytes_screenshot = bytes(screenshot, encoding='utf-8')
    feed_xclipboard(bytes_screenshot)


