#!/usr/bin/env python3

import os
import argparse


def qute(cmd):
    with open(os.environ['QUTE_FIFO'], 'w') as fifo:
        fifo.write(cmd)
        fifo.write('\n')
        fifo.flush()

def error(msg):
    print(msg, file=sys.stderr)
    qute('message-error "{}"'.format(msg))

def parse_args():
    parser = argparse.ArgumentParser(description="Clear URL and yank to clipboard")
    parser.add_argument('--selection', '-s', action='store_true',
                        help='Yank to selection')
    return parser.parse_args()


if __name__ == '__main__':
    if 'QUTE_FIFO' not in os.environ:
        print(f"No QUTE_FIFO found - {sys.argv[0]} must be run as a qutebrowser userscript")
        sys.exit(-1)

    try:
        args = parse_args()

        url = os.environ['QUTE_URL']

        try:
            import unalix
            url = unalix.clear_url(url)
        except:
            pass

        if args.selection:
            qute('yank inline "{}" -s'.format(url))
        else:
            qute('yank inline "{}"'.format(url))

    except Exception as e:
        error(str(e))