#!/bin/bash

#START=$(date +%s)

#check if mythbackend is running and was just started
for i in 1 2
do
if [ `cat /service/mythbackend/supervise/pid` ]
then
    now=$(date +%s)
    mythbackendStartTime=`stat -c %Y /service/mythbackend/supervise/pid`
    if [[ $(( $now - $mythbackendStartTime )) -lt 59 ]]
    then
        #echo "mythbackend started less than a minute ago. Sleeping..."
        sleep 60
    fi
else
    #echo "mythbackend not running. exiting."
    exit
fi
done

if [ -f /usr/share/mythtv/contrib/user_jobs/mythlink.pl ]
then
    recdir="/data/storage/disk0/media/recordings"
    tmprecdir="/data/storage/disk0/media/tmp/recordings"
    rm -r $tmprecdir
    su - mythtv -c "perl /usr/share/mythtv/contrib/user_jobs/mythlink.pl --format '%Ct/%U/%T/%T %- S%ssE%ep %- %oY-%om-%od = %S' --link '$tmprecdir'"

    # rename category_types (%Ct) from numbers to names
    for cattype in $tmprecdir/*
    do
        if [ $cattype == "$tmprecdir/1" ]
        then
            rsync -a "$cattype/" "$tmprecdir/Movies"
            rm -r "$cattype"
        elif [[ $cattype == "$tmprecdir/2" ]] || [[ $cattype == "$tmprecdir/4" ]]
        then
            rsync -a "$cattype/" "$tmprecdir/TV Shows"
            rm -r "$cattype"
        elif [ $cattype == "$tmprecdir/3" ]
        then
            rsync -a "$cattype/" "$tmprecdir/Sports"
            rm -r "$cattype"
        else
            #ignore Movies, TV Shows, Sports. Move all others to TV Shows
            if [[ $cattype != "$tmprecdir/Movies" ]] && [[ $cattype != "$tmprecdir/TV Shows" ]] && [[ $cattype != "$tmprecdir/Sports" ]]
            then
                if [ ! -d "$tmprecdir/TV Shows" ]
                then
                    mkdir "$tmprecdir/TV Shows"
                fi
                rsync -a "$cattype" "$tmprecdir/TV Shows"
                rm -r "$cattype"
            fi
        fi
    done

    #delete Deleted recgroup
    for link in $tmprecdir/**/Deleted
    do
        rm -r "$link"
    done

    #move all links in recgroup dirs out to parent dir
    for recgroup in $tmprecdir/**/*
    do
        if [ -d "$recgroup" ]
        then
            cd "$recgroup"
            rsync -a "$recgroup/" ..
            cd "$tmprecdir"
            rm -r "$recgroup"
        fi
    done

    #replace SE if no season/episode is in myth
    for link in $tmprecdir/**/**/*\ -\ SE\ -\ *
    do
        newlink=`echo "$link" | sed 's/ - SE - / - /'`
        mv "$link" "$newlink"
    done
    #replace SEyy if no season is in myth
    for link in $tmprecdir/**/**/*\ -\ SE[0-9][0-9]\ -\ *
    do
        newlink=`echo "$link" | sed 's/ - SE/ - S00E/'`
        mv "$link" "$newlink"
    done
    #replace SyyE if no episode is in myth
    for link in $tmprecdir/**/**/*\ -\ S[0-9][0-9]E\ -\ *
    do
        newlink=`echo "$link" | sed 's/E - /E00 - /'`
        mv "$link" "$newlink"
    done
    #replace blank original date
    for link in $tmprecdir/**/**/*\ -\ 0000-00-00\ -\ *
    do
        newlink=`echo "$link" | sed 's/ - 0000-00-00 - / - /'`
        mv "$link" "$newlink"
    done
    #add dash pt suffix if filename before the subtitle is the same
    #so that plex will scan and include in library
    uniqs="$(ls $tmprecdir/**/**/* | sed 's/ = .*//' | sort | uniq -d)"
    SAVEIFS=$IFS
    IFS=$'\n'
    for link in $uniqs
    do
        i=1
        for dup in `ls -v $link*`
        do
            newlink=`echo "$dup" | sed "s/ = /-pt$i = /"`
            mv "$dup" "$newlink"
            i=$((i+1))
        done
    done
    IFS=$SAVEIFS

    #change symlinks mtime to match the file it is linked to
#    for link in $tmprecdir/**/*
#    do
#        if [ -L "$link" ]
#        then
#            file=`readlink "$link"`
#            touch -hr "$file" "$link"
#        fi
#    done

    #sync tmprecdir to recdir
    #rsync -aOP --delete --ignore-existing "$tmprecdir/" "$recdir/"
    rsync -aO --delete "$tmprecdir/" "$recdir/"

    #check if plex media server is running
    if [[ `pidof "Plex Media Server"` ]]
    then
        #get plex section and update
        script -q -c '/usr/LH/bin/plexmediascanner.sh -l' | grep -i myth | cut -d: -f1 | while read -r line
        do
            /usr/LH/bin/plexmediascanner.sh --scan --refresh --section $line
        done
    fi
fi

#END=$(date +%s)
#DIFF=$(( $END - $START ))
#echo "It took $DIFF seconds"
