#!/bin/sh 

show_help(){
cat << EOF
This is a very simple script to convert a .sub file into a .vtt

Some manual work is still required. We assume a sub file to start like

\`\`\`
[INFORMATION]
[TITLE]
[AUTHOR]
[COMMENT]
[END INFORMATION]
[SUBTITLE]
00:00:01.00,00:00:09.00
Some translated text

00:01:48.00,00:01:53.00
Some more text

\`\`\`

You'll need to manually remove the parts between brackets, only then will we convert the rest.

Parameters
    -h, --help  Show this help message

    FILE        The file to convert The file needs to end with .sub and will output a file of the same name, but with .vtt extention.

Usage
    ./sub_to_vtt.sh FILE

For a bulk, you can do
    for f in *.sub; do ./sub_to_vtt.sh $f; done

EOF
exit 0
}

if [ "$1" = "-h" ] || [ "$1" = "--help" ]
then
show_help
fi

SUB_FILE="$1"
VTT_FILE=$(echo "$SUB_FILE" | sed -E 's/\.sub$/.vtt/g')

if [ "$SUB_FILE" = "$VTT_FILE" ]
then
echo 'ERROR: PLEASE PROVIDE A .sub FILE, or provide the --help parameter for help.'
exit 1
fi

maual_action_required(){
cat << EOF

Please remove the following lines from $SUB_FILE

\`\`\`
[INFORMATION]
[TITLE]
[AUTHOR]
[COMMENT]
[END INFORMATION]
[SUBTITLE]
\`\`\`

The first line of the file should have a timing, in the following form

\`\`\`
00:00:01.00,00:00:09.00
\`\`\`

EOF
exit 1
}

cat "$SUB_FILE" | grep -E '^\[[A-Z ]+\]' > /dev/null && maual_action_required

echo 'WEBVTT' > "$VTT_FILE"
echo '' >> "$VTT_FILE"

# 00:00:01.00,00:00:09.00
#  to
# 00:00:01.000 --> 00:00:09.000
cat "$SUB_FILE" | sed -E 's/^([0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{2}),([0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{2})/\10 --\> \20/g' >> "$VTT_FILE"
