#!/usr/bin/env bash

rawurlencode() {
    local string="${1}"
    local strlen=${#string}
    local encoded=""
    local pos c o

    for (( pos=0 ; pos<strlen ; pos++ )); do
        c=${string:$pos:1}
        case "$c" in
            [-_.~a-zA-Z0-9] ) o="${c}" ;;
            * )               printf -v o '%%%02x' "'$c"
        esac
        encoded+="${o}"
    done
    echo "${encoded}"    # You can either set a return variable (FASTER) 
    REPLY="${encoded}"   #+or echo the result (EASIER)... or both... :p
}


prefix="$(basename "$(pwd)")"
ls | grep "One Piece " |
while IFS="" read season; do
    echo "SEASON: $season";
    seasonNo=$(echo "$season" | cut -d' ' -f 4)
    
    echo "#EXTM3U" > season${seasonNo}.m3u
    ls "$season/"* | grep ".mkv\$" |
    while read ep; do
        #uri="$(echo "$prefix/$ep" | jq -sRr @uri)"
        uri="$(rawurlencode "$prefix/$ep")"
        epNo=$(echo "$(basename "${ep}")" | cut -d' ' -f 5)
        echo "#EXTINF:-1, One Piece s${seasonNo}e${epNo}" >> season${seasonNo}.m3u
        echo "http://hemera.srv.janniaux.me:9999/${uri}" >> season${seasonNo}.m3u
    done
done
