#!/bin/bash

# Like the "old" eos-sendlog, with an addition to take the input from multiple commands.

DIE()     { echo "$progname: error: $1" >&2; exit 1; }
Verbose() { [ $verbose = yes ] && echo -e "$@" >&2 ; }

Options() {
    local opts
    local sopts="e:hv"
    local lopts="0x0,dpaste,termbin"       # pastebin options
    lopts+=",expire:,help,verbose,no-yad"  # general options

    opts="$(/bin/getopt -o="$sopts" --longoptions "$lopts" --name "$progname" -- "$@")" || Usage 1
    eval set -- "$opts"

    while true ; do
        case "$1" in
            -h | --help)                   Usage 0 ;;
            -v | --verbose)                verbose=yes ;;
            --0x0 | --dpaste | --termbin)  helper_options+=("$1") ;;
            -e | --expire)                 helper_options+=(--expire="$2"); shift ;;
            --no-yad)                      helper_options+=($1) ;;
            --)                            shift; break ;;
            *)                             break ;;
        esac
        shift
    done
    [ "$1" ] && commands="$*"
}

Usage() {
    cat <<EOF >&2
Usage:
    1. input from one command via stdin:
          <command> | $progname [$progname-options]
    2. input from outputs of multiple commands:
          $progname [$progname-options] "<command1> ; <command2> ; <command3> ..."
${progname}-options:
    --0x0           Use only pastebin 0x0.st.
    --dpaste        Use only pastebin dpaste.com.
    --termbin       Use only pastebin termbin.com.
    --help, -h      This help.
    --verbose, -v   Be more verbose.
    --expire, -e    The URL will expire in X days. Default: $expire_def.
                    Currently supported only for 0x0.st.
    --no-yad        Prevent using yad messages (useful if display cannot be opened).

Without ${progname}-options the services are tried in order:
    1. 0x0
    2. dpaste
    3. termbin
until one succeeds or all fail.

Examples:
    inxi -Fza | $progname --dpaste
    $progname "pacman -Qm ; lsusb"
EOF
    [ "$1" ] && exit "$1"
}

Main() {
    local progname=${0##*/}
    local commands=""
    local verbose=no
    local -r expire_def=7      # days
    local helper_options=(--expire=$expire_def)

    Options "$@"

    if [ "$commands" ] ; then
        Verbose "==> input from commands..."
        eos-sendlog-helper "${helper_options[@]}" "$commands"
    else
        Verbose "==> input from stdin..."
        local -r file=$(mktemp)
        chmod go-rwx $file
        cat > $file
        eos-sendlog-helper "${helper_options[@]}" --infile=$file
        rm -f $file
    fi
}

Main "$@"
