#!/bin/bash

#Colors:
Black='\033[0;30m'
Red='\033[0;31m'
Green='\033[0;32m'
Orange='\033[0;33m'
Blue='\033[0;34m'
Purple='\033[0;35m'
Cyan='\033[0;36m'
Yellow='\033[1;33m'
White='\033[1;37m'

Light_gray='\033[0;37m'
Light_red='\033[1;31m'
Light_green='\033[1;32m'
Light_Red='\033[1;34m'
Light_purple='\033[1;35m'
Light_cyan='\033[1;36m'

Dark_gray='\033[1;30m'

NC='\033[0m' # No Color


echo -e "${Green}[${Red}+${Green}] MP4 2 M3U8 ${Yellow}developed by ${Red}Zarat.dev ${NC}\n"

MYDIR=$(dirname $(readlink -f ${BASH_SOURCE[0]}))
SAVEDIR=$(pwd)

# Check programs
if [ -z "$(which ffmpeg)" ]; then
    echo "Error: ffmpeg is not installed"
    exit 1
fi


cd "$MYDIR"

TARGET_FILES=$(find ./ -type f -name "*.mp4")

COUNTER=0

for f in $TARGET_FILES
do
  f=$(basename "$f") # fullname of the file
  f="${f%.*}" # name without extension

  if [ ! -d "${f}" ]; then

    ((COUNTER++))

    # Separador
    echo -e "${Green}[${White}${COUNTER}${Green}] ${Cyan}====================================================================================== ${Green}[${White}${COUNTER}${Green}]${NC}"

    # Create directory
    echo -e "${Green}[${Red}+${Green}] ${Orange}Creando directorio ${Green}\"$f\"${NC}"
    mkdir "${f}"

    # Conver video
    echo -e "${Green}[${Red}+${Green}] ${Orange}Convirtiendo ${Green}\"$f.mp4\" ${Orange}a m3u8... ${NC}"
    ffmpeg -i "${f}.mp4" -codec: copy -start_number 0 -hls_time 10 -hls_list_size 0 -hls_segment_filename "${f}/a_%03d.jpg" -f hls "${f}/master" &> /dev/null

    # Crear mosaico
    echo -e "${Green}[${Red}+${Green}] ${Orange}Creando mosaico... ${NC}"
    ffmpeg -i "${f}.mp4" -filter_complex "select='not(mod(n,120))',scale=128:72,tile=11x11" -frames:v 1 -qscale:v 3 -an "${f}/mosaic.jpg" &> /dev/null

    # Sacar frame del segundo 50
    echo -e "${Green}[${Red}+${Green}] ${Orange}Creando poster... ${NC}"
    ffmpeg -i "${f}.mp4" -ss 00:00:50 -vframes 1 "${f}/poster.jpg" &> /dev/null

    # Mover archivo roiginal
    echo -e "${Green}[${Red}+${Green}] ${Orange}Moviendo ${Green}\"$f.mp4\" ${Orange}a ${Green}${f} ${NC}"
    mv "${f}.mp4" "${f}/original.mp4"
    fi

done

echo -e "${Green}[${White}OK${Green}] ${Cyan}====================================================================================== ${Green}[${White}OK${Green}]${NC}"
echo -e "${Green}[${White}OK${Green}] ${White}${COUNTER} ${Orange}videos convertidos a m3u8.${NC}\n"


cd "$SAVEDIR"