#!/bin/bash
# Copyright 2014 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.

# This script will check out llvm and clang, build a full package
# with the latest plugin revisions and then repackage an existing
# clang-package with the new plugin revisions.

# The new package can be uploaded to replace the existing clang
# package at the same clang revision.

THIS_DIR="$(dirname "${0}")"
LLVM_BUILD_DIR="${THIS_DIR}/../../../third_party/llvm-build"
LLVM_TAR_DIR="${LLVM_BUILD_DIR}/Release+Asserts"
LLVM_BIN_DIR="${LLVM_TAR_DIR}/bin"
LLVM_LIB_DIR="${LLVM_TAR_DIR}/lib"

set -eu

if [ "$(uname -s)" = "Darwin" ]; then
  PLATFORM=Mac
  SO_EXT="dylib"
else
  PLATFORM=Linux_x64
  SO_EXT="so"
fi

# Build clang with the new plugin revisions.
"$THIS_DIR"/package.sh $@

R=$("${LLVM_BIN_DIR}/clang" --version | \
     sed -ne 's/clang version .*(\([0-9]*\))/\1/p')
PDIR=clang-$R

if [ ! -f "$PDIR.tgz" ]; then
    echo "Could not find package archive $PDIR.tgz generated by package.sh"
    exit 1
fi

# We don't want to change the clang binary, so fetch the current clang
# package and add the plugin shared-libraries to the existing package.
rm -rf $LLVM_BUILD_DIR
"$THIS_DIR"/update.sh

LIBNAME=\
$(grep 'set(LIBRARYNAME' "$THIS_DIR"/../blink_gc_plugin/CMakeLists.txt \
    | cut -d ' ' -f 2 | tr -d ')')
LIBFILE=lib$LIBNAME.$SO_EXT

# Check that we are actually creating the plugin at a new revision.
if [ -f "$LLVM_LIB_DIR/$LIBFILE" ]; then
    echo "The plugin revision $LIBNAME is already in the existing package."
    exit 1
fi

cp $PDIR/lib/$LIBFILE "$LLVM_LIB_DIR/"
if [ "$(uname -s)" = "Darwin" ]; then
  tar zcf ${PDIR}_repack.tgz -C "$LLVM_TAR_DIR" bin include lib buildlog.txt
else
  tar zcf ${PDIR}_repack.tgz -C "$LLVM_TAR_DIR" bin lib buildlog.txt
fi

echo The clang package has been repackaged with $LIBNAME
echo To upload, run:
echo gsutil cp -a public-read ${PDIR}_repack.tgz \
     gs://chromium-browser-clang/$PLATFORM/$PDIR.tgz
