#!/bin/sh
#
# image2ascii - convert(1) any image to an ASCII-graphic using ImageMagick(1)

umask 077

tmpdir=$(mktemp -d "${TMPDIR:-/tmp}"/img.XXXXXX) || exit 1
# shellcheck disable=SC2064
trap "rm -rf ${tmpdir}; exit" EXIT HUP INT QUIT TERM
tmpfile="${tmpdir}/image"

usage() {
  printf '%s' "\
Usage: ${0##*/} [option] [imagefile]

Options:
   -help                show this help text
   -geometry 132x50     define the size of the ascii image
"
  exit 0
}

# set default geometry to display width:
geometry=$(stty size </dev/tty | awk '{ print $2 "x" $1 }')

# test if stty did not output a useful value:
# shellcheck disable=SC2249
case "${geometry}" in
  '') geometry="80x24" ;;
  0x0) geometry="80x24" ;;
esac

case "$#" in
  0) cat >"${tmpfile}" ;;
  1)
    case "$1" in
      -*) usage ;;
      *) cat "$1" >"${tmpfile}" ;;
    esac
    ;;
  2)
    case "$1" in
      -geometry)
        geometry="$2"
        cat >"${tmpfile}"
        ;;
      *) usage ;;
    esac
    ;;
  3)
    case "$1" in
      -geometry)
        geometry="$2"
        cat "$3" >"${tmpfile}"
        ;;
      *) usage ;;
    esac
    ;;
  *) usage ;;
esac

# multiply x with 2 and y with 4 (pbmtoascii divides by 2x4)
geometry=$(echo "${geometry}" | awk -Fx '{ print 2*$1 "x" 4*$2 }')

convert -geometry "${geometry}" "${tmpfile}" "${tmpfile}.pbm" 2>/dev/null
pbmtoascii -2x4 <"${tmpfile}.pbm"
