#!/bin/bash

CODECS_JSON_URL='https://browser-resources.s3.yandex.net/linux/codecs.json'

download_ffmpeg () {
  DOWNLOAD="wget -O$1"
  while read url
  do
    $DOWNLOAD "$url"
    if [ $? -eq 0 ]; then
      return 0
    fi
  done <<< "$2"
  return 1
}

install_ffmpeg() {
  SOURCE="usr/lib/chromium-browser/libffmpeg.so"
  DEST="/opt/yandex/browser"
  if [ $UID -eq 0 ]; then
    mv $SOURCE $DEST
  else
    sudo -p "Install FFMPEG as root, password: " mv $SOURCE $DEST
  fi
  return $?
}

update_ffmpeg () {
  FFMPEG_DIR=$(mktemp -d) || return 1
  FFMPEG_FILE=$(mktemp -p "$FFMPEG_DIR") || return 1
  trap "rm -rf $FFMPEG_DIR" EXIT

  CODECS_JSON=$(wget -qO- "$CODECS_JSON_URL")
  if [ $? -ne 0 ]; then
    echo "FFMPEG codecs installation failed: can not download $CODECS_JSON_URL"
    return 1
  fi

  SUITABLE_URLS=$(echo "$CODECS_JSON" | jq -r '."138.0.7204"[]?')
  if [ -z "$SUITABLE_URLS" ]; then
    echo "FFMPEG codecs installation failed: there are no download urls for the current browser version: 138.0.7204"
    return 1
  fi

  cd "$FFMPEG_DIR" &&
    download_ffmpeg "$FFMPEG_FILE" "$SUITABLE_URLS" &&
    ar -x "$FFMPEG_FILE" &&
    tar xf "data.tar.xz" &&
    install_ffmpeg &&
  cd - > /dev/null

  if [ $? -eq 0 ]; then
    echo "FFMPEG codecs have been installed"
  else
    echo "FFMPEG codecs installation failed"
    return 1
  fi
}

update_ffmpeg
