#!/bin/bash

echo2()   { echo "$@" >&2 ; }
printf2() { printf "$@" >&2 ; }
DIE()     { echo2 "$progname: error: $1"; exit 1; }

Usage() {
    cat <<EOF >&2
$progname sends the input (stdin) to a pastebin service.

Usage: $progname [options] command-string
Options:
   --0x0         Uses 0x0.st
   --dpaste      Uses dpaste.com
   --termbin     Uses termbin.com
   --help, -h    This help
   --expire=*    Specifies the URL expiration time in days.
   --no-yad      Prevent using yad messages.

Without options the services are tried in order until one succeeds or all fail.
Trial order: 0x0 dpaste termbin.
EOF
    [ "$1" ] && exit "$1"
}

0x0() {
    local url code

    url=$($curl --fail -F'file=@-' -Fexpires=$((expire * 24)) https://0x0.st)
    code=$?
    if [ $code -eq 0 ] ; then
        echo "$url"
        echo "--> The URL below will expire in $expire days." >&2
    else
        echo "==> 'curl' failed with code $code." >&2
    fi
    return $code
}
dpaste()      { $curl -F "content=<-" https://dpaste.com/api/v2/ ; }
termbin()     { [ -x /bin/nc ] || return 1; nc -w $timeout termbin.com 9999; }
ix.io()       { $curl -F'f:1=<-'  ix.io ; }                            # 2023/12/04: fails??
wgetpaste()   { wgetpaste -n anonymous ; }                             # 2023/12/04: fails, no more maintained??

Tee() {
    local srv="$1"
    echo "$input" | "$srv" > $log
    return $?
}

GeneralWarning() {
    declare -A urls=(
        [0x0]="https://0x0.st"
        [dpaste]="https://dpaste.com"
        [termbin]="termbin.com"
    )
    local txt=""
    local stop=no

    txt+="You are about to send <i>your data</i> to a pastebin service on the internet.\n"
    txt+="Anyone will be able to see the data.\n"
    txt+="Please make sure you are not sending any unwanted information.\n\n"
    txt+="If you want to manage the information you've sent already, please contact <b>${urls[$srv]}</b>.\n"

    case "$yad" in
        yes)
            local cmd=(
                eos_yad --form --title="Warning" --text="$txt"
                --button="yad-quit!!Do not send":1 --button="yad-execute!!Continue sending":3
            )

            "${cmd[@]}"

            case "$?" in
                3) ;;
                *) stop=yes ;;
            esac
            ;;
        no)
            ReopenStdin
            echo -e "$txt" | sed -e 's|<.>||' -e 's|</.>||' >&2
            read -p "Continue sending (Y/n)? " >&2
            case "$REPLY" in
                [Nn]*) stop=yes ;;
            esac
            ;;
    esac
    [ $stop = yes ] && { echo2 "Nothing sent."; exit 0; }
}

ReopenStdin() {
    if [ $stdin_needs_opening = yes ] ; then
        stdin_needs_opening=no
        exec < /dev/tty
    fi
}

CanUseYad() {
    # check if yad exists, and if so, can we use it

    local -n _use_yad="$1"

    if expac -Q %n yad >/dev/null ; then
        _use_yad=yes                                                  # yad is installed
        if [ "$EUID" = "0" ] && eos_is_in_chroot ; then
            _use_yad=no                                               # don't use yad in chroot
        else
            case "$XDG_SESSION_TYPE" in
                tty)       _use_yad=no ;;                             # tty does not support yad
                x11)       [ "$DISPLAY" ]         || _use_yad=no ;;   # no DISPLAY, no yad
                wayland-*) [ "$WAYLAND_DISPLAY" ] || _use_yad=no ;;   # same with wayland
            esac
        fi
    else
        _use_yad=no                                                   # yad is not installed
    fi
}

Main() {
    local -r progname="${0##*/}"
    local -r log=/tmp/tmp.$progname.log
    local -r timeout=10                               # max seconds to wait when sending to pastebin
    local -r curl="/bin/curl --fail -Lsm $timeout"
    local count=0
    local services=(
        0x0
        dpaste
        termbin
    )
    local expire=7     # this initial value here will always be overwritten by eos-sendlog
    local yad=""
    local infile=""
    local commands=""
    local stdin_needs_opening=no

    source /usr/share/endeavouros/scripts/eos-script-lib-yad || exit 1

    CanUseYad yad

    while [ "$1" ] ; do
        case "$1" in
            --0x0 | --dpaste | --termbin)  services=("${1:2}") ;;
            --help | -h)                   Usage 0 ;;
            --expire=*)                    expire="${1#*=}" ;;
            --no-yad)                      yad=no ;;
            --infile=*)                    infile="${1#*=}"; break ;;
            -*)                            echo2 "Unsupported option '$1'"; exit 1 ;;
            *)                             commands="$*"; break ;;
        esac
        shift
    done

    if [ "$infile" ] ; then
        local -r input="$(cat $infile)"                   # input from a file
        stdin_needs_opening=yes
    elif [ "$commands" ] ; then
        local -r input="$(LANG=C bash -c "$commands")"    # input from commands
    else
        local -r input="$(cat)"                           # input from stdin
        stdin_needs_opening=yes
    fi
    [ "$input" ] || DIE "No input!"

    for srv in "${services[@]}" ; do
        GeneralWarning
        if Tee "$srv" ; then
            cat $log
            return 0
        fi
        ((count++))
        [ $count -lt ${#services[@]} ] && echo2 "==> Info: ${srv} failed, trying ${services[$count]} ..."
    done
    DIE "configured pastebin services failed!"
}

Main "$@"
