# Recursively replace @@include@@ template variables with the referenced file,
# and write the resulting text to stdout.
process_template_includes() {
  INCSTACK+="$1->"
  # Includes are relative to the file that does the include.
  INCDIR=$(dirname $1)
  # Clear IFS so 'read' doesn't trim whitespace
  local OLDIFS="$IFS"
  IFS=''
  while read -r LINE
  do
    INCLINE=$(sed -e '/^[[:space:]]*@@include@@/!d' <<<$LINE)
    if [ -n "$INCLINE" ]; then
      INCFILE=$(echo $INCLINE | sed -e "s#@@include@@\(.*\)#\1#")
      # Simple filename match to detect cyclic includes.
      CYCLE=$(sed -e "\#$INCFILE#"'!d' <<<$INCSTACK)
      if [ "$CYCLE" ]; then
        echo "ERROR: Possible cyclic include detected." 1>&2
        echo "$INCSTACK$INCFILE" 1>&2
        exit 1
      fi
      if [ ! -r "$INCDIR/$INCFILE" ]; then
        echo "ERROR: Couldn't read include file: $INCDIR/$INCFILE" 1>&2
        exit 1
      fi
      process_template_includes "$INCDIR/$INCFILE"
    else
      echo "$LINE"
    fi
  done < "$1"
  IFS="$OLDIFS"
  INCSTACK=${INCSTACK%"$1->"}
}

# Replace template variables (@@VARNAME@@) in the given template file. If a
# second argument is given, save the processed text to that filename, otherwise
# modify the template file in place.
process_template() (
  # Don't worry if some of these substitution variables aren't set.
  # Note that this function is run in a sub-shell so we don't leak this
  # setting, since we still want unbound variables to be an error elsewhere.
  set +u

  local TMPLIN="$1"
  if [ -z "$2" ]; then
    local TMPLOUT="$TMPLIN"
  else
    local TMPLOUT="$2"
  fi
  # Process includes first so included text also gets substitutions.
  TMPLINCL="$(process_template_includes "$TMPLIN")"
  sed \
    -e "s#@@PACKAGE@@#${PACKAGE}#g" \
    -e "s#@@PACKAGE_FILENAME@@#${PACKAGE_FILENAME}#g" \
    -e "s#@@PROGNAME@@#${PROGNAME}#g" \
    -e "s#@@CHANNEL@@#${CHANNEL}#g" \
    -e "s#@@COMPANY_FULLNAME@@#${COMPANY_FULLNAME}#g" \
    -e "s#@@VERSION@@#${VERSION}#g" \
    -e "s#@@PACKAGE_RELEASE@@#${PACKAGE_RELEASE}#g" \
    -e "s#@@VERSIONFULL@@#${VERSIONFULL}#g" \
    -e "s#@@INSTALLDIR@@#${INSTALLDIR}#g" \
    -e "s#@@BUILDDIR@@#${BUILDDIR}#g" \
    -e "s#@@STAGEDIR@@#${STAGEDIR}#g" \
    -e "s#@@SCRIPTDIR@@#${SCRIPTDIR}#g" \
    -e "s#@@MENUNAME@@#${MENUNAME}#g" \
    -e "s#@@PRODUCTURL@@#${PRODUCTURL}#g" \
    -e "s#@@PREDEPENDS@@#${PREDEPENDS}#g" \
    -e "s#@@DEPENDS@@#${DEPENDS}#g" \
    -e "s#@@PROVIDES@@#${PROVIDES}#g" \
    -e "s#@@REPLACES@@#${REPLACES}#g" \
    -e "s#@@CONFLICTS@@#${CONFLICTS}#g" \
    -e "s#@@ARCHITECTURE@@#${ARCHITECTURE}#g" \
    -e "s#@@MAINTNAME@@#${MAINTNAME}#g" \
    -e "s#@@MAINTMAIL@@#${MAINTMAIL}#g" \
    -e "s#@@REPOCONFIG@@#${REPOCONFIG}#g" \
    -e "s#@@SHORTDESC@@#${SHORTDESC}#g" \
    -e "s#@@FULLDESC@@#${FULLDESC}#g" \
    -e "s#@@DEFAULT_FLAGS@@#${DEFAULT_FLAGS:-}#g" \
    -e "s#@@SXS_USER_DATA_DIR@@#${SXS_USER_DATA_DIR:-}#g" \
    -e "s#@@USR_BIN_SYMLINK_NAME@@#${USR_BIN_SYMLINK_NAME:-}#g" \
    > "$TMPLOUT" <<< "$TMPLINCL"
)

# Setup the installation directory hierachy in the package staging area.
prep_staging_common() {
  install -m 755 -d "${STAGEDIR}/${INSTALLDIR}" \
    "${STAGEDIR}/usr/bin" \
    "${STAGEDIR}/usr/share/applications" \
    "${STAGEDIR}/usr/share/gnome-control-center/default-apps" \
    "${STAGEDIR}/usr/share/man/man1"
}

get_version_info() {
  source "${BUILDDIR}/installer/version.txt"
  VERSION="${MAJOR}.${MINOR}.${BUILD}.${PATCH}"
  # TODO(phajdan.jr): Provide a mechanism to pass a different package
  # release number if needed. The meaning of it is to bump it for
  # packaging-only changes while the underlying software has the same version.
  # This corresponds to the Release field in RPM spec files and debian_revision
  # component of the Version field for DEB control file.
  # Generally with Chrome's fast release cycle it'd be more hassle to try
  # to bump this number between releases.
  PACKAGE_RELEASE="1"
}

stage_install_common() {
  echo "Staging common install files in '${STAGEDIR}'..."

  # TODO(mmoss) This assumes we built the static binaries. To support shared
  # builds, we probably want an install target in scons so it can give us all
  # the right files. See also:
  # http://code.google.com/p/chromium/issues/detail?id=4451
  #
  # app
  # We need to add the debug link so gdb knows to look for the symbols.
  DEBUGFILE="${BUILDDIR}/${PROGNAME}.debug"
  STRIPPEDFILE="${BUILDDIR}/${PROGNAME}.stripped"
  "${BUILDDIR}/installer/common/eu-strip" -o "${STRIPPEDFILE}" -f "${DEBUGFILE}" "${BUILDDIR}/${PROGNAME}"
  install -m 755 "${STRIPPEDFILE}" "${STAGEDIR}/${INSTALLDIR}/${PROGNAME}"
  rm "${DEBUGFILE}" "${STRIPPEDFILE}"

  # resources
  install -m 644 "${BUILDDIR}/resources.pak" "${STAGEDIR}/${INSTALLDIR}/"
  # TODO(mmoss): This has broken a couple times on adding new .pak files. Maybe
  # we should flag all installer files in FILES.cfg and get them from there, so
  # there's only one place people need to keep track of such things (and in
  # only the public repository).
  if [ -r "${BUILDDIR}/chrome_100_percent.pak" ]; then
    install -m 644 "${BUILDDIR}/chrome_100_percent.pak" "${STAGEDIR}/${INSTALLDIR}/"
  else
    install -m 644 "${BUILDDIR}/theme_resources_100_percent.pak" "${STAGEDIR}/${INSTALLDIR}/"
    install -m 644 "${BUILDDIR}/ui_resources_100_percent.pak" "${STAGEDIR}/${INSTALLDIR}/"
  fi

  # ICU data file; only necessary when icu_use_data_file_flag is set to 1
  # in build/common.gypi.
  install -m 644 "${BUILDDIR}/icudtl.dat" "${STAGEDIR}/${INSTALLDIR}/"

  # sandbox
  # Rename sandbox binary with hyphen instead of underscore because that's what
  # the code looks for, but the build targets can't use hyphens (scons bug?)
  install -m 4755 -s "${BUILDDIR}/${PROGNAME}_sandbox" \
    "${STAGEDIR}/${INSTALLDIR}/${PROGNAME}-sandbox"

  # l10n paks
  cp -a "${BUILDDIR}/locales" "${STAGEDIR}/${INSTALLDIR}/"
  find "${STAGEDIR}/${INSTALLDIR}/locales" -type f -exec chmod 644 '{}' \;
  find "${STAGEDIR}/${INSTALLDIR}/locales" -type d -exec chmod 755 '{}' \;

  # ffmpeg libs
  install -m 644 -s "${BUILDDIR}/libffmpegsumo.so" "${STAGEDIR}/${INSTALLDIR}/"

  # Widevine CDM.
  if [ -f "${BUILDDIR}/libwidevinecdmadapter.so" ]; then
    install -m 644 -s "${BUILDDIR}/libwidevinecdmadapter.so" "${STAGEDIR}/${INSTALLDIR}/"
    install -m 644 "${BUILDDIR}/libwidevinecdm.so" "${STAGEDIR}/${INSTALLDIR}/"
  fi

  # Pepper Flash.
  PEPPERFLASH_SRCDIR="${BUILDDIR}/PepperFlash"
  PEPPERFLASH_DESTDIR="${STAGEDIR}/${INSTALLDIR}/PepperFlash"
  install -m 755 -d "${PEPPERFLASH_DESTDIR}"
  install -m 644 -s "${PEPPERFLASH_SRCDIR}/libpepflashplayer.so" \
    "${PEPPERFLASH_DESTDIR}/"
  install -m 644 "${PEPPERFLASH_SRCDIR}/manifest.json" \
    "${PEPPERFLASH_DESTDIR}/"

  # pdf plugin
  if [ -f "${BUILDDIR}/libpdf.so" ]; then
    install -m 644 -s "${BUILDDIR}/libpdf.so" "${STAGEDIR}/${INSTALLDIR}/"
  fi

  # peerconnection shared library
  if [ -f "${BUILDDIR}/lib/libpeerconnection.so" ]; then
    install -m 755 -d "${STAGEDIR}/${INSTALLDIR}/lib/"

    install -m 644 -s "${BUILDDIR}/lib/libpeerconnection.so" "${STAGEDIR}/${INSTALLDIR}/lib/"
  fi

  # nacl pepper plugin
  if [ -f "${BUILDDIR}/libppGoogleNaClPluginChrome.so" ]; then
    install -m 644 -s "${BUILDDIR}/libppGoogleNaClPluginChrome.so" "${STAGEDIR}/${INSTALLDIR}/"
  fi

  # nacl_helper and nacl_helper_bootstrap
  # Don't use "-s" (strip) because this runs binutils "strip", which
  # mangles the special ELF program headers of nacl_helper_bootstrap.
  # Explicitly use eu-strip instead, because it doesn't have that problem.
  for file in nacl_helper nacl_helper_bootstrap; do
    buildfile="${BUILDDIR}/${file}"
    if [ -f "${buildfile}" ]; then
      strippedfile="${buildfile}.stripped"
      debugfile="${buildfile}.debug"
      "${BUILDDIR}/installer/common/eu-strip" -o "${strippedfile}" -f "${debugfile}" "${buildfile}"
      install -m 755 "${strippedfile}" "${STAGEDIR}/${INSTALLDIR}/${file}"
    fi
  done
  # Don't use "-s" (strip) because this would use the Linux toolchain to
  # strip the NaCl binary, which has the potential to break it.  It
  # certainly resets the OSABI and ABIVERSION fields to non-NaCl values,
  # although the NaCl IRT loader doesn't care about these fields.  In any
  # case, the IRT binaries are already stripped by NaCl's build process.
  for filename in ${BUILDDIR}/nacl_irt_*.nexe; do
    # Re-check the filename in case globbing matched nothing.
    if [ -f "$filename" ]; then
      install -m 644 "$filename" "${STAGEDIR}/${INSTALLDIR}/`basename "$filename"`"
    fi
  done

  # default apps
  if [ -d "${BUILDDIR}/default_apps" ]; then
    cp -a "${BUILDDIR}/default_apps" "${STAGEDIR}/${INSTALLDIR}/"
    find "${STAGEDIR}/${INSTALLDIR}/default_apps" -type d -exec chmod 755 '{}' \;
    find "${STAGEDIR}/${INSTALLDIR}/default_apps" -type f -exec chmod 644 '{}' \;
  fi

  # launcher script and symlink
  process_template "${BUILDDIR}/installer/common/wrapper" \
    "${STAGEDIR}/${INSTALLDIR}/${PACKAGE}"
  chmod 755 "${STAGEDIR}/${INSTALLDIR}/${PACKAGE}"
  if [ ! -f "${STAGEDIR}/${INSTALLDIR}/google-chrome" ]; then
    ln -sn "${INSTALLDIR}/${PACKAGE}" \
      "${STAGEDIR}/${INSTALLDIR}/google-chrome"
  fi
  ln -snf "${INSTALLDIR}/${PACKAGE}" \
    "${STAGEDIR}/usr/bin/${USR_BIN_SYMLINK_NAME}"

  # app icons
  install -m 644 \
    "${BUILDDIR}/installer/theme/product_logo_"*.png \
    "${BUILDDIR}/installer/theme/product_logo_32.xpm" \
    "${STAGEDIR}/${INSTALLDIR}/"

  # desktop integration
  install -m 755 "${BUILDDIR}/xdg-mime" "${STAGEDIR}${INSTALLDIR}/"
  install -m 755 "${BUILDDIR}/xdg-settings" "${STAGEDIR}${INSTALLDIR}/"
  process_template "${BUILDDIR}/installer/common/desktop.template" \
    "${STAGEDIR}/usr/share/applications/${PACKAGE}.desktop"
  chmod 644 "${STAGEDIR}/usr/share/applications/${PACKAGE}.desktop"
  process_template "${BUILDDIR}/installer/common/default-app.template" \
    "${STAGEDIR}/usr/share/gnome-control-center/default-apps/${PACKAGE}.xml"
  chmod 644 "${STAGEDIR}/usr/share/gnome-control-center/default-apps/${PACKAGE}.xml"
  process_template "${BUILDDIR}/installer/common/default-app-block.template" \
    "${STAGEDIR}${INSTALLDIR}/default-app-block"
  chmod 644 "${STAGEDIR}${INSTALLDIR}/default-app-block"

  # documentation
  install -m 755 "${BUILDDIR}/${PROGNAME}.1" \
    "${STAGEDIR}/usr/share/man/man1/${PACKAGE}.1"
}