#!/bin/bash

echo "Compiling stream with ID ${STREAM_ID}"

export MC_HOST_minio=https://${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}@${S3_ENDPOINT}

for i in `mc ls minio/${BUCKET}/hls/0/ | grep -o "stream-$STREAM_ID.*.ts"`;do
  echo file https://${S3_ENDPOINT}/$BUCKET/hls/0/$i;
done > /tmp/allts


ffmpeg -f concat -safe 0 -protocol_whitelist file,http,tcp,https,tls -i /tmp/allts \
  -acodec copy -bsf:a aac_adtstoasc -vcodec copy -movflags frag_keyframe+empty_moov \
  -f mp4 - | mc pipe minio/$BUCKET/recordings/${STREAM_ID}.mp4

echo "Deleting original ts files..."

for i in `mc ls minio/${BUCKET}/hls/0/ | grep -o "stream-$STREAM_ID.*.ts"`;do
  mc rm minio/${BUCKET}/hls/0/$i;
done
for i in `mc ls minio/${BUCKET}/hls/1/ | grep -o "stream-$STREAM_ID.*.ts"`;do
  mc rm minio/${BUCKET}/hls/1/$i;
done
for i in `mc ls minio/${BUCKET}/hls/2/ | grep -o "stream-$STREAM_ID.*.ts"`;do
  mc rm minio/${BUCKET}/hls/2/$i;
done
