#!/bin/bash
# Copyright 2018 Big Switch Networks, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

# Following build params expected for this script:
# CONFLUENCE_USER
# CONFLUENCE_TOKEN
# DOCKER_REGISTRY
# FORCE_UPLOAD (optional, boolean, default = false)

# print command and output for every line. verbosity++
set -eux

git clean -fxd
GIT_REPO=`pwd`

# fetch tags before going to the container.
# since ssh keys are not usable inside the container
git fetch --tags

case "$GIT_BRANCH" in
    *"master"*) echo "RELEASE JOB NOT REQUIRED FOR MASTER BRANCH. SKIPPING."; exit 0
esac

# set a few constants based on git branch to be used by the build job
# GIT_TAG_REGEX = regular expression used to get tag number
# PAGE_ID = wiki page ID to be updated with tarball
# OSP_REL_NAME = openstack release name to be used in tarball name
case "$GIT_BRANCH" in
  *"rocky"*)
    GIT_TAG_REGEX="13.*.*"
    PAGE_ID="866942996"
    OSP_REL_NAME="ROCKY"
    RHOSP_REL_NAME="RHOSP-14"
    ;;
  *"queen"*)
    GIT_TAG_REGEX="12.*.*"
    PAGE_ID="861044932"
    OSP_REL_NAME="QUEENS"
    RHOSP_REL_NAME="RHOSP-13"
    ;;
  *"pike"*)
    GIT_TAG_REGEX="11.*.*"
    PAGE_ID="861044928"
    OSP_REL_NAME="PIKE"
    RHOSP_REL_NAME="RHOSP-12"
    ;;
  *"ocata"*)
    GIT_TAG_REGEX="10.*.*"
    PAGE_ID="846594211"
    OSP_REL_NAME="OCATA"
    RHOSP_REL_NAME="RHOSP-11"
    ;;
  *"newton"*)
    GIT_TAG_REGEX="9.*.*"
    PAGE_ID="845905936"
    OSP_REL_NAME="NEWTON"
    RHOSP_REL_NAME="RHOSP-10"
    ;;
  *)
    echo "UNKNOWN BRANCH ENCOUNTERED. SKIPPING."
    exit 1
    ;;
esac


# get current latest version based on branch specific tag regex and ordering
# based on commit date
CURR_VERSION=`git for-each-ref refs/tags/$GIT_TAG_REGEX --sort="-*committerdate" --format="%(refname:short)" --count=1`

# fetch the tagged .tar.gz from pypi to pwd/dist directory
echo "Download tagged plugin package from PYPI"
mkdir dist
pip download networking-bigswitch==$CURR_VERSION --no-binary :all: --dest dist

echo "Building RPM packages"
DOCKER_IMAGE_RPM=$DOCKER_REGISTRY'/horizon-bsn-builder:latest'
BUILD_OS=centos7-x86_64

docker pull $DOCKER_IMAGE_RPM

BUILDDIR=$(mktemp -d)
mkdir -p $BUILDDIR/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}

# get changelog for tags
CHANGE_LOG=`git for-each-ref refs/tags/$GIT_TAG_REGEX --sort="-*committerdate" --format="* %(*committerdate:local) %(*authorname) %(*authoremail) - %(refname:short)%0a- %(subject)"`
# replace newline chars with \n
CHANGE_LOG="${CHANGE_LOG//$'\n'/\\n}"
# remove timestamp from changelog string
CHANGE_LOG=`echo "$CHANGE_LOG" | sed -E "s/[0-9]{2}:[0-9]{2}:[0-9]{2}\ //g"`
# replace variables in spec file
# change log can contain forward slash. so use % as delimiter for second sed expression
sed -i -e "s/\${version_number}/$CURR_VERSION/" -e "s%\${change_log}%$CHANGE_LOG%" rhel/python-networking-bigswitch.spec

cp dist/* $BUILDDIR/SOURCES/
cp rhel/*.service $BUILDDIR/SOURCES/
cp rhel/*.spec $BUILDDIR/SPECS/
cp build_packages/build-rhel-packages-inner.sh $BUILDDIR/build-rhel-packages-inner.sh

docker run -v $BUILDDIR:/rpmbuild $DOCKER_IMAGE_RPM /rpmbuild/build-rhel-packages-inner.sh

# Copy built RPMs to pkg/
BIGTOP_PARTIAL_PATH="$BUILD_OS/$GIT_BRANCH/tagged/$CURR_VERSION"
OUTDIR=$(readlink -m "pkg/$BIGTOP_PARTIAL_PATH")
rm -rf "$OUTDIR" && mkdir -p "$OUTDIR"
cp $BUILDDIR/RPMS/noarch/*.rpm "$OUTDIR"

# helper method to get version number
get_version () {
    RPM=$1;
    B=${RPM##*/};
    B=${B%-*};
    V=${B##*-};
}

# build a single tar with all plugin RPM files and yamls
DATE=`date +%Y-%m-%d-%H-%M`
ALL_RPM_YAML_TAR_DIR="$RHOSP_REL_NAME-$OSP_REL_NAME-PLUGINS-$DATE"
ALL_RPM_YAML_TAR_GZ="$ALL_RPM_YAML_TAR_DIR.tar.gz"
# 1. get yamls and customize scripts from BOSI
mkdir bosi
rsync -e 'ssh -o "StrictHostKeyChecking no"' -uva  bigtop:public_html/bosi/4.0.0/latest/* ./bosi
mv ./bosi/rhosp_resources/$GIT_BRANCH/yamls ./$ALL_RPM_YAML_TAR_DIR
mv ./bosi/rhosp_resources/$GIT_BRANCH/ivs/* ./$ALL_RPM_YAML_TAR_DIR

# 2. get neutron-bsn-lldp *.noarch.rpm from bigtop
rsync -e 'ssh -o "StrictHostKeyChecking no"' -uva bigtop:public_html/neutron-bsn-lldp/centos7-x86_64/origin/master/latest/*.noarch.rpm ./$ALL_RPM_YAML_TAR_DIR
LLDP_PKG="`ls ./$ALL_RPM_YAML_TAR_DIR/neutron-bsn-lldp*`"
get_version $LLDP_PKG
LLDP_VERSION=$V
echo "neutron-bsn-lldp version is" $LLDP_VERSION

# 3. update startup.sh and customize.sh with neutron-bsn-lldp pkg version
sed -i -e "s/\${lldp_version}/$LLDP_VERSION/" ./$ALL_RPM_YAML_TAR_DIR/customize.sh
sed -i -e "s/\${lldp_version}/$LLDP_VERSION/" ./$ALL_RPM_YAML_TAR_DIR/startup.sh
sed -i -e "s/\${lldp_version}/$LLDP_VERSION/" ./$ALL_RPM_YAML_TAR_DIR/README

# 4. get python-bsn-neutronclient*.noarch.rpm from bigtop
rsync -e 'ssh -o "StrictHostKeyChecking no"' -uva bigtop:public_html/python-bsn-neutronclient/centos7-x86_64/$GIT_BRANCH/latest/*.noarch.rpm ./$ALL_RPM_YAML_TAR_DIR

# 5. build a tarball and put it at $OUTDIR
tar -zcvf $OUTDIR/$ALL_RPM_YAML_TAR_GZ $ALL_RPM_YAML_TAR_DIR
cp dist/*.tar.gz "$OUTDIR"
git log > "$OUTDIR/gitlog.txt"
touch "$OUTDIR/build-$CURR_VERSION"
ln -snf $(basename $OUTDIR) $OUTDIR/../latest

rm -rf "$BUILDDIR"

# check if directory for current version exists on bigtop
REMOTE_CMD="[ -d /home/bsn/public_html/networking-bigswitch/$BIGTOP_PARTIAL_PATH ]"
if ( $FORCE_UPLOAD )
then
    echo "FORCE_UPLOAD set TRUE. Skipping check if version exists on bigtop."
elif ( ssh -o "StrictHostKeyChecking no" bigtop $REMOTE_CMD )
then
    # folder doesn't exist, rsync
    echo "THIS VERSION ALREADY EXISTS ON BIGTOP. EXITING."
    exit 0
fi

# if this version directory doesn't exist on BIGTOP, rsync it and update internal confluence wiki page
rsync -e 'ssh -o "StrictHostKeyChecking no"' -uva pkg/. bigtop:public_html/networking-bigswitch

# put a backslash before double quotes, hence triple backslash before double
# quotes \\\"
HTML_HREF="<a href=\\\"http://bigtop.eng.bigswitch.com/~bsn/networking-bigswitch/$BIGTOP_PARTIAL_PATH/$ALL_RPM_YAML_TAR_GZ\\\" class=\\\"external-link\\\" rel=\\\"nofollow\\\">$ALL_RPM_YAML_TAR_GZ</a>"

python ./build_packages/update_wiki.py "${CONFLUENCE_USER}" "${CONFLUENCE_TOKEN}" "${PAGE_ID}" "${HTML_HREF}"
