#!/usr/bin/env sh

# Description: Selections are archived into a tar file (uncompressed) and uploaded to file.io
#              For single files:
#              Paste contents of a text file to http://ix.io
#              Upload a binary file to file.io
#
# Dependencies: curl, jq, tar, file with `--mime-type` support
#
# Note: Binary file set to expire after a week
#
# Shell: POSIX compliant
# Author: Arun Prakash Jana

selection=${NNN_SEL:-${XDG_CONFIG_HOME:-$HOME/.config}/nnn/.selection}
if [ -s "$selection" ]; then
    xargs -0 tar -c < "$selection" | \
        curl -s -F "file=@/dev/stdin;filename=selection.tar" 'https://file.io/?expires=1w' | \
        jq '.link' | tr -d '"'

    # Clear selection
    printf "-" > "$NNN_PIPE"
else
    if [ -n "$1" ] && [ -s "$1" ]; then
        if file --mime-type "$1" | grep -q -F "text/"; then
            curl -F "file=@$1" https://0x0.st
        else
            # Upload the file, show the download link and wait till user presses any key
            curl -s -F "file=@$1" https://file.io/?expires=1w | jq '.link' | tr -d '"'
            # To write download link to "$1".loc and exit
            # curl -s -F "file=@$1" https://file.io/?expires=1w -o `basename "$1"`.loc
        fi
    else
        printf "empty file!"
    fi
fi

read -r _
