#!/bin/bash

## Set color 
Red="\e[31m"
Green="\e[32m"
Yellow="\e[33m"
NoColor="\e[0m"


## help
Usage(){

	echo "$(basename "${0}") [mp4 file path]"
	exit
}

Action () {

	echo -ne "$1 : "
	shift
	ResStdout=$("${@}" 2> /dev/null)
	Res=$?
	if [[ ${Res} -eq 0 ]]
		then
			echo -e "[${Green}OK${NoColor}] ${ResStdout}"
		else
			if [[ ${Res} -eq 255 ]]
				then
					echo -e "[${Yellow}N/A${NoColor}] ${ResStdout}"
				else
					echo -e "[${Red}Failed${NoColor}] ${ResStdout}" 
					exit
			fi
	fi
}

CheckFile() {
	Return=0
	[[ ! -e ${File} ]] && ((Return++))
	file "${File}"| grep -q "MP4"
	Res=${?}
	[[ ${Res} -ne 0 ]] && ((Return++))
	return "${Return}"
}

CreateEnv() {
	if [[ ! -d "${BaseDir}" ]]
		then
			mkdir -p "${BaseDir}"
			Return=$?
		else
			Return=1
			echo " - Directory \"${BaseDir}\" exist"
	fi
	return "${Return}"
}

Generate() {
	ffmpeg -i "${File}" -pix_fmt bgr8  "${BaseDir}"/"${BaseName}"_%04d.bmp &> /dev/null
	Res=${?}
	if [[ "${Res}" -eq 0 ]]
		then
			Return=0
			echo "- $(find "${BaseDir}" -name "*.bmp" | wc -l) Files generated"
		else
			Return=1
			rm -Rf "${BaseDir}"
			echo " - FFmpeg FAILED - ${BaseDir} deleted"
	fi
	return ${Return}
}

[[ -z $1 ]] && Usage

# Env
File=$(realpath "${1}")
BaseName=$(basename "${1}" | sed 's/\.mp4$//g')
BaseDir="$(xdg-user-dir PICTURES)/dwm-anime-wallpaper/${BaseName}"

# Main
Action "Check File" CheckFile
Action "Create Env" CreateEnv
Action "Generate bmp files" Generate
