#!/usr/bin/env python3

"""
The MIT License (MIT)
Copyright (c) 2020 aiotter
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

import sys
import shutil
from subprocess import Popen, PIPE
from contextlib import contextmanager, ExitStack

CHUNK_SIZE = 1048576


@contextmanager
def open_clipboard(mode='r', text=True):
    if mode == 'r':
        if shutil.which('pbpaste'):
            with Popen('pbpaste', stdout=PIPE, text=text) as proc:
                yield proc.stdout

        elif shutil.which('xsel'):
            with Popen(['xsel', '--clipboard', '--output'],
                       stdout=PIPE, text=text) as proc:
                yield proc.stdout

        elif shutil.which('xclip'):
            with Popen(['xclip', '-selection', 'c', '-o'],
                       stdout=PIPE, text=text) as proc:
                yield proc.stdout

        else:
            raise FileNotFoundError('Either pbpaste or xsel is needed')

    elif mode == 'w':
        if shutil.which('pbcopy'):
            with Popen('pbcopy', stdin=PIPE, text=text) as proc:
                yield proc.stdin

        elif shutil.which('xsel'):
            with Popen(['xsel', '--clipboard', '--input'],
                       stdin=PIPE, text=text) as proc:
                yield proc.stdin

        elif shutil.which('xclip'):
            with Popen(['xclip', '-selection', 'c'],
                       stdin=PIPE, text=text) as proc:
                yield proc.stdin

        else:
            raise FileNotFoundError('Either pbcopy, xsel or xclip is needed')

    else:
        raise ValueError("mode argument must be either 'r' or 'w'")


def _read_by(chunk_size, file):
    while True:
        chunk = file.read(chunk_size)
        if not chunk:
            break
        yield chunk


def main():
    with ExitStack() as stack:
        clip_r = stack.enter_context(open_clipboard('r', text=False))
        clip_w = stack.enter_context(open_clipboard('w', text=False))

        input = clip_r if sys.stdin.isatty() else sys.stdin.buffer

        for chunk in _read_by(CHUNK_SIZE, input):
            if sys.stdin.isatty() or not sys.stdout.isatty():
                sys.stdout.buffer.write(chunk)
            clip_w.write(chunk)


if __name__ == '__main__':
    main()
