#!/usr/bin/env zsh
#
# Defines transfer alias and provides easy command line file and folder sharing.
#
# Authors:
#   Remco Verhoef <remco@dutchcoders.io>
#   https://github.com/zulu-zsh/plugin-transfer/blob/master/transfer
#
# Modifications made by Dominic Reich <oe7drt@oevsv.at>
# August 23, 2020
#

_transfer() { 
    # check arguments
    if [ $# -eq 0 ]; 
    then 
        echo "No arguments specified.\nusages: upload [file]"
        echo "        cat [file] | upload [remote-basename]"
        return 1
    fi

    # get temporarily filename, output is written to this file show progress can be showed
    tmpfile=$( mktemp -t transferXXX )
    chmod 644 $tmpfile
    
    # upload stdin or file
    file=$1

    if tty -s; 
    then 
        basefile=$(basename "$file" | sed -e 's/[^a-zA-Z0-9._-]/-/g') 

        if [ ! -e $file ];
        then
            echo "File $file doesn't exists."
            return 1
        fi
        
        if [ -d $file ];
        then
            # zip directory and transfer
            zipfile="$( mktemp -t transferXXX.zip )"
            cd $(dirname $file) && zip -r -q - $(basename $file) >> $zipfile
            ##curl --progress-bar --upload-file "$zipfile" "https://transfer.sh/$basefile.zip" >> $tmpfile
            
            # add scp routine here for zipfile...
            scp -q "$zipfile" "chronos:/var/www/chronos/pub/$basefile.zip"
            echo "https://chronos.oe7drt.com/pub/${basefile}.zip"
            rm -f $zipfile
        else
            # transfer file
            #curl --progress-bar --upload-file "$file" "https://transfer.sh/$basefile" >> $tmpfile
            scp -q "$file" "chronos:/var/www/chronos/pub/${basefile}.txt"
            echo "https://chronos.oe7drt.com/pub/${basefile}.txt"
        fi
    else 
        # transfer pipe
        #curl --progress-bar --upload-file "-" "https://transfer.sh/$file" >> $tmpfile
        cat "-" >> $tmpfile
        scp -q "$tmpfile" "chronos:/var/www/chronos/pub/${file}.txt"
        echo "https://chronos.oe7drt.com/pub/${file}.txt"
    fi
   
    # cat output link
    #cat $tmpfile

    # cleanup
    rm -f $tmpfile
}

_transfer "$@"