#!/usr/bin/env bash

# compatibility: jellyfin-independant

# Edit these variables to point to your public web root and jellyfin media location.
# This script was built to run on my nginx reverse proxy via using a commonly shared jellyfin
# media storage mount, however if this was ran from the Jellyfin box an additional benefit
# would be refreshing file and directory traversal cache for faster library scans

nginx_www='/var/www/travisflix.com'
opendir_www='/var/www/nixscripts'
jf_media='/mnt/mergerfs/media'

# Check if the mergerfs mount exists
if [[ $(mountpoint "$jf_media") ]]; then

    # exit script if variable is empty
    [ -z "$nginx_www" ] && { echo 'Error: variable nginx_www is not set or empty'; exit 1; }

    # refresh public text files with media index
    cd "$jf_media"
    find "$jf_media/video-movies" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort > $nginx_www/movies.txt
    find "$jf_media/video-shows" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort > $nginx_www/shows.txt
    echo >> $nginx_www/shows.txt
    tree --noreport -d --charset=en_US.utf8 "$jf_media/video-shows" >> $nginx_www/shows.txt
    find "$jf_media/video-standup" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort > $nginx_www/standup.txt
    find "$jf_media/video-tennis" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort --reverse > $nginx_www/tennis.txt
    find "$jf_media/video-motogp" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort --reverse > $nginx_www/motogp.txt
    echo >> $nginx_www/motogp.txt
    tree --noreport --charset=en_US.utf8 "$jf_media/video-motogp" >> $nginx_www/motogp.txt
    find "$jf_media/video-formula1" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort --reverse > $nginx_www/formula1.txt
    echo >> $nginx_www/formula1.txt
    tree --noreport --charset=en_US.utf8 "$jf_media/video-formula1" >> $nginx_www/formula1.txt

    find "$jf_media/video-tech" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort > $nginx_www/tech.txt
    cp -f $nginx_www/movies.txt $opendir_www/
    cp -f $nginx_www/shows.txt $opendir_www/
    cp -f $nginx_www/standup.txt $opendir_www/
    cp -f $nginx_www/formula1.txt $opendir_www/
    cp -f $nginx_www/motogp.txt $opendir_www/
    cp -f $nginx_www/tech.txt $opendir_www/

else
    exit 1
fi

