#!/usr/bin/env fish

set fish_trace 1

set progname (status basename)

function warning
    set_color yellow
    echo "[$progname]" $argv >&2
    set_color --default
end

function error
    set_color brred
    echo "[$progname]" $argv >&2
    set_color --default
    exit 1
end

argparse --name="$progname" \
    'i/input=' \
    'o/output=' \
    't/top=' \
    'b/bottom=' \
    's/scale=' \
    'open' \
    'f/force' \
    -- $argv

set input "$_flag_input"
set output "$_flag_output"
set top "$_flag_top"
set bottom "$_flag_bottom"
set scale "$_flag_scale"
set force "$_flag_force"

test -f "$input"
or error "No input file provided"


if test -z "$top""$bottom"
    warning "No top or bottom text provided"

    test -n "$top"
    or set top (echo | wdmenu -p 'Top text: ')
    test -n "$bottom"
    or set bottom (echo | wdmenu -p 'Bottom text: ')
end

set original_name (basename "$input" |
                   string replace -r '\.\w+$' '')
set meme_text (string join - $top $bottom)

test -n "$output"
or set output "$meme_text-$original_name.png"

if test -f "$output"
    and not set -q force
    error "Output file exists"
end

if set -q scale
    set resized (mktemp -t memegen-XXXXX.png)
    command magick convert "$input" -resize "$scale""%" "$resized"
else
    set resized "$input"
end

set size (magick identify -format "%[fx:w]x%[fx:h]" "$resized")

command magick convert "$resized" \
    -gravity north \
    \( -size "$size" xc:none -font Impact -pointsize 50 -stroke black -strokewidth 7 -annotate 0 "$top" -blur 0x1 \) -composite \
    -font Impact -pointsize 50 -fill white -stroke none -annotate 0 "$top" \
    -gravity south \
    \( -size "$size" xc:none -font Impact -pointsize 50 -stroke black -strokewidth 7 -annotate 0 "$bottom" -blur 0x1 \) \
    -font Impact -pointsize 50 -fill white -stroke none -annotate 0 "$bottom" -composite \
    $argv "$output"

if test "$input" != "$resized"
    command rm "$resized"
end

if set -q _flag_open
    command xdg-open "$output"
end

# vim: ft=fish
