#!/bin/sh

# Copyright (c) 2015, Percona LLC and/or its affiliates. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

DEV="${DEV:-""}"
DIRTY_BUILD="${DIRTY_BUILD:-"no"}"

if [ $# -eq 1 -a "$1" = "help" ]; then
   echo "Usage: $0"
   echo
   echo "This script must be ran from the root or scripts/ dir."
   exit 0
fi

set -eu

err() {
   echo "ERROR: $@" >&2
   exit 1
}

BIN="percona-qan-app"

if [ -f "build" -a -f "install" ]; then
   cd ..
fi

if [ -f "bower.json" ]; then
   ROOT_DIR="$PWD"
else
   err "Run this script from the percona/platform-app directory."
fi

if [ -z "$(which bower)" ]; then
   err "Bower is not installed. Run 'npm install -g bower' to install it."
fi

cd "$ROOT_DIR"

# Determine if this is a dev or release build. A release build requires using
# the master branch that's tagged with the same version in conf/app.conf. Else,
# we presume dev build.
VER="$(awk -F: '/version/ {print $2}' bower.json | sed -e 's/[^0-9.a-z-]*//g')"
REV="$(git log -n 1 --no-walk --pretty="%h")"
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if [ "$BRANCH" = "master" -a "$DEV" = "" ]; then
   # git log -n 1 --no-walk --tags --pretty="%h %d" --decorate=full
   # 1475390  (HEAD, tag: refs/tags/v1.0.0, refs/remotes/origin/master, refs/heads/master, refs/heads/foo)
   latestTag="$(git log -n 1 --no-walk --tags --pretty="%h %d" --decorate=full)"
   tagRev="$(echo "$latestTag" | awk '{print $1}')"
   tagVer="$(echo "$latestTag" | perl -n -e '/refs\/tags\/v([\d\.]+)/ && print $1')"
   if [ "$tagVer" -a "$tagRev" = "$REV" ]; then
      if [ "$tagVer" != "$VER" ]; then
         err "Version mismatch: bower.json has v$VER, but git tag has v$tagVer"
      else
         dirty="$(git status --porcelain)"
         if [ "$dirty" ]; then
            if [ "$DIRTY_BUILD" = "no" ]; then
               err "Cannot do release build because this is the master branch with version" \
                  "tag v$tagVer but there are uncommitted changes or untracked files" \
                  "(see 'git status'). If the latest commit is not v$tagVer, remove the tag (git tag -d v$tagVer);" \
                  "else, add and commit all changes, then re-tag the latest commit" \
                  "(git tag -a v$tagVer -m \"v$tagVer\"). Or, specify DIRTY_BUILD=yes to force" \
                  "the release build (not recommended)."
            else
               echo "Dirty release build of master branch v$VER"
            fi
         else
            echo "Release build of master branch v$VER"
         fi
         DEV="no"
      fi
   else
      echo "Dev build of master branch @ $REV (latest commit has no version tag)"
      DEV="yes"
   fi
else
   echo "Dev build of $BRANCH branch @ $REV"
   DEV="yes"
fi

# To distinguish dev and release builds, we append "-date.revision" to dev builds,
# e.g. release 1.0.0 = "1.0.0", but dev 1.0.0 = "1.0.0-20150825.a73cd9e".
if [ "$DEV" = "yes" ] && [ "$DIRTY_BUILD" = "no" ]; then
   ymd="$(TZ="UTC" date "+%Y%m%d")"
   VER="$VER-$ymd.$REV"
fi

# Install/update JS deps.
bower install

# Set up the distro dir.
DISTRO_DIR="$ROOT_DIR/distro/$BIN-$VER"
[ ! -d "distro" ] && mkdir distro
[ -d "$DISTRO_DIR" ] && rm -rf "$DISTRO_DIR"
mkdir "$DISTRO_DIR"
cd "$DISTRO_DIR"

# Copy the scripts, but remove this build script.
cp "$ROOT_DIR/scripts/"* .
rm build

# Copy index.hml replacing "v<version>" with this version.
sed -e "s/v[0-9].[0-9].[0-9]/v$VER/" "$ROOT_DIR/index.html" > index.html

# Copy the AngularJS app.
cp -R "$ROOT_DIR/client" ./client/

# Copy only the needed 3rd-party JS scripts, i.e. ones loaded by index.html.
mkdir bower_components
for file in $(perl -ne 'm/(bower_components[^"]+)/ and print $1, "\n"' "$ROOT_DIR/index.html"); do
   dir="$(dirname $file)"
   mkdir -p "$dir"
   cp "$ROOT_DIR/$file" "$dir"
   if [ -e "$ROOT_DIR/$file.map" ]; then
       cp "$ROOT_DIR/$file.map" "$dir"
   fi
   if [ -e "$ROOT_DIR/${file%.*}.map" ]; then
       cp "$ROOT_DIR/${file%.*}.map" "$dir"
   fi
done

# Copy all of Bootstrap.
cp -R "$ROOT_DIR/bower_components/bootstrap/dist/"* bower_components/bootstrap/dist

# Copy fonts
cp -R "$ROOT_DIR/bower_components/font-awesome/fonts/" ./bower_components/font-awesome/fonts/

# Go up one dir to distro/ and tarball the disto dir.
cd ..
tar cvfz $BIN-$VER.tar.gz $BIN-$VER/ > /dev/null

echo
echo "Done building distro/$BIN-$VER.tar.gz"
echo
