#! /bin/bash

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

case "$*" in
    "")
        echo "Usage: `basename $0` [-w WIDTH] [-h HEIGHT] [-par] 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
        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

    # Handle cases where a screen command running on Cygwin is in the process chain.
    # Traverse parent processes from the current PID until reaching a screen command
    # that holds a pty. If found, redirect sequences to that pty.
    # Otherwise, redirect sequences to standard output.
    myPID=$$
    myPSL=$(ps -p ${myPID} | sed '2!d')
    myPPID=$(echo ${myPSL} | awk '{print $2}')
    myTTY=$(echo ${myPSL} | awk '{print $5}')
    myCMD=$(echo ${myPSL} | awk '{print $NF}')
    loopcount=0
    is_screen_pty=0
    while [ ${loopcount} -lt 8 ]; do
        myPID=${myPPID}
        if [[ ${myPID} == "" ]]; then
            break;
        fi
        myPSL=$(ps -p ${myPID} | sed '2!d')
        myPPID=$(echo ${myPSL} | awk '{print $2}')
        myTTY=$(echo ${myPSL} | awk '{print $5}')
        myCMD=$(echo ${myPSL} | awk '{print $NF}')
        if [[ ${myCMD} == *"/screen" && ${myTTY} == "pty"* ]]; then
            is_screen_pty=1
            break;
        fi
        loopcount=$((loopcount + 1))
    done

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

    if (( is_screen_pty == 1 )) && [ -t 1 ]; then
        echo -en "${MINTTY_SEQ}" > "/dev/${myTTY}"
    else
        echo -en "${MINTTY_SEQ}"
    fi

done
