#!/bin/bash
red=`tput setaf 1`
green=`tput setaf 2`
yellow=`tput setaf 3`
blue=`tput setaf 4`
#magenta=`tput setaf 5`
cyan=`tput setaf 6`

# Copyright (c) 2016 Ramon <https://github.com/ram-on/imgurbash2>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#--------------------------------------------------------------------
# AUTHORS:  Ramon <https://github.com/ram-on/imgurbash2>
#           Originally written by Bart Nagel <bart@tremby.net>
#           Ascii art provided by cirrus <cirrus@cirrusminor.info>
# REQUIRED: curl
# OPTIONAL: xsel or xclip for copying URLs to your clipboard.
#--------------------------------------------------------------------
#
# The URLs will be outputted on your terminal. If you have xsel or xclip the
# URLs will also be put on the X selection, which you can usually paste with a CTRL-V.

# Software version
version="2.1"


#
# Function to output usage instructions
#
# Parameters:  None
#
function usage() {
	echo "Uploads images to imgur and output their imgurl URL link.  It can also delete" >&2
	echo "previously uploaded images.  If xsel or xclip is available, the links are copied" >&2
	echo "to your clipboard." >&2
	echo "" >&2
	echo "Usage:" >&2
	echo "    $(basename $0) [option] <image_1> [<image_2>...]" >&2
	echo "" >&2
	echo "Where:" >&2
	echo "    image_num is a local image file or a remote image (i.e. http/https)." >&2
	echo "" >&2
	echo "Options:" >&2
	echo "    -d, --delete <delete_hash_1> [<delete_hash2>...]" >&2
	echo "        Deletes image(s) based on the the supplied delete hash.  The delete hash" >&2
	echo "        is outputted when the user uploads an image." >&2
	echo "    -h, --help" >&2
	echo "        Displays this help and exit." >&2
	echo "    -v, --version" >&2
	echo "        Print program version and exit." >&2
	echo "" >&2
	echo "Examples:" >&2
	echo "    Refer to https://github.com/ram-on/imgurbash2" >&2
}


#
# Returns true if the image is stored on a remote machine (i.e. http or https);
# false otherwise.
#
# Parameter:  URL to parse
#
function is_remote_image() {	
	if [ $(grep -i -E "^(http[s]?)://.+" <<< "$1")  ]; then
		return $(true)
	else
		return $(false)
	fi
}


#
# curl function that will send requests to the imgur server(s).
#
function curl_imgur() {
	curl -sH "Authorization: Client-ID 1923eac1555838e" "$@"
}
#
function candy () {
echo -e '\e[1;31m' 
echo "        ┌───────────────────────────────────┐"
echo "        │     Uploading Image To Imgur!     │ "
echo "        └───────────────────────────────────┘"
echo "       ╱"
echo "   ▀▄   ▄▀"
echo -e "  ▄█▀███▀█▄ "
echo -e " █▀███████▀█"
echo -e " ▀ ▀▄▄ ▄▄▀ ▀"
echo -e '\e[1;37m'
}


#
# Uploads image to imgur
#
# Parameter:  Image file path or image URL
#
function upload_image() {

	file="$1"

	# if the image is stored remotely...
	if is_remote_image "$file"; then
		curl_imgur --data-urlencode "image=$file" "https://api.imgur.com/3/upload"
		
	# else if the local image file exists on disk...
	elif [ -f "$file" ]; then
		curl_imgur -F "image=@$file" "https://api.imgur.com/3/upload"
	
	# else the file does not exist
	else
		echo '"error":"File does not exist, skipping"'
	fi
}



#
# Given a string it will try to extract its values (from the given JSON response).
# E.g.  '"error":"Invalid client_id"' ==> string = "error", value = "Invalid client_id"
#
# Paramateres:
#   $1 - Response JSON.
#   $2 - 'String' (not datatype) which will be used to get the value from.
#
function get_value_from_response() {
	sed -e 's/.*\"'$2'\":"\([^"]*\).*/\1/' <<< "$1"
}


#
# Uploads image(s) to imgur.
#
function upload_images() {
	clip=""
	
	# loop through arguments
	for file do
		# upload the image
		response=$(upload_image "$file")
		url=""

		# get image url link
		grep -qo '"status":200' <<< "$response"  &&  url=$(get_value_from_response "$response" "link" | sed -e 's/\\//g')

		if [ -z "$url" ]; then
			echo "Upload failed for $file:  "$(get_value_from_response "$response" "error") >&2
			errors=true
		else 
			# output the imgur URL
			printf '%s    (Delete Hash = %s)\n' "$url" $(get_value_from_response "$response" "deletehash")

			# append the URL to a string so we can put them all on the clipboard later
			clip="$clip$url
		"
		fi
	done

	# copy the URLs to the clipboard (if the user has xsel or xclip installed)
	if [ $DISPLAY ]; then
		{ type xsel >/dev/null 2>/dev/null && echo -n $clip | xsel --input --clipboard; } \
			|| { type xclip >/dev/null 2>/dev/null && echo -n $clip | xclip -sel "clip"; } \
			|| echo "Haven't copied to the clipboard:  no xsel or xclip" >&2
	else
		echo "Haven't copied to the clipboard:  no \$DISPLAY" >&2
	fi
}


function delcandy () {
echo -e '\e[1;31m' 
echo "        ┌───────────────────────────────────┐"
echo "        │    Deleting Image From Imgur!     │ "
echo "        └───────────────────────────────────┘"
echo "       ╱"
echo "   ▀▄   ▄▀"
echo -e "  ▄█▀███▀█▄ "
echo -e " █▀███████▀█"
echo -e " ▀ ▀▄▄ ▄▄▀ ▀"
echo -e '\e[1;37m'
}

tput setaf 3
#
# Deletes the images corresponding to the supplied deletehashes.
#
function delete_images() {
	# ignore the '-d' argument
	shift
	
	for deletehash do
		# try to delete the image
		response=$(curl_imgur -X DELETE "https://api.imgur.com/3/image/""$deletehash")
		
		# was the operation successful?
		if [ -z $(grep -o '"status":200' <<< "$response") ]; then
			echo "Deletion failed for $deletehash:  "$(get_value_from_response "$response" "error") >&2
			errors=true
		else
			echo "Deletion OK:  $deletehash" >&2
		fi
	done
}



# check curl is available
type curl >/dev/null 2>/dev/null || {
	echo "Couln't find curl, which is required." >&2
	exit 17
}

# check arguments
if [ "$1" = "-h" -o "$1" = "--help" ]; then
	usage
	exit 0
elif [ "$1" = "-v" -o "$1" = "--version" ]; then
	echo "Version:  $version"
	exit 0
elif [ $# == 0 ]; then
	echo "No file specified" >&2
	echo "" >&2
	usage
	exit 16
fi


errors=false
if [ "$1" = "-d" -o "$1" = "--delete" ]; then
        delcandy
	delete_images "$@"
else
        candy
	upload_images "$@"
fi

if $errors; then
	exit 1
fi