#!/usr/bin/env fish

# tt -- a tool for transfering files and folders over text

# requirements:
# fish, tar, zstd, brotli, base64

function err
    echo -- $argv >&2
end

switch $argv[1]
case s send
    if test (count $argv[2..-1]) -eq 0
        err "tt: no files or directories given"
        exit 1
    end
    for f in $argv[2..-1]
        test -e "$f"; or set -a missing "$f"
    end
    if set -q missing
        for p in $missing
            err "tt: '$p' was not found"
        end
        exit 1
    else
        for p in $argv[2..-1]
            set -a args -C (path resolve (path dirname $p)) (path basename $p)
        end

        set zstd (tar -cI 'zstd -19' $args | base64 -w0)
        set brotli (tar -cI 'brotli -9' $args | base64 -w0)
        if test (string length -- $zstd) -le (string length -- $brotli)
            echo z:$zstd
        else
            echo b:$brotli
        end
    end
case r receive
    read -P "string: " string

    if test -z "$string"
        err "tt: empty strings aren't allowed"
        exit 1
    end

    set used_algo (string match -rg "^([zb]):" -- $string)
    if test $used_algo = "z"
        set algo zstd
    else if test $used_algo = "b"
        set algo brotli
    else
        err "tt: wrong or missing prefix"
        exit 1
    end

    set string (string match -rg ":(.*)" -- $string)
    echo -- $string | base64 -d 2>/dev/null | tar -xvoI "$algo" 2>/dev/null
    set ps -l $pipestatus
    if test $ps[2] -ne 0
        err "tt: invalid base64 string"
        exit 1
    else if test $ps[3] -ne 0
        err "tt: archive is corrupted or invalid"
        exit 1
    end
case '*'
    echo "usage: tt <s|r> [file|dir ...]"
    echo
    echo "  s, send     <file|dir> ... "
    echo "  r, receive"
end
