#!/bin/bash
###########################################################
##                      TM Rename Tool                   ##
## Created by TheeMahn: <theemahn@ultimateedition.info>  ##
## Licensed under GNU GPL v3 or later, at your option.   ##
##       http://www.gnu.org/licenses/gpl.html            ##
###########################################################
#
# TMRename is a part of the tm-tools package.
# Many of the tools are heavy and are not
# intended to be ran by the common user.
# The tools are typically geared for the admininstrator.
# please see man tmtools for more info.
#
# http://ultimateedition.info
VERSION="1.0-2"
id=0
# set colors so errors etc. stand out.

if [[ -f "ultimate-common" ]]; then
	source ultimate-common
elif [[ -f "/usr/share/ultimate_edition/ultimate-common" ]]; then
	source /usr/share/ultimate_edition/ultimate-common
else
	echo "No Ultimate Edition common source. Please install ultimate-edition-common."
	exit 1;
fi


function Dupes {
ls * > tmp.txt 2>/dev/null
cat tmp.txt | while read FILE
do
filename=$(basename $FILE)
extension=${filename##*.}
filename2=${filename%.*}
Encapsulate "Filename:" $filename
Encapsulate "EXT:" $extension
Encapsulate "Filename2:" $filename2
#Toss a little eyecandy
  echo -e -n "${txtwht}======================="
  RR=0; DLENGTH=`expr length $FILE`; while [ $RR -le $DLENGTH ]; do echo -n "="; RR=RR+1; done; echo;
  echo "Beginning extraction of "$FILE
  echo -n "======================="
  RR=0; DLENGTH=`expr length $FILE`; while [ $RR -le $DLENGTH ]; do echo -n "="; RR=RR+1; done; echo;
done
}


function Tag {
#re-write is coming of this entire section to allow it to not only allow individual files, but broadbased.  I did not initally write this section, but will re-write this entire section.  We are deving powerful tools at least in the cli, will write the gui to correnspond.  We want results & now, how can you advance software without that mode of thinking?  Does anyone care if I trash a Terabyte at a time in testing?  I now understand why I have tons of space.  Testing...

FILE=$2
for FILE in *.{Avi,Mov,Mpeg,Mpg,Mkv,Mp4,M4v}
do
  DIR="${FILE%.*}"
echo "$DIR"
	if [[ "$DIR" != "*" ]]; then
		if [[ "$2" != "" ]]; then
			echo "Tag '$FILE' with '$DIR'"
		else
### Define the variables.
	filename=$FILE
        DATE=`mediainfo "$filename" | grep "Recorded date" | awk -F" : " '{ print $2 }' | tr -d '\r' | sed -e 's/ /\_/' | rev | cut -b 10- | rev`
        TIME=`mediainfo "$filename" | grep "Recorded date" | awk -F" : " '{ print $2 }' | tr -d '\r' | sed -e 's/ /\_/' | cut -b 12- | rev | cut -b 4- | rev`
	LONGDATE=`date -d "$DATE" "+%B %d, %Y"`
	LONGTIME=`date -d "$TIME" "+%l:%M %p" |  sed -e 's/^[ \t]*//'`
	DURATION=`ffmpeg -i "$filename" 2>&1 | awk '/Duration:/{$4 gsub(/\:/," ") ;realseconds= $4; seconds = int($4); minutes= $3 ;hours= $2;totalsoundtrack = (seconds+(minutes*60)+(hours*3600)) $8 } END { print hours ":" minutes ":" realseconds}' | rev | cut  -b 5- | rev`
	ASPECT=`mediainfo "$filename" | grep "Display aspect ratio" | awk -F" : " '{ print $2 }' | tr -d '\r' | sed -e 's/[/]/\:/'`
       MKVNAME="$DATE"_"$TIME"
### Create an XBMC-compliant .nfo file
FTH=$DIR
echo $FTH
echo "<episodedetails>
        <title>$FTH</title>
        <rating></rating>
        <season></season>
        <episode></episode>
        <plot>This video was recorded on $LONGDATE at $LONGTIME.</plot>
        <credits></credits>
        <director></director>
        <aired>$DATE</aired>
	<time>$TIME</time>
	<runtime>$DURATION</runtime>
</episodedetails>" > "$FTH".nfo

echo "" >> "$FTH".nfo
echo "========== ORIGINAL FILE INFO ==========" >> "$FTH".nfo
echo "" >> "$FTH".nfo

mediainfo "$filename" >> "$FTH".nfo

### Create an XBMC-compliant video thumbnail

if [[ "$ASPECT" == "4:3" ]]; then
        THUMBSIZE="640x480!"
   else
	THUMBSIZE="854x480!"
fi

ffmpegthumbnailer -i "$filename" -o temp.jpg -s 854
convert -resize "$THUMBSIZE" temp.jpg "$FTH".jpg
mv "$FTH".jpg "$FTH".tbn
			echo "Tag '$FILE' with '$DIR'"
			#mkvpropedit Star.Wars-Episode.1.The.Phantom.Menace.1999.720p.Bluray.Mkv --edit info --set "title=Star.Wars-Episode.1.The.Phantom.Menace" was going to actually impregnate the file, lets comply / keep the users happy.
	fi
fi
done
}
#echo $2 $3 $4

#if [[ $2 != '' ]]; then
#filename=$2
#echo "Tagging: "$filename
#extension=${filename##*.}
#FTH=${filename%.*}
### Is the source interlaced?
#echo -n "Is the source interlaced? [y/N]"
#read -n 1 c

#if [[ "$c" == "y" ]]; then
### mencoder deinterlacing options
#	OPTIONS="-vf yadif=3:1 -ofps 60000/1001"
#	FPS="60"
#	echo ""
#	echo "60i - I will deinterlace and encode at $FPS frames per second."
#else
#	OPTIONS=""
# 	FPS="30"
#	echo ""
#	echo "30p - I don't need to deinterlace and I will encode at $FPS frames per second."
#fi

#while [[ $# != 0 ]]; do

### Define the variables.
#	filename=$1
#        DATE=`mediainfo "$filename" | grep "Recorded date" | awk -F" : " '{ print $2 }' | tr -d '\r' | sed -e 's/ /\_/' | rev | cut -b 10- | rev`
#        TIME=`mediainfo "$filename" | grep "Recorded date" | awk -F" : " '{ print $2 }' | tr -d '\r' | sed -e 's/ /\_/' | cut -b 12- | rev | cut -b 4- | rev`
#	LONGDATE=`date -d "$DATE" "+%B %d, %Y"`
#	LONGTIME=`date -d "$TIME" "+%l:%M %p" |  sed -e 's/^[ \t]*//'`
#	DURATION=`ffmpeg -i "$filename" 2>&1 | awk '/Duration:/{$4 gsub(/\:/," ") ;realseconds= $4; seconds = int($4); minutes= $3 ;hours= $2;totalsoundtrack = (seconds+(minutes*60)+(hours*3600)) $8 } END { print hours ":" minutes ":" realseconds}' | rev | cut  -b 5- | rev`
#	ASPECT=`mediainfo "$filename" | grep "Display aspect ratio" | awk -F" : " '{ print $2 }' | tr -d '\r' | sed -e 's/[/]/\:/'`
 #       MKVNAME="$DATE"_"$TIME"

### Debugging: Uncomment these lines and the script will tell you what it is thinking.
#echo $filename
#echo "Date is $DATE"
#echo "Time is $TIME"
#echo "Base file name: $MKVNAME"
#echo "Long date is $LONGDATE"
#echo "Long time is $LONGTIME"
#echo "This video was recorded on $LONGDATE at $LONGTIME."
#echo "This video's runtime is: $DURATION"
#echo "This video should be displayed with a $ASPECT aspect ratio"
#echo ""; shift; done; exit

### Encode the video using x264 and the source-based deinterlacing options
#mencoder $OPTIONS -noskip -aspect $ASPECT -of rawvideo -o video.h264 -nosound -ovc x264 -x264encopts bitrate=3000:threads=auto:bframes=3:partitions=i4x4,i8x8,p8x8,b8x8:8x8dct:me=hex:subq=7:turbo=2:frameref=3:deblock=-1,-1:weight_b:trellis=2:mixed_refs:level=3.1:vbv_maxrate=17500:vbv_bufsize=14000:qblur=0.5 "$filename"

### Encode the audio to Ogg Vorbis using ffmpeg pipe to vorbistools because ffmpeg's Vorbis encoder is terrible.
#ffmpeg -i "$filename" -f wav - | oggenc -q 5 - -o audio.ogg

### Mux the audio and video together
#mkvmerge --default-duration 0:"$FPS"000/1001fps -o "$FTH".mkv video.h264 -D audio.ogg

### Create an XBMC-compliant .nfo file
#echo "<episodedetails>
#        <title>$FTH</title>
#        <rating></rating>
#        <season></season>
#        <episode></episode>
#        <plot>This video was recorded on $LONGDATE at $LONGTIME.</plot>
#        <credits></credits>
#        <director></director>
#        <aired>$DATE</aired>
#	<time>$TIME</time>
#	<runtime>$DURATION</runtime>
#</episodedetails>" > "$FTH".nfo

#echo "" >> "$FTH".nfo
#echo "========== ORIGINAL FILE INFO ==========" >> "$FTH".nfo
#echo "" >> "$FTH".nfo

#mediainfo "$filename" >> "$FTH".nfo

### Create an XBMC-compliant video thumbnail

#if [[ "$ASPECT" == "4:3" ]]; then
#        THUMBSIZE="640x480!"
#   else
#	THUMBSIZE="854x480!"
#fi

#ffmpegthumbnailer -i "$filename" -o temp.jpg -s 854
#convert -resize "$THUMBSIZE" temp.jpg "$FTH".jpg
#mv "$FTH".jpg "$FTH".tbn

### Clean up temporary files
#rm temp.jpg
#shift
#done



#for FILE in *.{Avi,Mov,Mpeg,Mpg,Mkv,Mp4,M4v}
#do
#  DIR="${FILE%.*}"
#echo "$DIR"
#	if [[ "$DIR" != "*" ]]; then
#		if [[ "$2" != "" ]]; then
#			echo "Tag '$FILE' with '$DIR'"
#		else
#			echo "Tag '$FILE' with '$DIR'"
			#mkvpropedit Star.Wars-Episode.1.The.Phantom.Menace.1999.720p.Bluray.Mkv --edit info --set "title=Star.Wars-Episode.1.The.Phantom.Menace"
#		fi
#	fi
#done
#else
#if [[ $3 == "-Y" ]]; then
#echo "failure"
#fi
#fi
#}

function Sort {
echo -e "${bldwht}TheeMahn's Rename - Sort function invoked.${txtwht}"
case $2 in
	-f ) FD='*.*';;
	-d ) FD="*/";;
	* ) echo 'Invalid option '$2;exit 0;;
esac
echo 'Pattern: '$FD
for FILE in $FD

do
	    dirs="${FILE%.*}"
	    name=`echo "$FILE"|sed 's/ -.*//'`
	    letter=`echo "$name"|cut -c1`
	if [[ "$dirs" != "*" && "$dirs" != "*/" ]]; then
	id=$((id +1))
		dir="$letter/$dirs"
		if [[ "$3" == "-Y" ]]; then
			echo -e "${txtcyn}Making directory: "'"'"$dirs/"'"'"${bldred}"
			echo -e "${txtcyn}Moving: mv "'"'"$FILE"'"' '"'"$dirs/"'"'"${bldred}"
			mkdir -p "$dirs"
			`mv -f "$FILE" "$dirs/"`
		else
			echo -e "${txtcyn}mkdir "'"'"$dirs/"'"'"${bldred}"
			echo -e "${txtcyn}mv "'"'"$FILE"'"' '"'"$dirs/"'"'"${bldred}"
		fi
	fi
done
if [[ "$3" != "-Y" ]]; then
	echo -e "${txtgrn}Folder(s) / Files(s) to be effected: "$id
else
	echo -e "${txtgrn}Folder(s) / Files(s) have been effected: ${txtrst}"$id
fi
}

function Subs {
echo -e "${bldwht}TheeMahn's Rename - Sub directory function invoked.${txtwht}"
case $2 in
	-f ) FD='*.*';;
	-d ) FD="*/";;
	* ) echo -e "${bldred}Invalid option: "$2"${txtrst}";exit 0;;
esac
echo 'Pattern: '$FD
for FILE in $FD

do
echo $FILE
done
# Otherwise or the user answered yes.
cat tmp.txt | while read FILE
do
target=$(echo "$FILE" | sed -e "s/\///g")
FTR=$(find $FILE -type f -name '*')
EXT=$(echo "$FTR"|awk -F . '{print $NF}')
if [[ "$FTR" != "$FILE$target.$EXT" ]]; then
id=$((id +1))
	if [[ "$2" != "-Y" ]]; then
		echo 'mv "'$FTR'"' '"'$FILE$target.$EXT'"'
	else
		echo -e "${txtgrn}Moving:" mv '"'"$FTR"'"' '"'"$FILE$target.$EXT"'"'
		#`mv -f "$FTR" "$FILE$target.$EXT"`
	fi
fi
done
if [[ "$3" != "-Y" ]]; then
	echo -e "${txtgrn}Folder(s) / Files(s) to be effected: "$id
else
	echo -e "${txtgrn}Folder(s) / Files(s) have been effected: ${txtrst}"$id
fi
}

#File / Directory Manipulation
#=============================
function CustomAdd {
echo $1 $2 $3 $4
if [[ "$2" == "-f" ]]; then
	FD="*"
else
	FD="./*/"
fi
echo $4
case "$1" in
	-ab ) SS="s/^/${3}/";;
	-ae ) echo "Add to ending";;
	* ) exit 0;;
esac
if [[ "$3" == "" ]]; then
	exit 0

else

for dir in $FD;
do
SEDED=$(echo $dir | sed "s/${3}//g" | sed $SS)
   case "$dir" in
     * )  if [[ "$dir" != "$SEDED" ]]; then
	#:Set auto increment ID:#
	id=$((id +1))
	if [[ "$4" != "-Y" ]]; then
	echo -e "${txtwht}"mv '"'"$dir"'"' '"'"$SEDED"'"'
	else
	`mv -f "$dir" "$SEDED"`
	fi
	fi ;;
   esac
done
if [[ "$4" == "-Y" ]]; then
	echo -e "${txtgrn}Folder(s) / Files(s) to be effected: "$id
else
	echo -e "${txtgrn}Folder(s) / Files(s) have been effected: ${txtrst}"$id
fi
fi
}

function Custom {
echo $1 $2 $3
if [[ "$2" == "-f" ]]; then
	FD="*"
else
	FD="./*/"
fi

if [[ "$3" == "" ]]; then
	exit 0

else

for dir in $FD;
do
SEDED=$(echo $dir | sed "s/${3}//g")
   case "$dir" in
     * )  if [[ "$dir" != "$SEDED" ]]; then
	#:Set auto increment ID:#
	id=$((id +1))
	if [[ "$4" != "-Y" ]]; then
	echo -e "${txtwht}"mv '"'"$dir"'"' '"'"$SEDED"'"'
	else
	`mv -f "$dir" "$SEDED"`
	fi
	fi ;;
   esac
done
if [[ "$3" != "-Y" ]]; then
	echo -e "${txtgrn}Folder(s) / Files(s) to be effected: "$id
else
	echo -e "${txtgrn}Folder(s) / Files(s) have been effected: ${txtrst}"$id
fi
fi
}

function Process {
echo -e "${bldwht}TheeMahn's Rename - Process function invoked.${txtwht}"
if [[ "$1" == "-f" ]]; then
FD="*"
else
FD="./*/"
fi
if [[ "$2" == "" ]]; then
for dir in $FD;
do
if [[ "$1" == "-d" ]]; then
SEDED=$(echo $dir  | sed 's/\(.*\)/\L\1/' | sed 's/720p.*$/720p\//' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/ /\./g' | sed 's/xvid//i' | sed 's/\[/\.\[/i' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/\.-//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/_/\./g' | sed 's/\.\.\.*/\./i' | sed 's/\.\/$/\//' | sed 's/Dvdrip$/Dvdrip/g')
else
SEDED=$(echo $dir  | sed 's/\(.*\)/\L\1/' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/ /\./g' | sed 's/xvid//i' | sed 's/\[/\.\[/i' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/\.-//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/_/\./g' | sed 's/\.\.\.*/\./i' | sed 's/\.\/$/\//' | sed 's/Dvdrip$/Dvdrip/g')
fi
   case "$dir" in
     * )  if [[ "$dir" != "$SEDED" ]]; then
	#:Set auto increment ID:#
	id=$((id +1))
	echo -e "${txtwht}"mv '"'"$dir"'"' '"'"$SEDED"'"'
	fi ;;
   esac
#echo 'SEDED: '$SEDED

done
if [[ "$2" != "-Y" ]]; then
	echo -e "${txtgrn}Folder(s) / Files(s) to be effected: "$id
else
	echo -e "${txtgrn}Folder(s) / Files(s) have been effected: "$id
fi
else
for dir in $FD;
do
SEDED=$(echo $dir  | sed 's/\(.*\)/\L\1/' | sed 's/720p.*$/720p\//' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/ /\./g' | sed 's/xvid//i' | sed 's/\[/\.\[/i' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/\.-//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/_/\./g' | sed 's/\.\.\.*/\./i' | sed 's/\.\/$/\//' | sed 's/Dvdrip$/Dvdrip/g')
   case "$dir" in
     * )  if [[ "$dir" != "$SEDED" ]]; then
	#:Set auto increment ID:#
	id=$((id +1))
	echo -e "${txtgrn}Moving:" mv '"'"$dir"'"' '"'"$SEDED"'"'
	`mv -f "$dir" "$SEDED"`
	#`mv '"$dir"' '"$SEDED"'`

	fi ;;
   esac
#echo 'SEDED: '$SEDED

done
if [[ "$2" != "-Y" ]]; then
	echo -e "${txtgrn}Folder(s) / Files(s) to be effected: "$id
else
	echo -e "${txtgrn}Folder(s) / Files(s) have been effected: ${txtrst}"$id
fi
fi
}
#sed 's/\[^\]*//g'
#Lowercase
#sed 's/\(.*\)/\L\1/'
#Cap firstletter
#sed 's/\<./\U&/g'
#Slew
#sed 's/\.\.*/./g' | sed 's/\[/\.\[/i' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/\.-//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g'
#Strip periods
#sed 's/\.\.\.*//i'
#Last period
#sed 's/\.\/$/\//'
function Help {
	echo -e "${txtwht}

TMRename $VERSION
==============

TMRename is a part of the tm-tools package.  Many of the tools are heavy and are not
intended to be ran by the common user.  The tools are geared for the admininstrator.
please see man tmtools for more info.

tmrename -<COMMAND> <[option] [file/folder]> [option] [option]

	possible commands...
	-v	--version		dump version info
	-f	--files			Renames file(s)
	-s	--sort			Makes folder abc etc based on filename(s) and moves them
	-S	--sub-directory		Renames folders as file in subdirectory.
	-t	--tag			Tag file to embed info as filename implies.
	-ab	--add-begining		Add a custom field to begining of filename
	-ae	--add-ending		Add a custom field to the end of filename prior to extention.
	-c	--custom		This is the heaviest command you can implement please read the manual.
	-d	--directories		Process directories instead of files.
	-D	--dupes			Scan for duplicate files.
	-Y	--YES			Danger Will Robinson... when used will implement all changes displayed.
	-h	--help			this help message

	Useage files;
	tmrename -f

	Will process all files with default settings.
	Showing output of commands to be preformed. Adding -Y as
	a secondary switch or fourth switch in custom will
	preform the actions for you, please use ${bldred}CAUTION${txtwht}, review before
	implementing this switch.

	Useage Help;
	tmrename -h

	Displays this message. For futher information please refer to the manpages.

	man tmrename
	"
	echo -e "${txtgrn}"
	echo -e "Example 1: tmrename -f"
	echo -e "${txtwht}Will scan all file(s) and output commands to be preformed to renaame
	the file(s) unix friendly."

	echo -e "${txtgrn}"
	echo -e "Example 2: tmrename -f Indiana.Jones.1.1981.Raiders.Of.The.Lost.Ark.Mkv"
	echo -e "${txtwht}Will make a folder called Indiana.Jones.1.1981.Raiders.Of.The.Lost.Ark and move the file into that folder."
	echo -e "${txtgrn}"
	echo -e "Example 3: tmrename -s -f"
	echo -e "${txtwht}Will scan all file(s) in current folder and copy pasteably show the commands to create the folder and move appropriatley.
	A -Y after will do all for you as said above please use ${bldred}CAUTION${txtwht}."
echo "
GNU tmrename home page: <http://www.ultimateedition.info/>.
E-mail bug reports to: <theemahn@ultimateedition.info>.
Be sure to include the word tmrename somewhere in the Subject: field."
	exit 0
}

function Version {
echo "TMRename $VERSION
==============
GNU repomaster home page: <http://www.ultimateedition.info/>.
E-mail bug reports to: <theemahn@ultimateedition.info>.
Be sure to include the word repomaster somewhere in the Subject: field."
}

    case "$1" in
      -h|--help|-\?) Help; exit 0;;
      -v|--version) Version; exit 0;;
      -f|--files) Process $1 $2; exit 0;;
      -d|--directories) Process $1 $2; exit 0;;
      -c|--custom) Custom $1 $2 $3 $4; exit 0;;
      -ab|--add-begining) CustomAdd $1 $2 $3 $4; exit 0;;
      -D|--dupes) Dupes $1 $2; exit 0;;
      -ae|--add-ending) CustomAdd $1 $2 $3 $4; exit 0;;
      -t|--tag) Tag $1 $2 $3; exit 0;;
      -s|--sort) Sort $1 $2 $3; exit 0;;
      -S|--sub-directories) Subs $1 $2 $3; exit 0;;
      *) Help; exit 0;;
    esac
