#!/bin/zsh

set -e # bail on errors

function filesize() {
  stat "$1" | cut -d' ' -f8
}

ORIG_IMG_PATH="$1"

# ignore screenshots created by this script or upload-to-s3
if [[ "$ORIG_IMG_PATH" == *"@1x.png" ]] || [[ "$ORIG_IMG_PATH" == *"@1x.jpg" ]]; then
  exit 0
fi

BIG_SIZE=$((666 * 1024))

WEB_IMG_PATH="$ORIG_IMG_PATH"
ls -lh "$WEB_IMG_PATH"
if [[ $(filesize "$ORIG_IMG_PATH") -gt $BIG_SIZE ]]; then
  echo "TOO BIG, DERETINA..."
  WEB_IMG_PATH="${ORIG_IMG_PATH%.png}@1x.png"
  convert -resize "50%" "$ORIG_IMG_PATH" "$WEB_IMG_PATH"
  ls -lh "$WEB_IMG_PATH"
  if [[ $(filesize "$WEB_IMG_PATH") -gt $BIG_SIZE ]]; then
    echo "STILL TOO BIG, COVERTING TO JPEG"
    WEB_IMG_PATH="${ORIG_IMG_PATH%.png}@1x.jpg"
    convert -quality 95 -resize "50%" "$ORIG_IMG_PATH" "$WEB_IMG_PATH"
    ls -lh "$WEB_IMG_PATH"
  fi
fi
FILENAME=$(basename "$WEB_IMG_PATH")
FILENAME="${FILENAME// /_}"
IMG_HOST="static.samhuri.net"
URL="http://${IMG_HOST}/${FILENAME}"
echo -n "$URL" | pbcopy
s3cmd put "$WEB_IMG_PATH" "s3://${IMG_HOST}/${FILENAME}"
echo "$URL"
