#!/bin/sh

DATE=$2

set_alias(){
    if [[ -z $OUTPUT_HOST ]]; then
        OUTPUT_HOST=$INPUT_HOST
        OUTPUT_ACCESS_KEY=$INPUT_ACCESS_KEY
        OUTPUT_SECRET_KEY=$INPUT_SECRET_KEY
    fi
    mc alias set input $INPUT_HOST $INPUT_ACCESS_KEY $INPUT_SECRET_KEY
    mc alias set output $OUTPUT_HOST $OUTPUT_ACCESS_KEY $OUTPUT_SECRET_KEY
}

run() {
    set_alias
    for file in $(mc ls --json input/$INPUT_BUCKET |  jq -rs --arg filter "$INPUT_FILTER" 'map(select(.key|contains($filter)))[].key'); do
        mc cp input/$INPUT_BUCKET/$file ./
        echo "file $file" >> stream.list
    done

    FILE=$OUTPUT_NAME.mp4
    ffmpeg -f concat -i stream.list -c copy $FILE
    mc cp ./$FILE output/$OUTPUT_BUCKET/$FILE 
}

list() {
    set_alias
    mc ls input/$INPUT_BUCKET --json | jq -rs --arg date "$DATE" 'map({date:.lastModified,key:.key|match("stream-.{9}")|.string})|unique_by(.key)|map(select(.date|contains($date))|.key)[]'
}

case $1 in
run)
  run;;
list)
  list;;
*)
    echo "Command no found. Help :"
    echo -e "\tencode.sh run"
    echo -e "\tencode.sh list <DATE:2021-12-01>";;
esac
