#!/usr/bin/bash

logo=$1
pape=$2

if [[ -z "$logo" ]] || [[ -z "$pape" ]]; then
    echo $'Usage: ./mepapemaker.sh <logo> <wallpaper>\n\n<logo> is the logo name without the svg file extension.\nFor <wallpaper>, all image formats supported by\nImageMagick are valid targets.'
    exit
fi

if [ ! -f "./logo/$logo.svg" ]; then
    echo $'No such logo found.\nCheck the logo directory for available options or add\nyour own <logo>.svg to the directory.'
    exit
fi

if [ ! -f "$pape" ]; then
    echo $'Wallpaper not found. Maybe you mistyped?'
    exit
fi

# get the width and height of the logo
lheight=$(magick identify -format "%h" "./logo/$logo.svg")
lwidth=$(magick identify -format "%w" "./logo/$logo.svg")

# determine smaller dimension to use for scale
if [[ "$lheight" -lt "$lwidth" ]]; then
  lscale_val=$lheight
else
  lscale_val=$lwidth
fi

# get the width and height of the wallpaper
pheight=$(magick identify -format "%h" "$pape")
pwidth=$(magick identify -format "%w" "$pape")

# determine smaller dimension to use for scale
if [[ "$pheight" -lt "$pwidth" ]]; then
  pscale_val=$pheight
else
  pscale_val=$pwidth
fi

# calculate appropriate density to scale the svg
# 25 is the dimension of either side of the svg
# 50 is the rough scale of the logo that will be on the final image (in %)
density=$(awk "BEGIN {print ($pscale_val/($lscale_val+2))*50}")

# generate a PNG mask from the source svg
magick \
  -density $density \
  -gravity center \
  ./logo/$logo.svg \
  -background white \
  -extent "${pwidth}x${pheight}" \
  -resize 100% \
  tmp_mask.png

# generate wallpaper name
outfile_name=${logo}_btw_$(basename "$pape")

# add arch mask to original image
magick \
  "$pape" \
  -write-mask "tmp_mask.png" \
  -gravity center \
  -blur 0x30 \
  -attenuate 0.3 \
  +noise Laplacian \
  -evaluate Multiply 1.3 \
  "$outfile_name"

# delete temporary file
rm "tmp_mask.png"
