#! /bin/bash

width=
height=
pAR=
forcePTY=
while
    case "$1" in
        -w|-width)
            width=";width=$2"
            shift; shift;;
        -h|-height)
            height=";height=$2"
            shift; shift;;
        -fit)
            pAR=";preserveAspectRatio=0"
            shift;;
        -t|-pty)
            forcePTY="$2"
            shift; shift;;
        *)
            false;;
    esac
do true
done

case "$*" in
    "")
        echo "Usage: `basename $0` [-w WIDTH] [-h HEIGHT] [-fit] [-t ptyX] IMAGE [...]" >&2
        echo >&2
        echo "This script outputs images to the terminal for display." >&2
        echo "Parameters:" >&2
        echo "  -w, -width N    width in N cell units, or Npx, or N%" >&2
        echo "  -h, -height N   height in N cell units, or Npx, or N%" >&2
        echo "  -fit            with both width and height: do not preserve aspect ratio" >&2
        echo "  -t, -pty ptyX   Specify the PTY(/dev/ptyX) to force-write to." >&2
        exit;;
esac

case "${BASH}" in
    ?*)
        echo=echo;;
    *)
        echo=/bin/echo;;
esac

for img in "$@"
do
    if [[ "-" == "${img}" ]]; then
        NAME_B64=$(echo -n "stdin" | base64 -w 0)
        IMG_B64=$(base64 -w 0)
    elif [ -r "${img}" ]; then
        NAME_B64=$(echo -n "$img" | base64 -w 0)
        IMG_B64=$(base64 -w 0 "${img}")
    else
        echo cannot read file "${img}" >&2
        continue
    fi

    if [ -n "$STY" ]; then
        SC_PID=${STY%%.*}
        SC_PS=$(ps -p $SC_PID | sed '2!d')
        SC_TTY=$(echo ${SC_PS} | awk '{print $5}')
        SC_PPID=$(echo ${SC_PS} | awk '{print $2}')
        if [[ ${SC_PPID} == "1" ]]; then
            SC_PID=$(ps -ef | grep -E "screen.*[rR]" | grep "$SC_PID" | awk '{print $2}')
            if [ -n "$SC_PID" ]; then
                SC_TTY=$(ps -p $SC_PID | sed '2!d' | awk '{print $5}')
            else
                SC_TTY=""
            fi
        else
            SC_PS=$(ps -p $SC_PPID | sed '2!d')
            SC_TTY=$(echo ${SC_PS} | awk '{print $5}')
        fi
    else
        SC_TTY=""
    fi

    MINTTY_SEQ=$'\e]1337;File=name='${NAME_B64}';inline=1'${width}${height}${pAR}':'${IMG_B64}$'\a'

    if [[ ${forcePTY} != "" ]]; then
        if [[ -w /dev/${forcePTY} ]]; then
            echo -en "${MINTTY_SEQ}" > "/dev/${forcePTY}"
            continue
        else
            echo "Cannot write to file /dev/${forcePTY}"
            exit 1
        fi
    else
        if [[ ${SC_TTY} == "pty"* ]] && [ -t 1 ]; then
            echo -en "${MINTTY_SEQ}" > "/dev/${SC_TTY}"
        else
            echo -en "${MINTTY_SEQ}"
        fi
    fi

done
