#!/bin/bash
# Open attachment with correct extension based on mime type

tmpfile=$(mktemp)
cat >"$tmpfile"

mime=$(file --mime-type -b "$tmpfile")

case "$mime" in
application/pdf) ext=".pdf" ;;
image/png) ext=".png" ;;
image/jpeg) ext=".jpg" ;;
image/gif) ext=".gif" ;;
text/html) ext=".html" ;;
text/plain) ext=".txt" ;;
application/zip) ext=".zip" ;;
application/msword) ext=".doc" ;;
application/vnd.openxmlformats-officedocument.wordprocessingml.document) ext=".docx" ;;
application/vnd.ms-excel) ext=".xls" ;;
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet) ext=".xlsx" ;;
application/vnd.ms-powerpoint) ext=".ppt" ;;
application/vnd.openxmlformats-officedocument.presentationml.presentation) ext=".pptx" ;;
*) ext="" ;;
esac

if [[ -n $ext ]]; then
    mv "$tmpfile" "${tmpfile}${ext}"
    tmpfile="${tmpfile}${ext}"
fi

open "$tmpfile"
