#!/usr/bin/env bash

GRPOPPRO_DATA_DIR=~/.local/share/grpoppro
#GRPOPPRO_DATA_DIR=${XDG_DATA_HOME:-$HOME/.local/}/grpoppro
GRPOPPRO_DATA_FILE=$GRPOPPRO_DATA_DIR/lastPlayed
INTERACTIVE="on"
menu="rofi -show -dmenu -p seasonXepisode"
#menu="fzf -i --prompt=seasonXepisode"
#menu="dmenu -i -l 10 -p seasonXepisode"
apiurl="https://coverapi.store"
player="mpv"

function getFzfForTermux {
if command -v fzf >/dev/null 2>&1; then
	echo -e "\n"
else
	apt install -y fzf
fi
}

[[ "$OSTYPE" != "linux-gnu" ]] && INTERACTIVE="off" && menu="fzf -i --prompt=seasonXepisode" && player="am start -n is.xyz.mpv/.MPVActivity -a android.intent.action.VIEW -d" && getFzfForTermux

function getMovieStreamUrl() {
streamurl=$(curl -s 'https://coverapi.store/engine/ajax/controller.php' \
  -H 'Connection: keep-alive' \
  -H 'sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="98"' \
  -H 'Accept: application/json, text/javascript, */*; q=0.01' \
  -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' \
  -H 'X-Requested-With: XMLHttpRequest' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36' \
  -H 'sec-ch-ua-platform: "Linux"' \
  -H 'Origin: https://coverapi.store' \
  -H 'Sec-Fetch-Site: same-origin' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Referer: '$simpleurl'' \
  -H 'Accept-Language: en-GB,en;q=0.9,el;q=0.8' \
  -H 'Cookie: PHPSESSID=6be2a34628cde3aeefbfed1020a10127' \
  --data-raw 'mod=players&news_id='$movieid'' \
  --compressed | awk '{print $12}' | awk -F, '{print $1}' | sed 's/\\//g' | awk -F\" '{print $2}')
}

function getMovieID() {
movieid=$(curl -s $simpleurl | grep news_id | awk '{print $5}' | awk -F\' '{print $2}')
}

function getSeriesID_URL {
getMovieID "$simpleurl"
seriesid=$movieid
seriesurl=$(curl -s 'https://coverapi.store/uploads/playlists/'$seriesid'.txt')
}

function getIMDBID() {
imdbid=$(curl -s "https://www.imdb.com/find?ref_=nv_sr_fn&s=all&q=$title" | grep -io '<a href=['"'"'"][^"'"'"']*['"'"'"]' | grep "title" | head -n1 | sed -e 's/^<a href=["'"'"']//i' -e 's/["'"'"']$//i' -e 's/\/title\///' -e 's/\///g')
if ! [[ "$imdbid" == *"tt"* ]];then
	[[ "$INTERACTIVE" == "on" ]] && notify-send -t 2000 "Film or show not found in imdb" || echo -e "\n\tFilm or show not found in imdb"
	exit
fi
}

function usage {
	echo -e "\n\tUsage: $(basename "$0") \"name of film or show\" [season] [episode(ex 01 02 .. 10 11)]\n\tOr $(basename "$0") [--menu|--resume|--finish]"
	exit
}
function play {
	if $(curl -s $simpleurl | grep -q "id='el-content'></div>");
	then [[ "$INTERACTIVE" == "on" ]] && notify-send -t 2000 "No file found" || echo -e "\n\tNo file found" && exit
	fi
	[[ "$player" == "mpv" ]] && player="mpv --save-position-on-quit --fs"
	[[ "$OSTYPE" != "linux-gnu" ]] && INTERACTIVE="off" && streamurl=$(echo $streamurl | sed 's/https/http/g')
	$player $streamurl
}
function dumpData() {
	echo $title > ~/.local/share/grpoppro/lastPlayed
	echo $seasonEpisode >> ~/.local/share/grpoppro/lastPlayed
	echo $streamurl >> ~/.local/share/grpoppro/lastPlayed
	[[ "$INTERACTIVE" == "on" ]] && notify-send -t 2000 "Last Played -> $seasonEpisode" || echo "Last Played -> $seasonEpisode"

}
function sourceData {
[ -f "$GRPOPPRO_DATA_FILE" ] && lastSeasonEpisodePlayed="$(sed -n 2p $GRPOPPRO_DATA_FILE)" && lastSeriesPlayed="$(sed -n 1p $GRPOPPRO_DATA_FILE)" && lastEpisodePlayedURL="$(sed -n 3p $GRPOPPRO_DATA_FILE)"
}
[[ "$#" -lt 1 ]] && usage
[[ "$#" -gt 3 ]] && usage
[[ "$#" -eq 2 ]] && usage
#Standard Stuff
function basics() {
title=$(echo "$1" | sed 's/ /%20/g')
getIMDBID "$title"
simpleurl=$apiurl/embed/$imdbid/
}

function menuSearch {
[[ "$INTERACTIVE" == "on" ]] && title=$(rofi -dmenu -i -no-fixed-num-lines -p "Search Series")
[[ "$INTERACTIVE" == "off" ]] && [[ -z "$title" ]] && read -p "Search Series: " title
[[ -z "$title" ]] && exit
title=$(echo $title | sed 's/ /%20/g')
getIMDBID "$title"
simpleurl=$apiurl/embed/$imdbid/
getSeriesID_URL
seasonEpisode=$(curl -s 'https://coverapi.store/uploads/playlists/'$seriesid'.txt' | grep "mp4" | awk -F\" '{print $8}' | awk -F/ '{print $NF}' | awk -F. '{print $1}' | $menu)
if [[ -z "$seasonEpisode" ]]; then
	[[ "$INTERACTIVE" == "on" ]] && notify-send -t 2000 "Nothing Selected" || echo "Nothing Selected"
	exit
fi
streamurl=$(curl -s 'https://coverapi.store/uploads/playlists/'$seriesid'.txt' | grep "mp4" | grep "${seasonEpisode}" | head -n 1 | awk -F\" '{print $8}')
mkdir -p ~/.local/share/grpoppro
dumpData "$title" "$seasonEpisode"
play
resume
}

function resume {
sourceData
title=$lastSeriesPlayed
getIMDBID "$title"
while true
do
	sourceData
	simpleurl=$apiurl/embed/$imdbid/
	getSeriesID_URL
       	seasonEpisode=$(curl -s 'https://coverapi.store/uploads/playlists/'$seriesid'.txt' | grep "mp4" | awk -F\" '{print $8}' | awk -F/ '{print $NF}' | awk -F. '{print $1}' | sed -n -e "0,/$lastSeasonEpisodePlayed/!p" | $menu)
        if [[ -z "$seasonEpisode" ]]; then
                [[ "$INTERACTIVE" == "on" ]] && notify-send "Nothing Selected" || echo "Nothing Selected"
                exit
        fi
        streamurl=$(curl -s 'https://coverapi.store/uploads/playlists/'$seriesid'.txt' | grep "mp4" | grep "${seasonEpisode}" | head -n 1 | awk -F\" '{print $8}')
	dumpData "$title" "$seasonEpisode"
	play        
done
}
function resumeUnfinishedEpisode {
sourceData
streamurl=$lastEpisodePlayedURL
[[ "$OSTYPE" != "linux-gnu" ]] && INTERACTIVE="off" && streamurl=$(echo $streamurl | sed 's/https/http/g')
[[ "$player" == "mpv" ]] && player="mpv --resume-playback --fs"
$player $streamurl
resume
}

[[ "$1" == "--menu" ]] && menuSearch 
[[ "$1" == "--resume" ]] && resume 
[[ "$1" == "--finish" ]] && resumeUnfinishedEpisode

if [[ "$1" == *"tt"* ]] && [[ "$#" -eq 1 ]] && [[ "$1" != "--menu" ]] && [[ "$1" != "--resume" ]];then
	simpleurl=$1
        getMovieID "$simpleurl"
	getMovieStreamUrl "$movieid"
	play
	exit
fi
# Series URL
if [[ "$#" -eq 3 ]];then
	basics "$1"
	getSeriesID_URL
	season=$2
	episode=$3
	streamurl=$(curl -s 'https://coverapi.store/uploads/playlists/'$seriesid'.txt' | grep "mp4" | grep "${season}x${episode}" | head -n 1 | awk -F\" '{print $8}')
	play
	exit
fi
# Movies URL
if [[ "$#" -eq 1 ]] && [[ "$1" != "--menu" ]] && [[ "$1" != "--resume" ]];then
	basics "$1"
	getMovieID "$simpleurl"
	getMovieStreamUrl "$movieid"
	play
	exit
fi
