#!/usr/bin/python3
## -*- coding: utf-8 -*- vim:shiftwidth=4:expandtab:
##
## ifne: Run a command if the standard input is not empty
##       (a clone of moreutils ifne(1) command)
## Copyright (c) 2018 SATOH Fumiyasu @ OSSTech Corp., Japan
##               <https://www.OSSTech.co.jp/>
##
## License: GNU General Public License version 3
##

import os
import sys
import subprocess

def die(msg, rc=1):
    print(msg, file=sys.stderr, end='')
    sys.exit(rc)

## ======================================================================

in_f = sys.stdin.buffer
run_if_empty = False
io_size = 8192
cmd_usage = 'Usage: %s [-n] COMMAND [ARG ...]\n' % (sys.argv[0])

try:
    if sys.argv[1] == '-n':
        run_if_empty = True
        cmd_and_args = sys.argv[2:]
    else:
        cmd_and_args = sys.argv[1:]
except IndexError:
    die(cmd_usage)
if not cmd_and_args:
    die(cmd_usage)

in_data = in_f.read(io_size)
if in_data == b'' and not run_if_empty:
    ## No run if STDIN is empty
    sys.exit(0)

if in_data != b'' and run_if_empty:
    ## No run if STDIN is NOT empty
    proc = None
    out_f = sys.stdout.buffer
else:
    ## Run if STDIN is NOT empty
    ##  or
    ## Run if STDIN is empty
    proc = subprocess.Popen(cmd_and_args, stdin=subprocess.PIPE)
    out_f = proc.stdin

while in_data != b'':
    out_f.write(in_data)
    in_data = in_f.read(io_size)

if proc:
    proc.stdin.close()
    proc.wait()
    if proc.returncode >= 0:
        sys.exit(proc.returncode)
    else:
        os.kill(os.getpid(), -proc.returncode)

sys.exit(0)
