set -eu
START=${1} # http://olevod.com/index.php/vod/play/id/62435/sid/1/nid/1.html
STAGE1=$(mktemp)
wget --no-check-certificate "${START}" -O "${STAGE1}"
echo "content placed in STAGE1: ${STAGE1}" >&1
STANZA=$(grep -Eo '"url":"https:.*master.m3u8"' "${STAGE1}")
PLAYLIST=$(jq -r .url <<< "{${STANZA}}")
STAGE2=$(mktemp)
echo "fetching stage 2 (first playlist) STAGE2: ${STAGE2}"
wget --no-check-certificate "${PLAYLIST}" -O "${STAGE2}"
echo "constructing path to playlist..."
REL_PATH_TO_PLAYLIST=$(grep -o '.*m3u8$' "${STAGE2}" | cut -f2 -d")
BASE=${PLAYLIST%/*}
echo "base: ${BASE}"
FULL_PATH="${BASE}/${REL_PATH_TO_PLAYLIST}"
STAGE3=$(mktemp)
echo "Fetching first playlist from ${FULL_PATH} and placing it in ${STAGE3}"
wget --no-check-certificate "${FULL_PATH}" -O "${STAGE3}"
while read -r REL ; do
wget --no-check-certificate "${BASE}/${REL}"
done < <(grep -Eo '.*ts$' "${STAGE3}")
find . -type f -name '*.ts' | cut -f2 -d- | grep -v '[A-Za-z]' | sort -h | xargs --replace=REP echo file 'seg-REP-v1-a1.ts' > inputs
ffmpeg -f concat -i inputs -c copy output.ts
ffmpeg -i output.ts -acodec copy -vcodec copy output.mp4
rm output.ts