#!/bin/bash
# Generate iptv playlists for FVWM-Crystal
#
# Version:	1.0.1
# License: 	GPL 3+
#
# Author:	Dominuque Michel <dominique.c.michel@users.sourceforge.net>
#
# Description:
# Download the IPTV playlists from iptv-org and generate the playlists
# into $FVWMUSERDDIR/Playlists/IPTV. For use with mplayer for now.
#
# Syntax: just run it without argument when inside fvwm-crystal.

#DEBUG_SCRIPT="echo"
## Some checks {{{1
has() {
	case "$(command -v "$1" 2>/dev/null)" in
		alias*|"") return 1
	esac
}

# Print error message and exit.
_errx() {
	>&2 printf '\033[31;1merror :\033[m %s\n' "$1"
	exit 1
}

# Check if the needed dependencies are installed
for prog in sed grep wget; do
	! has "$prog" && dependencies_not_installed="${dependencies_not_installed}${prog}, "
done
[ -n "${dependencies_not_installed}" ] && _errx "Missing dependencies, please install: ${dependencies_not_installed%??}."

## variables {{{1
WGET_CMD="wget -O"
IPTV_ROOT_URI="https://iptv-org.github.io/iptv/"
IPTV_URI_SUFFIX=".m3u"

IPTV_CAT_DIR='categories'
IPTV_TMP_DIR="${FVWM_USERDIR}"/tmp/iptv
IPTV_PLAYLISTS_DIR="${FVWM_USERDIR}"/Playlists/IPTV

# Network check
GOAL="${IPTV_ROOT_URI}index${IPTV_URI_SUFFIX}"
if [[ $(wget -q --spider "${GOAL}"; echo $?) != 0 ]]; then
	_errx "No connection to ${GOAL}. Check it and re-run this script when ${GOAL} is avaible via internet."
fi

#source "${FVWM_CONFIGDIR}"/preferences/IPTV
if [[ ! -e "${FVWM_USERDIR}"/preferences/IPTVCatPlaylists ]]; then
	cp "${FVWM_SYSTEMDIR}"/preferences/IPTVCatPlaylists "${FVWM_USERDIR}"/preferences
fi
source "${FVWM_USERDIR}"/preferences/IPTVCatPlaylists
# ${DEBUG_SCRIPT} IPTV_CAT ${IPTVCatPlaylists}

# For an up-to-date list, see https://github.com/iptv-org/iptv/
# We don't want the xxx category here, because otherwise it is
# too easy to fool that script.
IPTV_REF_CATEGORIES=( animation auto business classic comedy cooking culture
	documentary education entertainment family general kids legislative
	lifestyle movies music news outdoor relax religious science
	series shop sports travel weather undefined )
# ${DEBUG_SCRIPT} IPTV_REF ${IPTV_REF_CATEGORIES[@]}

## Set the wanted categoriess and download them {{{1
for i in "${IPTV_REF_CATEGORIES[@]}" ; do
	if [[ "$(grep $i <<< ${IPTV_CATEGORIES_PLAYLISTS})" ]] ; then
		IPTV_TMP_CAT="${IPTV_TMP_CAT} $i"
	fi
done
# ${DEBUG_SCRIPT} TMP_CAT ${IPTV_TMP_CAT}

IPTV_CAT_PLAYLISTS=( ${IPTV_TMP_CAT} )
#IPTV_CAT_PLAYLISTS=( ${IPTV_TMP_CAT} ${IPTV_XXX_PLAYLISTS} )
# ${DEBUG_SCRIPT} IPTV_CAT_PLAYLISTS ${IPTV_CAT_PLAYLISTS[@]}
${DEBUG_SCRIPT} mkdir -p "${IPTV_TMP_DIR}"
mkdir -p "${IPTV_TMP_DIR}"
for i in "${IPTV_CAT_PLAYLISTS[@]}"; do
	${DEBUG_SCRIPT} ${WGET_CMD} "${IPTV_TMP_DIR}/${i}${IPTV_URI_SUFFIX}" "${IPTV_ROOT_URI}${IPTV_CAT_DIR}/${i}${IPTV_URI_SUFFIX}"
	#${WGET_CMD} "${IPTV_TMP_DIR}/${i}${IPTV_URI_SUFFIX}" "${IPTV_ROOT_URI}${IPTV_CAT_DIR}/${i}${IPTV_URI_SUFFIX}"
done

## Do something {{{1
write_playlists() {
while read myline ; do
	if [[ -n "${myline}" ]] ; then
		# We ignore the lines that begin with #EXTM3U and #EXTVLCOPT for now
		if [[ ! -n "$(grep -e ^#EXTM3U -e ^#EXTVLCOPT <<< "${myline}")" ]] ; then
			if [[ -n "$(grep -e ^#EXTINF <<< "${myline}")" ]] ; then
				TITLE="$(sed -e "s:^.*group-title=\"\(.*\)\",\(.*\):\2:" -e "s:/:-:g" <<< "${myline}")"
				#echo TITLE = $TITLE
				GROUPTITLE="$(sed -e 's:^.*group-title="\(.*\)\(".*\):\1:' -e 's:\" user-agent.*::' <<< "${myline}")"
				#echo "GROUPTITLE = ${GROUPTITLE}"
				# We don't want a too long file name, so keep only the first language
				# FIXIT: LANGUAGE is country now. Maybe change the whole script to add support for the databse csv files
				#        pro: more flexible; con: slower... maybe, who knows without trying
#				LANGUAGE="$(sed -e "s:^.*tvg-id=\"\(.*\)\" tvg-logo.*:\1:" -e "s:;.*::" <<< "${myline}")"
				LANGUAGE="$(sed -e "s:^.*tvg-id=\"\(.*\)\" tvg-logo.*:\1:" -e "s:.*[.]::" <<< "${myline}")"
				#echo LANGUAGE = $LANGUAGE
				#COUNTRY="$(sed "s:^.*tvg-id=\"\(.*\)\" tvg-language.*:\1:" <<< "${myline}")"
				#echo COUNTRY = $COUNTRY
#				mydir="${IPTV_PLAYLISTS_DIR}/${GROUPTITLE}/${LANGUAGE}"
				mydir="${IPTV_PLAYLISTS_DIR}/${LANGUAGE}/${GROUPTITLE}"
				myfile="${mydir}/${COUNTRY}${TITLE}${IPTV_URI_SUFFIX}"
			else
				mkdir -p "${mydir}"
				# ffmpeg:// doesn't works with all channels without '-cache 8092'
				# '-cache 8092' works faster with some channel, but doesn't work without 'ffmpeg://' with other channels.
				echo "ffmpeg://${myline}" > "${myfile}"
				echo "Playlist written in ${myfile}"
			fi
		fi
	fi
done < ${1}
}

## Main function {{{1
${DEBUG_SCRIPT} rm -rf "${IPTV_PLAYLISTS_DIR}"
rm -rf "${IPTV_PLAYLISTS_DIR}"
for i in "${IPTV_CAT_PLAYLISTS[@]}"; do
	${DEBUG_SCRIPT} write_playlists "${IPTV_TMP_DIR}/${i}${IPTV_URI_SUFFIX}"
#	write_playlists "${IPTV_TMP_DIR}/${i}${IPTV_URI_SUFFIX}"
done
