#!/bin/sh

tmpfile="$(mktemp)"
imgtype=""
use_height=""

while :; do
    case "$1" in
        "--nsfw"|"nsfw"|"-n"|"n")
            if [ "$imgtype" = "" ]; then
                [ "$DEBUG" = "true" ] && echo "Getting a nsfw image"
                imgtype="nsfw"
            else
                echo "$imgtype images were already chosen! Please only specify either sfw or nsfw!"
            fi
            ;;
        "--sfw"|"sfw"|"-s"|"s")
            if [ "$imgtype" = "" ]; then
                [ "$DEBUG" = "true" ] && echo "Getting a sfw image"
                imgtype="sfw"
            else
                echo "$imgtype images were already chosen! Please only specify either sfw or nsfw!"
            fi
            ;;
        "--w3m"|"w3m"|"--img"|"img"|"-i"|"i")
            [ "$DEBUG" = "true" ] && echo "Using w3m image backend for neofetch"
            use_w3m="true"
            ;;
        "--height"|"-h")
            if [ "$use_height" = "" ]; then
                use_height="$2"
                [ "$DEBUG" = "true" ] && echo "Using height $height"
            else
                echo "You can only specify the height argument once!"
            fi
            shift
            ;;
        *)
            if [ -z "$1" ]; then
                break
            fi
            echo "Could not interpret parameter '$1'."
            ;;
    esac
    shift
done

if [ "$imgtype" = "nsfw" ]; then
    imgurl="https://nekos.life/api/v2/img/cum_jpg"
else
    imgurl="https://nekos.life/api/v2/img/neko"
fi

if [ "$use_height" != "" ]; then
    height="$use_height"
else
    height="$(($(stty size | awk '{print $1}') - 5))"
fi

url=$(curl -fsSL "$imgurl" | jq -r ".url")

curl -fsSLo "$tmpfile.jpg" "$url"
if [ "$TERM" = "xterm-kitty" ]; then
    command -v convert > /dev/null 2>&1 && neofetch --kitty "$tmpfile.jpg" || kitty_imagemagick_warn=true
    if [ "$kitty_imagemagick_warn" = "true" ]; then
        jp2a --height="$height" "$tmpfile.jpg" > "$tmpfile"
        neofetch --source "$tmpfile"
    fi
elif [ "$LC_TERMINAL" = "iTerm2" ]; then
    neofetch --iterm2 "$tmpfile.jpg"
elif [ "$use_w3m" = "true" ]; then
    neofetch --w3m "$tmpfile.jpg"
else
    jp2a --height="$height" "$tmpfile.jpg" > "$tmpfile"
    neofetch --source "$tmpfile"
fi

rm "$tmpfile" "$tmpfile.jpg"

[ "$kitty_imagemagick_warn" = "true" ] && echo "WARN: imagemagick is required for kitty image backend"
