#!/bin/bash
# Script to generate clips of agents acting in Roboschool environments
# Chapter 9, Hands-on Intelligent Agents with OpenAI Gym | Praveen Palanisamy
: '
#1. List of all env names
env_list="RoboschoolInvertedPendulum-v1,RoboschoolInvertedPendulumSwingup-v1,RoboschoolInvertedDoublePendulum-v1,RoboschoolReacher-v1,RoboschoolHopper-v1,RoboschoolWalker2d-v1,RoboschoolHalfCheetah-v1,RoboschoolAnt-v1,RoboschoolHumanoid-v1,RoboschoolHumanoidFlagrun-v1,RoboschoolHumanoidFlagrunHarder-v1,RoboschoolPong-v1"
env_names=(${env_list//,/ })
# Directory where the Monitor video files will be saved by the run_roboschoo_env.py script
save_dir="./env_video_clips/"  

#2. For each env_name in env_list, run_roboschool_env --evn env_name
for env_name in "${env_names[@]}"
do
    echo "$env_name"
    python run_roboschool_env.py --env "$env_name"

done

#3. Concat the episode videos generated by monitor in each env folder
for env_name in "${env_names[@]}"
do
    video_clips=$save_dir$env_name/*.mp4
    ls $video_clips | perl -ne 'print "file $_"' | ffmpeg -f concat -safe 0 -i - -c copy $save_dir$env_name/combined.mp4
done

#4. Convert the concatenated videos to gif
for env_name in "${env_names[@]}"
do
    ffmpeg -i $save_dir$env_name/combined.mp4 -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 5 -loop 0 - $save_dir$env_name/combined.gif
done
'

#1. List of all env names

env_list="RoboschoolInvertedPendulum-v1,RoboschoolInvertedPendulumSwingup-v1,RoboschoolInvertedDoublePendulum-v1,RoboschoolReacher-v1,RoboschoolHopper-v1,RoboschoolWalker2d-v1,RoboschoolHalfCheetah-v1,RoboschoolAnt-v1,RoboschoolHumanoid-v1,RoboschoolHumanoidFlagrun-v1,RoboschoolHumanoidFlagrunHarder-v1,RoboschoolPong-v1"
env_names=(${env_list//,/ })

# Directory where the Monitor video files will be saved by the run_roboschoo_env.py script
save_dir="./roboschool_clips/"  

for env_name in "${env_names[@]}"
do
    echo "$env_name"
    #2. For each env_name in env_names, run_roboschool_env --evn env_name to generate episode recordings
    python run_roboschool_env.py --env "$env_name"

    #3. Concat the episode videos generated by monitor in each env folder
    video_clips=$save_dir$env_name/*.mp4
    ls $video_clips | perl -ne 'print "file $_"' | ffmpeg -f concat -safe 0 -i - -c copy $save_dir$env_name/combined.mp4

    #4. Convert the concatenated videos to gif
    ffmpeg -i $save_dir$env_name/combined.mp4 -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 5 -loop 0 - $save_dir$env_name/combined.gif
done
