#!/usr/bin/env bash
#
# uguush - command-line uploader for uguu.se and others
#

## CONFIGURATION

# colors
c0="$(tput sgr0)"
c1="$(tput setaf 1)"
c2="$(tput setaf 2)"

# filename to use for screenshots
localTemp="$(mktemp)"

# screenshot functions
capFullscreen() {
	localFile="${localTemp}.png"
	mv "${localTemp}" "${localFile}"
	maim -u "${localFile}"
}

capSelection() {
	localFile="${localTemp}.png"
	mv "${localTemp}" "${localFile}"
	maim -s -u "${localFile}"
}

capWindow() {
	localFile="${localTemp}.png"
	mv "${localTemp}" "${localFile}"
	maim -i $(xprop -root _NET_ACTIVE_WINDOW | grep -o '0x.*') -u
}

# delay
delaySeconds='0'

# hosts and shorteners
host='uguu'
shortener=
hosts='uguu teknik 0x0 ptpb mixtape lewd fiery doko'
shorteners='waaai 0x0'

## FUNCTIONS

depends() {
	if [ ! type curl &> /dev/null ]; then
		echo >&2 "Checking for curl... [${c1}FAILED${c0}]"
		echo 'curl not found.'
		exit 1
	fi
}

usage() {
	cat << EOF

uguush - upload to various file hosts

Usage:
	$(basename "${0}") [options]

Options:
	-d		Delay the screenshot by the specified number of seconds.
	-f		Take a fullscreen screenshot.
	-h		Show this help message.
	-o		Select a host to use. Can be uguu, teknik, 0x0, ptpb, mixtape, lewd, fiery or doko.
	-p <path>	Custom path to save the image to. Saves the image as "%Y-%m-%d %H-%M-%S.png".
	-s		Take a selection screenshot.
	-u <file>	Upload a file.
	-x		Do not notify dbus, update the log, or modify the clipboard.
	-w		Take a screenshot of the current window.
	-S		Select a shortener to use. Can be waaai or 0x0.
	-l <url>	Upload the file at the provided URL.

EOF
}

delay() {
	for (( i=delaySeconds; i > 0; --i )); do
		echo "${i}..."
		sleep 1
	done
}

screenshot() {
	if [ "${doFullscreen}" ]; then
		capFullscreen
	elif [ "${doSelection}" ]; then
		capSelection &> /dev/null
		if ! [ -s "${localFile}" ]; then
			$(rm "${localFile}" 2> /dev/null)
			exit
		fi
	elif [ "${doWindow}" ]; then
		capWindow
	elif [ "${doURL}" ]; then
		if [ -f "/usr/share/mime/globs" ]; then
			urlExtension="$(curl -sf --head "${remoteURL}" | grep 'Content-Type: ' | head -1 | grep -Po '(?<=\ )[^\;]*')"
			urlExtension="$(echo "${urlExtension}" | sed -e "s/\\r//")"
			urlExtension="$(cat /usr/share/mime/globs | grep "${urlExtension}" | sort -r | head -1 | grep -Po '(?<=\.)[^\n]*')"
		else
			urlExtension="$(basename ${remoteURL})"
			urlExtension=${urlExtension#*.}
		fi
		localFile="${localTemp}.${urlExtension}"
		$(curl -sf "${remoteURL}" > "${localFile}")
	fi
}

upload() {
	for (( i = 1; i <= 3; i++ )); do
		echo -n "Try #${i}... "

		case "${host}" in
			teknik) hostURL='https://api.teknik.io/v1/Upload' ;;
			0x0) hostURL='https://0x0.st/' ;;
			uguu) hostURL='https://uguu.se/api.php?d=upload-tool' ;;
			ptpb) hostURL='https://ptpb.pw/' ;;
			mixtape) hostURL='https://mixtape.moe/upload.php' ;;
			lewd) hostURL='https://lewd.se/api.php?d=upload-tool' ;;
			fiery) hostURL='https://safe.fiery.me/api/upload' ;;
			doko) hostURL='https://doko.moe/upload.php' ;;
		esac

		case "${shortener}" in
			waaai) shortenerURL='https://api.waa.ai/shorten' ;;
			0x0) shortenerURL='http://0x0.st/' ;;
			ptpb) shortenerURL='https://ptpb.pw/u'
		esac

		if [ "${host}" = 'uguu' ]; then
			uploadResult="$(curl -sf -F file="@${localFile}" "${hostURL}")"
		elif [ "${host}" = '0x0' ]; then
			uploadResult="$(curl -sf -F file="@${localFile}" "${hostURL}")"
		elif [ "${host}" = 'teknik' ]; then
			uploadResult="$(curl -sf -F file="@${localFile}" "${hostURL}")"
			uploadResult="${uploadResult##*url\":\"}"
			uploadResult="${uploadResult%%\"*}"
		elif [ "${host}" = 'mixtape' ]; then
			uploadResult="$(curl -sf -F files[]="@${localFile}" "${hostURL}")"
			uploadResult="$(echo "${uploadResult}" | grep -Po '"url":"[A-Za-z0-9]+.*?"' | sed 's/"url":"//;s/"//')"
			uploadResult="$(echo "${uploadResult//\\\//\/}")"
		elif [ "${host}" = 'ptpb' ]; then
			uploadResult="$(curl -sf -F c="@${localFile}" "${hostURL}")"
			uploadResult="${uploadResult##*url: }"
			uploadResult="${uploadResult%%$'\n'*}"
		elif [ "${host}" = 'lewd' ]; then
			uploadResult="$(curl -sf -F file="@${localFile}" "${hostURL}")"
		elif [ "${host}" = 'fiery' ]; then
			uploadResult="$(curl -sf -F files[]="@${localFile}" "${hostURL}")"
			uploadResult="$(echo "${uploadResult}" | grep -Po '"url":"[A-Za-z0-9]+.*?"' | sed 's/"url":"//;s/"//')"
		elif [ "${host}" = 'doko' ]; then
			uploadResult="$(curl -sf -F files[]="@${localFile}" "${hostURL}")"
			uploadResult="$(echo "${uploadResult}" | grep -Po '"url":"[A-Za-z0-9]+.*?"' | sed 's/"url":"//;s/"//')"
			uploadResult="$(echo "${uploadResult//\\\//\/}")"
		fi

		if [ "${shortener}" = 'waaai' ]; then
			tempResult="$(curl -sf -F url="${uploadResult}" "${shortenerURL}")"
			shortCode="${tempResult##*short_code\":\"}"
			shortCode="${shortCode%%\"*}"
			shortenerResult="https://waa.ai/${shortCode}"
			shortenerExtension="${tempResult##*extension\":}"
			shortenerExtension="${shortenerExtension%%\}*}"
			if [ "${shortenerExtension}" = 'true' ]; then
				shortenerExtension=${shortenerExtension##\"}
				shortenerExtension=${shortenerExtension%%\"}
				shortenerResult="${shortenerResult}.${shortenerExtension}"
			fi
		elif [ "${shortener}" = '0x0' ]; then
			shortenerResult="$(curl -sf -F shorten="${uploadResult}" "${shortenerURL}")"
		elif [ "${shortener}" = 'ptpb' ]; then
			shortenerResult="$(curl -sf -F c=@- "${shortenerURL}" <<< "${uploadResult}")"
		fi

		if [ "${shortener}" ]; then
			finalResult="${shortenerResult}"
		else
			finalResult="${uploadResult}"
		fi

		if [ "${?}" = 0 ]; then

			# copy to clipboard, log, and notify (unless $noComms is set)
			if [ ! "${noComms}" ]; then
					echo -n "${finalResult}" | xclip -selection primary
					echo -n "${finalResult}" | xclip -selection clipboard
					echo "$(date +"%D %R") | "${file}" | "${finalResult}"" >> ~/.uguush.log
					notify-send 'uguu~' "${finalResult}"
			fi
		fi

		echo "[${c2}OK${c0}]"
		echo "File has been uploaded: ${finalResult}"

		# if we took a screenshot, remove the temporary file
		if [ -z "${doFile}" ]; then
			rm "${localFile}"
		fi

		exit

	done
}

path() {
	if [ "${saveToPath}" = 'true' ]; then
		localFilename=$(date "+%Y-%m-%d %H-%M-%S")
		cp ${localFile} "${pathToSave}/${localFilename}.png"
	fi
}

## PARSE OPTIONS

while getopts :d:fhl:o:p:su:wxS: opt ;do
	case "${opt}" in
		d)
			# set delay value
			delaySeconds="${OPTARG}" ;;
		f)
			# take fullscreen shot
			doFullscreen='true' ;;
		h)
			# print help
			usage
			exit 0 ;;
		l)
			# set url to upload
			doURL='true'
			remoteURL="${OPTARG}" ;;
		o)
			# set host
			[[ "${hosts}" =~ "${OPTARG}" ]] && host="${OPTARG}" || exit 1 ;;
		p)
			# set path to save file
			saveToPath='true'
			pathToSave="${OPTARG}" ;;
		s)
			# take shot of selection
			doSelection='true' ;;
		u)
			# change $file to the specified file with -u
			doFile='true'
			localFile="${OPTARG}" ;;
		w)
			# take shot of current window
			doWindow='true' ;;
		x)
			# do not notify dbus, update log, or modify clipboard
			noComms='true' ;;
		S)
			# set shortener
			[[ "${shorteners}" =~ "${OPTARG}" ]] && shortener="${OPTARG}" || exit 1 ;;
		*)
			# print help and EXIT_FAILURE
			usage
			exit 1 ;;
	esac
done

# show usage if no arguments are given
if [ $# -lt 1 ]; then
	usage
	exit 1
fi

## EXECUTE FUNCTIONS

depends
delay
screenshot
path
upload

# if the program doesn't exit at the for-loop, the upload failed
echo 'File was not uploaded, did you specify a valid filename?'
