#!/bin/bash
QUALITY=85
THUMB_QUALITY_PNG=70
THUMB_QUALITY_JPG=50

cd $(dirname $(realpath -s ${0}))

RULES=()

function generate_rule() {
  image=${1}
  resolutions=${2}
  default_resolution=${3}
  quality=${4}
  thumb_quality=${5}
  thumb_format=${6}

  for resolution in ${resolutions}; do
    RULES+=("${image}@${resolution}.png")
    echo "${image}@${resolution}.png: ${image}.png" >> Makefile.wip
    echo "	\$(RESOLUTION) ${image} ${resolution} ${quality}" >> Makefile.wip
  done

  case ${thumb_format} in
  "png")
    RULES+=("${image}@thumb.png")
    echo "${image}@thumb.png: ${image}.png" >> Makefile.wip
    echo "	\$(THUMB) ${image} ${default_resolution} ${thumb_quality} png" >> Makefile.wip
    ;;
  "jpg")
    RULES+=("${image}@thumb.jpg")
    echo "${image}@thumb.jpg: ${image}.png" >> Makefile.wip
    echo "	\$(THUMB) ${image} ${default_resolution} ${thumb_quality} jpg" >> Makefile.wip
    ;;
  "none")
    RULES+=("${image}@thumb.png")
    echo "${image}@thumb.png: ${image}.png" >> Makefile.wip
    echo "	\$(THUMB) ${image} ${default_resolution} ${thumb_quality} none" >> Makefile.wip
    ;;
  *)
    echo "Unknown format: $thumb_format"
    exit 1
    ;;
  esac
}

function finalize() {
  echo -n "all:" >> Makefile
  for rule in "${RULES[@]}"; do
    echo -n " $rule" >> Makefile
  done
  echo >> Makefile
  cat Makefile.wip >> Makefile
  rm Makefile.wip
}

cat <<EOF > Makefile
RESOLUTION = \$(shell pwd)/generate_resolution.sh
THUMB = \$(shell pwd)/generate_thumb.sh
EOF
# Generate Images
themes="material_light material_dark solarized_light solarized_dark gruvbox_light gruvbox_dark amoled dracula"
for image in ${themes}; do
  generate_rule ${image} "220 266 335 352 532" 16x ${QUALITY} ${THUMB_QUALITY_JPG} jpg
done
generate_rule phone "220 300 400 520 640 800 1000 1220" 16x16 ${QUALITY} 0 none
generate_rule tablet "545 640 720 800 880 960 1090 1635 2180" 16x16 ${QUALITY} 0 none
generate_rule notifications "363 474 590" 16x ${QUALITY} ${THUMB_QUALITY_JPG} jpg
generate_rule desktop "363 474 590 726 948 1180" 16x ${QUALITY} ${THUMB_QUALITY_JPG} jpg

finalize
