#!/bin/bash

# from: https://gist.github.com/RichardBronosky/56d8f614fab2bacdd8b048fb58d0c0c7

LINUX_copy() {
    cat | xclip -selection clipboard
}

LINUX_paste() {
    xclip -selection clipboard -o
}

WSL_copy() {
    cat | /mnt/c/Windows/System32/clip.exe
}

WSL_paste() {
    /mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe Get-Clipboard | sed 's/\r//'
}

CYGWIN_copy() {
    cat >/dev/clipboard
}

CYGWIN_paste() {
    cat /dev/clipboard
}

MAC_copy() {
    cat | pbcopy
}

MAC_paste() {
    pbpaste
}

stdin_is_a_pipe() {
    [[ -p /dev/stdin ]]
}

stdin_is_a_tty() {
    [[ -t 0 ]]
}

stdin_is_pipe_like() {
    stdin_is_a_pipe || ! stdin_is_a_tty
}

stdout_is_pipe_like() {
    ! stdout_is_a_tty # meaning # it must be a pipe or redirection
}

stdout_is_a_tty() {
    [[ -t 1 ]]
}

requested_open_ended() {
    [[ "${args[0]:-}" == "-" ]]
}

requested_test_suite() {
    [[ "${args[0]:-}" == "--test" ]]
}

enable_tee_like_chaining() {
    # see `man tee`
    if stdout_is_pipe_like; then
        ${os}_paste
    elif requested_open_ended; then
        ${os}_paste
        echo
    fi
}

prevent_prompt_from_being_on_the_same_line() {
    if stdout_is_a_tty; then # we don't have to be strict about not altering the output
        echo
    fi
}

detect_os() {
    if [[ -f /proc/version ]] && grep -iq Microsoft /proc/version; then
        printf WSL
    else
        case "$(uname -s)" in
        Linux*) printf LINUX ;;
        Darwin*) printf MAC ;;
        CYGWIN*) printf CYGWIN ;;
        esac
    fi
}

function debug() {
    stdin_is_a_pipe && echo "stdin_is_a_pipe: 1" >>/tmp/ono || echo "stdin_is_a_pipe: 0" >>/tmp/ono
    stdin_is_a_tty && echo "stdin_is_a_tty: 1" >>/tmp/ono || echo "stdin_is_a_tty: 0" >>/tmp/ono
    stdin_is_pipe_like && echo "stdin_is_pipe_like: 1" >>/tmp/ono || echo "stdin_is_pipe_like: 0" >>/tmp/ono
    stdout_is_pipe_like && echo "stdout_is_pipe_like: 1" >>/tmp/ono || echo "stdout_is_pipe_like: 0" >>/tmp/ono
    stdout_is_a_tty && echo "stdout_is_a_tty: 1" >>/tmp/ono || echo "stdout_is_a_tty: 0" >>/tmp/ono
    echo >>/tmp/ono
}

main() {
    os="$(detect_os)"
    if stdin_is_pipe_like; then
        ${os}_copy
        enable_tee_like_chaining
    else # stdin is not pipe-like
        ${os}_paste
        prevent_prompt_from_being_on_the_same_line
    fi
}

args=("$@")
[[ ${DEBUG:-} == 1 ]] && debug
main
