#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment

#set -e

main(){
    # pre {{{
    local url urldefault buffer syntax syntax_filetype max_lines user min_lines direct_paste command is_stdin arg channel message conf extension

    if ! el_dependencies_check "pastebinit|file" ; then
        if ! el_dependencies_install "pastebinit|file" ; then
            exit 1
        fi
        #el_error "install the package pastebinit first"
    fi

    if [[ ! -t 0 ]] ; then
        is_stdin=1
    fi

    unset LANG LANGUAGE LC_ALL LC_MESSAGES

    # }}}

    # variables
    max_lines="10000"
    min_lines="10"
    user="$USER"
    is_irc_paste=1
    #urldefault="http://paste2.org" # broken
    # openstack don't accept syntax parameter? at least not for C (edc) files
    #urldefault="http://paste.openstack.org" # broken
    # we should use debian, it supports syntax, download, selection, username, etc
    #urldefault="http://paste.debian.net" # broken
    urldefault="dpaste.com" # works, but no syntax
    #urldefault="sprunge.us" # it works, but no syntax, but they can be downloaded and in any case its handy to have it working
    # TODO:  <Naglfar> try this: curl -F 'file=@-' https://ttm.sh
    # TODO:  <keyra_> Thanatermesis, memo for you: <TheTechRobo/#elive/2021-08-23 19:10>  in elivepaste, replace the pastebin with this? https://transfer.archivete.am/
    command="$@"

    conf="${HOME}/.config/elive/elivepaste/config.sh"

    # get confs
    if [[ -f "$conf" ]] ; then
        source "${conf}"
    fi

    # Usage
    if [[ -z "$1" ]] && ! ((is_stdin)) ; then
        #echo -e "Usage: $(basename $BASH_SOURCE) [options]"
        echo -e "Example: elivepaste sourcecode.c"
        echo -e "Example: dmesg | tail -n 200 | elivepaste"
        echo -e "Options:"
        echo -e "-c channel: second parameter is the name of the IRC channel where to send the message"
        echo -e "-m message: an optional extra message to include"
        echo -e "-d : direct paste mode (warning to not include more than 5 lines or this is considered flood"
        echo -e "-s : silent mode: do not send to any IRC channel, just get the returned url"
        exit 1
    fi

    for arg in "$@"
    do
        case "$arg" in
            -c)
                channel="${2#\#}"
                shift 2
                ;;
            -m)
                message="$2"
                shift 2
                ;;
            -d)
                direct_paste=1
                shift
                ;;
            -s)
                unset is_irc_paste
                shift
                ;;
        esac
    done

    : ${channel:="elive"}

    # run and save output
    if ((is_stdin)) ; then
        buffer="$( cat 2>&1 | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" )"
        command="(piped)"
    else

        if [[ -z "$1" ]] || [[ ! -s "$1" ]] ; then
            el_error "not file given"
            exit 1
        fi

        if [[ "${1}" = *"crashdump"* ]] ; then
            # Unfortunately at this time, pastebin.com doesn't works, says wrong api, so just notice the user with this:
            el_explain 0 "File is a crashdump, pastebin.com does a __very readable__ syntax if you use GDB, you should paste it manually if you want it"
        fi

        #if [[ -z "$2" ]] && [[ -f "${1}" ]] && ! el_dependencies_check "$1" 2>/dev/null 1>/dev/null ; then
            # $1 is a file, not a command
            buffer="$( cat "${1}" | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" )"
            extension="${1##*.}"
        #else
            #if [[ -e "$1" ]] ; then
            #buffer="$( "$@" 2>&1 | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" )"
            #echo "$buffer"
            #else
                #exit 1
            #fi
        #fi
    fi

    # set syntax {{{
    syntax_filetype="$( echo -e "$buffer" | file - )"

    case "$syntax_filetype" in
        *shell*script*)
            syntax="bash"
            ;;
        *ASCII\ C\ program*|*C\ source*)
            syntax="c"
            ;;
        *python\ script*)
            syntax="python"
            ;;
        *PHP*)
            syntax="php"
            ;;
        *diff*)
            syntax="diff"
            ;;
        *makefile*)
            syntax="make"
            ;;
        *)
            syntax="text"
            ;;
    esac

    # overwrite by extension
    case "$extension" in
        edc)
            syntax="c"
            ;;
        *)
            true
            ;;
    esac

    # - set syntax }}}

    # checks {{{

    # empty ?
    if [[ -z "$buffer" ]] ; then
        el_debug "buffer empty, ignoring..."
        exit 1
    fi

    # max lines allowed
    if [[ "$(echo -e "${buffer}" | wc -l)" -gt "$max_lines" ]] ; then
        el_error "Output lines are bigger than 500, too long paste, ignoring..."
        el_explain 0 "Try instead: __command args | foo | bar | $(basename $0)__"
        exit 1
    fi

    # few lines = paste directly in the channel | disabled, because is not a good thing to have
    #if [[ "$(echo -e "${buffer}" | wc -l)" -le "$min_lines" ]] ; then
        #direct_paste=1
    #fi
    # - checks }}}

    # get url
    if ! ((direct_paste)) ; then

        # paste it
        url="$( echo "${buffer}" | pastebinit -b "$urldefault" -a "$user" -f "${syntax}" 2>/dev/null | head -1 )"

        # checks
        if ! echo "${url}" | grep -qsE "https?://" || [[ "${url}" = "$urldefault" ]] ; then
            el_error "URL not get correctly: $url"
            exit 1
        fi

    fi

    # send to channel
    if ((is_irc_paste)) && ps ux | grep -Fv grep | grep -Fqs "hexchat" && el_dependencies_check hexchat 1>/dev/null 2>/dev/null ; then
        # send first a message
        if [[ -n "$message" ]] ; then
            hexchat -e -c "msg #$channel $message"
        fi

        if ((direct_paste)) ; then
            hexchat -e -c "msg #$channel \$ $command"
            hexchat -e -c "msg #$channel $buffer"
        else
            hexchat -e -c "msg #$channel [$command] $url"
        fi

        echo ""
        el_explain 0 "output sent to the #$channel channel"
        el_explain 0 "Paste available in: __${url}__"
    else
        # save it to clipboard, right-click mouse ready
        if el_dependencies_check xclip 2>/dev/null 1>/dev/null && [[ -n "$DISPLAY" ]] ; then
            echo "$url" | xclip -i -selection clipboard
        fi

        # finally show the url in the terminal
        echo -e ""
        el_explain 0 "Paste available in: __${url}__"
        #echo "$url"
    fi
}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
