#!/bin/bash
#
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Let the wrapped binary know that it has been run through the wrapper.
export CHROME_WRAPPER="$(readlink -f "$0")"

HERE="$(dirname "$CHROME_WRAPPER")"

# Architecture specific handling
case 'x86_64' in
  amd64|x86_64)
    FFMPEG_URL='https://launchpadlibrarian.net/414953672/chromium-codecs-ffmpeg-extra_73.0.3683.75-0ubuntu0.16.04.1_amd64.deb'
    FFMPEG_OFFSET='1077'
    ;;
  i386)
    FFMPEG_URL='https://launchpadlibrarian.net/414928359/chromium-codecs-ffmpeg-extra_73.0.3683.75-0ubuntu0.16.04.1_i386.deb'
    FFMPEG_OFFSET='1071'
    ;;
  armhf)
    FFMPEG_URL='https://launchpadlibrarian.net/415041301/chromium-codecs-ffmpeg-extra_73.0.3683.75-0ubuntu0.16.04.1_armhf.deb'
    FFMPEG_OFFSET='1079'
    ;;
  arm64)
    FFMPEG_URL='https://launchpadlibrarian.net/415070953/chromium-codecs-ffmpeg-extra_73.0.3683.75-0ubuntu0.16.04.1_arm64.deb'
    FFMPEG_OFFSET='1079'
    ;;
esac

# Look for a pre-cached, known to be work, libffmpeg.so
FFMPEG_VERSION_RANGE="93464 92972 92393 92142 91696 91124"
CACHED_FFMPEG_PATH="$HOME/.local/lib/vivaldi"
CACHED_FFMPEG=UNKNOWN
VIVALDI_FFMPEG_FOUND=NO
for CACHED_FFMPEG_VERSION in $FFMPEG_VERSION_RANGE; do
  if [ -r "$CACHED_FFMPEG_PATH/libffmpeg.so.$CACHED_FFMPEG_VERSION" ]; then
    CACHED_FFMPEG="$CACHED_FFMPEG_PATH/libffmpeg.so.$CACHED_FFMPEG_VERSION"
    export VIVALDI_FFMPEG_FOUND=YES
    break
  fi
done

# Check for libs in preferred order. Where possible, use other
# files/directories to confirm it's the correct variant.
SYSTEM_FFMPEG=UNKNOWN
SYSTEM_FFMPEG_VERSION=0
USE_SYSTEM_FFMPEG=NO
for FFMPEG_TEST in "$HERE/libffmpeg.so:/"\
                   "$HOME/.local/lib/vivaldi/libffmpeg.so:/"\
                   "$HOME/.local/lib/vivaldi-snapshot/libffmpeg.so:/"\
                   '/usr/lib/chromium-browser/libffmpeg.so:/usr/share/doc/chromium-codecs-ffmpeg-extra'\
                   '/usr/lib64/chromium-ffmpeg-extra/libffmpeg.so:/'\
                   '/usr/lib64/chromium-browser/libffmpeg.so.freeworld:/'; do
  if [ -e "${FFMPEG_TEST#*:}" ]; then
    if [ -r "${FFMPEG_TEST%:*}" ]; then
      # The version number is early in the binary and -m1 exits on
      # first match, so this operation is actually quite quick
      POTENTIAL_FFMPEG_VERSION="$(grep -aom1 'FFmpeg version N-[0-9]\+-' "${FFMPEG_TEST%:*}" | cut -f2 -d-)"
      if [ "$POTENTIAL_FFMPEG_VERSION" -ge "${FFMPEG_VERSION_RANGE##* }" -a "$POTENTIAL_FFMPEG_VERSION" -le "${FFMPEG_VERSION_RANGE%% *}" ]; then
        # Don't do expensive checks unless this is better than what we
        # already found
        if [ "$POTENTIAL_FFMPEG_VERSION" -gt "$SYSTEM_FFMPEG_VERSION" ]; then
          SYSTEM_FFMPEG="${FFMPEG_TEST%:*}"
          SYSTEM_FFMPEG_VERSION="$POTENTIAL_FFMPEG_VERSION"
          # Don't do expensive checks if the cache has a better file
          if [ "$CACHED_FFMPEG" = 'UNKNOWN' -a "$POTENTIAL_FFMPEG_VERSION" -gt "$CACHED_FFMPEG_VERSION" ]; then
            # Check the dependencies are satisfied as the user may have
            # obtained this from another distro
            if ! LANGUAGE=en ldd "${FFMPEG_TEST%:*}" 2>&1 | grep -qm1 'not \(a dynamic executable\|found\)'; then
              USE_SYSTEM_FFMPEG=YES
              export VIVALDI_FFMPEG_FOUND=YES
            fi
          fi
        fi
      fi
    fi
  fi
done

# Update the cache if we have found something better
if [ "$USE_SYSTEM_FFMPEG" = 'YES' -a "$SYSTEM_FFMPEG_VERSION" -gt "$CACHED_FFMPEG_VERSION" ]; then
  # Make sure we have permission to update our cache
  mkdir -p "$CACHED_FFMPEG_PATH" 2>/dev/null ||:
  if [ -w "$CACHED_FFMPEG_PATH" ]; then
    # Cache the suitable libffmpeg.so, only if it is not already
    # cached. Without this, if the version number is not one of the
    # list of known versions (but it is within the range), a copy
    # operation would happen on every startup
    if [ ! -e "$CACHED_FFMPEG_PATH/libffmpeg.so.$SYSTEM_FFMPEG_VERSION" ]; then
      # Delete old cached libffmpeg.so files, before installing (yet)
      # another lib. 200 days gives a little over 6 months of caching
      find "$CACHED_FFMPEG_PATH" -type f -name 'libffmpeg.so.*' -mtime +200 -delete
      # Move unversioned libs within our own cache. This means less
      # checks in the future and it avoids duplication. Copy everything
      # else because we might not have permission and it might break
      # other applications
      if [ "$(dirname "$SYSTEM_FFMPEG")" = "$CACHED_FFMPEG_PATH" ]; then
        mv "$SYSTEM_FFMPEG" "$CACHED_FFMPEG_PATH/libffmpeg.so.$SYSTEM_FFMPEG_VERSION"
      else
        install -m644 "$SYSTEM_FFMPEG" "$CACHED_FFMPEG_PATH/libffmpeg.so.$SYSTEM_FFMPEG_VERSION"
      fi
    fi
    CACHED_FFMPEG="$CACHED_FFMPEG_PATH/libffmpeg.so.$SYSTEM_FFMPEG_VERSION"
  fi
fi

if [ "$VIVALDI_FFMPEG_FOUND" = 'YES' ]; then
  # Prefer loading libffmpeg.so from a non-user-writeable area
  SYSTEM_FFMPEG_INSTALL_ROOT="$(echo "$SYSTEM_FFMPEG" | cut -d/ -f1-2)"
  if [ "$SYSTEM_FFMPEG_VERSION" -ge "$CACHED_FFMPEG_VERSION" ] && [ "$SYSTEM_FFMPEG_INSTALL_ROOT" = '/usr' -o "$SYSTEM_FFMPEG_INSTALL_ROOT" = '/opt' ]; then
    if [ -n "$LD_PRELOAD" ]; then
      export LD_PRELOAD="$LD_PRELOAD:$SYSTEM_FFMPEG"
    else
      export LD_PRELOAD="$SYSTEM_FFMPEG"
    fi
  else
    if [ -n "$LD_PRELOAD" ]; then
      export LD_PRELOAD="$LD_PRELOAD:$CACHED_FFMPEG"
    else
      export LD_PRELOAD="$CACHED_FFMPEG"
    fi
  fi
# Warn if proprietary media is not available
else
  if command -v curl >/dev/null 2>&1; then
    DOWNLOADER=curl
  else
    DOWNLOADER='wget -O-'
  fi
  cat << MEDIAHELP >&2

No suitable library for HTML5 proprietary media (MP4[H.264/AAC]) was found,
therefore only open codecs will play.

To add support for proprietary media, issue the following command and restart
Vivaldi:

MEDIAHELP
  codecs_install_msg () {
  cat << FFMPEG_CMD
  $DOWNLOADER $FFMPEG_URL |\\
  tail -c+$FFMPEG_OFFSET | tar JxC ~ --wildcards \*libffmpeg.so --xform 's,.*/,.local/lib/vivaldi/,'

FFMPEG_CMD
  }
  if [ -e /etc/os-release ]; then
    . /etc/os-release
    if [ "$ID" = 'ubuntu' ]; then
      # Give the generic help if the user is on Ubuntu and has
      # chromium-codecs-ffmpeg-extra but it still fails
      if [ -d '/usr/share/doc/chromium-codecs-ffmpeg-extra' ]; then
        codecs_install_msg
      else
        printf '  sudo apt update && sudo apt install chromium-codecs-ffmpeg-extra\n\n'
      fi
    else
      codecs_install_msg
    fi
  else
    codecs_install_msg
  fi
fi

export CHROME_VERSION_EXTRA="stable"

# We don't want bug-buddy intercepting our crashes. http://crbug.com/24120
export GNOME_DISABLE_CRASH_DIALOG=SET_BY_GOOGLE_CHROME

# Sanitize std{in,out,err} because they'll be shared with untrusted child
# processes (http://crbug.com/376567).
exec < /dev/null
exec > >(exec cat)
exec 2> >(exec cat >&2)

# Note: exec -a below is a bashism.
exec -a "$0" "$HERE/vivaldi-bin" "$@"
