#!/bin/bash
#
# Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved
#
# patchscript for security components Windows / JES4



date=`date +"%b\/%d\/%Y"`
Timestamp=$(date +%Y.%m.%d.%H.%M)

base_dir=`pwd`
security_base_dir="$base_dir/../.."

dest=${base_dir}/dist/patches

# Parameters:
# -p: directory containing the patch definition
# -b (optional): directory containing the new bits (zip files) to include in the patch
while getopts rp:b:f option
do
        case $option in
		p)      common=$OPTARG;;
        esac
done

if [ "$common" = "" ] ;
then
    echo "Usage $0 -p <patch_dir> [-b <build_location>]"
    exit 1
fi

if [ ! -d $common ] ;
then
	echo "No patch description at $common"
	exit 1
fi

common=`cd ${common};pwd`

echo "Using directory ${common} to build patch."

msys2dos () {
idir=$1
       echo $idir | sed -e "s|^/\(.\)/|\1:/|"
} # msys2dos

# Get component versions
get_nspr_mod () {
    from_file=$1
    search_string=$2
    value=`grep ^${search_string} ${from_file} | sed -e 's: *::g' -e 's|^.*=||g'`

    echo ${value}
}
get_nspr_version () {
    if [ -f  ${security_base_dir}/nspr/config/module.df ] ;
    then
      # NSPR 4.1
      search_file=${security_base_dir}/nspr/config/module.df
      nspr_mod_version=`get_nspr_mod ${search_file} MOD_VERSION`
      nspr_mod_minor=`get_nspr_mod ${search_file} MOD_MINOR`
      nspr_mod_patch=`get_nspr_mod ${search_file} MOD_PATCH`
      value=${nspr_mod_version}.${nspr_mod_minor}.${nspr_mod_patch}
    else
      # NSPR 4.4
	  value=`grep PR_VERSION ${security_base_dir}/nspr/pr/include/prinit.h | sed -e 's/"$//' -e 's/.*"//' -e 's/ .*//'`
    fi
    echo $value
}

nspr_version=`get_nspr_version`
nss_version=`grep NSS_VERSION ${security_base_dir}/nss/lib/nss/nss.h | head -1 | sed -e 's/[^"]*"//' -e 's/".*//' -e 's/ .*//' | cut -d. -f1-3`
jss_version=`grep JSS_VERSION ${security_base_dir}/jss/org/mozilla/jss/util/jssver.h | sed -e 's/"$//' -e 's/.*"//' -e 's/ .*//'`
jss_major=`echo $jss_version | cut -d . -f 1`

echo "NSPR $nspr_version"
echo "NSS $nss_version"
echo "JSS $jss_version"

build_readme () {
  echo "from template:"
  ls -l ${common}/patch.README
  
  # sed replaces the #xxx# values in the README
  # tr removes the Windows ^M (end of line) and ^Z (end of file)

  cat ${common}/patch.README | \
  sed \
  	  -e "s/#PATCHID#/${thispatchnum}/g" \
      -e "s/#PATCHID_BASE#/${patch_num}/g" \
      -e "s/#PATCH_REV#/${patch_rev}/g" \
      -e "s/#DATE#/${date}/g" \
      -e "s/#SECURITY_VERSION#/${security_version}/g" \
      -e "s/#NSPR_VERSION#/${nspr_version}/g" \
      -e "s/#NSS_VERSION#/${nss_version}/g" \
      -e "s/#JSS_VERSION#/${jss_version}/g" \
      -e "s/#DEPOT_NAME#/${thispatchnum}/g" \
      -e "/^#/d" \
   | tr -d '\15\32' \
   > ${thispatch}/README.${thispatchnum}
  
  err=$?
  if [ ! $err -eq 0 ] ;
  then
    echo "Unable to create README file (error $err)"
    exit 1
  fi
}

# get variable from patch.infos file
INFO_SEP==

get_info () {
    info_param=$1
    value=`grep ^$info_param$INFO_SEP ${common}/patch.infos | awk -F$INFO_SEP '{ print $2 }'`
    echo $value
}

JES4_basedir="JES4/Products/Shared"
# Create JES4 directory structure
create_layout_dir () {
	in_dir=$1
	
	lbase_dir=$in_dir/$JES4_basedir
	for sub_dir in lib bin include
	do
		echo "Creating directory $lbase_dir/$sub_dir"
		mkdir -p $lbase_dir/$sub_dir
		if [ ! $? -eq 0 ] ;
		then
			echo "Failed to create directory $lbase_dir/$sub_dir"
			exit 1
		fi
	done
} # create_layout_dir

# Create JES4 layout from sbi (lib, bin, include)
nozip_layout () {
	from_dir=$1
	to_dir=$2
	
	lbase_dir=$to_dir/$JES4_basedir
	for sub_dir in lib bin include
	do
		echo "Copying files from $from_dir/$sub_dir to $lbase_dir/$sub_dir"
		cp -r $from_dir/$sub_dir/* $lbase_dir/$sub_dir
		if [ ! $? -eq 0 ] ;
		then
			echo "Failed to copy files from $from_dir/$sub_dir to $lbase_dir/$sub_dir"
			exit 1
		fi
	done
	# Add jss4.jar from the directory before WINNT5.0_OPT.OBJ
	# reference_build is typically R:/security/SECURITY_3_10_20050729/WINNT5.0_OPT.OBJ
	cp $from_dir/../jss4.jar $lbase_dir/lib
} # nozip_layout

# Create JES4 layout from zip files
unzip_layout () {
	zip_dir=$1
	
	lbase_dir=$zip_dir/$JES4_basedir
	for zip_file in $(ls $zip_dir/*.zip)
	do
		zip_name=$(basename $zip_file .zip)
		tmp_dir=$zip_dir/tmp_$zip_name
		echo "Unzipping file $zip_file to $tmp_dir"
		mkdir -p $tmp_dir
		cd $tmp_dir
		unzip -o $zip_file
		echo "Copying content of $zip_file to $lbase_dir"
		for sub_dir in lib bin include
		do
			cp -r */$sub_dir/* $lbase_dir/$sub_dir
			# don't check result because the $sub_dir may not exist.
		done
		cd ${zip_dir}
		rm -rf $tmp_dir
	done
} # unzip_layout

create_ini_file () {
	ini_dir=$1
	ini_file=$2
	ism_file=$3
	
	ini_filename=$ini_dir/$ini_file
	
	# Change MSYS drive to DOS
	ini_dir_dos=$(msys2dos $ini_dir)
	# Replase Unix / with Windows \
	ini_dir_win=$(echo $ini_dir_dos | sed -e 's|/|\\|g')
	
	echo "Creating file $ini_filename"
	
	cat >$ini_filename << EOF_INI
[Project]    
Name="$ini_dir_win\\$ism_file"
BuildLabel=security
CompileScript=yes
      
[Release]    
BuildFlags=SHARED_Patch
Configuration=
Name=Release 1
SetupEXE=
      
[Mode]    
CubFile=
Silent=no
StopOnFirstError=no
CompileOnly=no
BuildTablesRefreshFiles=no
BuildTablesOnly=no
UpgradeOnly=no
Verbose=yes
WarningAsError=no
      
[BuildLocation]    
Path="$ini_dir_win"
EOF_INI

} # create_ini_file

# parse info files for this patch
patch_rev=`get_info REV`
patch_num=`get_info PATCH_NUM`
security_version=`get_info SECURITY_VERSION`
reference_build=`get_info REFERENCE_BUILD`
jss3_reference_build=`get_info JSS3_REFERENCE_BUILD`

echo "========================================"
echo "patch_rev=$patch_rev"
echo "patch_num=${patch_num}"
echo "========================================"

##############################################################
# Verifying the set of tools needed for the Windows installer
##############################################################
echo "========================================"
echo "Verifying the list of tools needed for the Windows installer"
# ANT
echo "ANT:"
which ant
if [ ! $? -eq 0 ] ;
then
	echo "ANT is required"
	echo "PATH=$PATH"
	exit 1
fi
# InstallShield
echo "IsSABld.exe (StandAlone InstallShield 11.5):"
which IsSABld.exe
if [ ! $? -eq 0 ] ;
then
	echo "IsSABld.exe is required"
	echo "PATH=$PATH"
	exit 1
fi
# UUIDGEN.exe (from MSVC)
echo "UUIDGEN.exe:"
which UUIDGEN.exe
if [ ! $? -eq 0 ] ;
then
	echo "UUIDGEN.exe is required (from MSVC)"
	echo "PATH=$PATH"
	exit 1
fi
# make
echo "MAKE:"
MAKE="gmake.exe"
which $MAKE
if [ ! $? -eq 0 ] ;
then
       MAKE="make.exe"
       which $MAKE
       if [ ! $? -eq 0 ] ;
       then
               echo "MAKE not found (tried gmake.exe and make.exe)"
               exit 1
       fi
fi
echo "MAKE=${MAKE}"
# JAVA_HOME
if [ -z "$JAVA_HOME" ] ;
then
	echo "JAVA_HOME must be set"
	exit 1
fi
# ANT_HOME
if [ -z "$ANT_HOME" ] ;
then
	echo "ANT_HOME must be set"
	exit 1
fi
# SUBST
SUBST=/C/WINNT/SYSTEM32/SUBST.exe

echo "========================================"

  # Build dir
  patch_build_dir=build/${patch_num}
  rm -rf ${patch_build_dir}
  mkdir -p ${patch_build_dir}

  thispatchnum=${patch_num}-${patch_rev}
  thispatch=${dest}/${thispatchnum}

echo "---------------------- Begin creation of the patch ----------------------"
echo "thispatch=$thispatch"

###########################
# Delete the old stuff
###########################
  if [ -d ${thispatch} ]; then
     echo "removing any previously built version of this patch"
     rm -rf ${thispatch}
  fi

###################################
# Create the patch output directory
##################################
  if [ ! -d ${thispatch} ]; then
     mkdir -p ${thispatch}
  fi

###############################
# Create README.<patchnum> file
###############################
echo "========================================"

  echo "======building readme...."
  build_readme
  echo "======done building readme...."

###############################
# Adding copyright file
###############################
  echo "Copying copyright file from ${common} to ${thispatch}"
  cp ${common}/copyright ${thispatch}
  if [ ! $? -eq 0 ] ;
  then
	echo "error cp copyright"
	exit 1
  fi
  echo "========================================"

###############################
# Create the installer patch
################################
# See documentation of this process at
# http://multiplatform.sfbay.sun.com/Wiki.jsp?page=JES4WindowsPatchCreation1
################################

OBJDIR=WINNT5.0_OPT.OBJ

MOZDIST=${security_base_dir}/mozilla/dist/${OBJDIR}/pkgarchive

installer_build_dir=${base_dir}/${patch_build_dir}/installer
rm -rf ${installer_build_dir}
mkdir -p ${installer_build_dir}
installer_jes4_dir=${installer_build_dir}/src/installer/JES4
ref_ism_file=SUNJES_JES4RR.ism
new_ism_file=SUNJES.ism


# Get patch build workspace from CVS -----------------------------------------
echo "========================================"
echo "Checking installer from CVS"
echo "========================================"

cd ${installer_build_dir}
# Check out the JES4 ISM,Installer related source and patch build scripts.
CVSROOT=:pserver:svbld@jescvs.us.oracle.com:/sw/jeswindows 
cvs co -l src/installer/JES4
err1=$?
cvs co src/installer/JES4/sunjes "src/installer/JES4/Patch/patch scripts"
err2=$?
if [ ! $err1 -eq 0 ] || [ ! $err2 -eq 0 ] ;
then
	echo "Unable to check out src/installer/JES4"
	echo "CVSROOT=$CVSROOT"
	exit 1
fi
# Change "patch scripts" into "patch_scripts"
echo "========================================"
echo "Renaming [patch scripts] into [patch_scripts]"
mv "${installer_jes4_dir}/Patch/patch scripts" ${installer_jes4_dir}/Patch/patch_scripts
if [ ! $? -eq 0 ] ;
then
	echo "Unable to rename patch scripts into patch_scripts"
	exit 1
fi

# Save the ISM file
echo "========================================"
echo "The SUNJES.ism has to be saved to allow checkout of the JES4_MP_RR ism"
mv ${installer_jes4_dir}/SUNJES.ism ${installer_jes4_dir}/SUNJES.ism_new
if [ ! $? -eq 0 ] ;
then
	echo "Unable to save the new ISM file to src/installer/JES4/SUNJES.ism_new"
	exit 1
fi

# Get the JES4 RR ISM file
cvs co -r JES4_MP_RR_installer src/installer/JES4/SUNJES.ism
if [ ! $? -eq 0 ] ;
then
	echo "Unable to check out JES4_MP_RR_installer src/installer/JES4/SUNJES.ism"
	echo "CVSROOT=$CVSROOT"
	exit 1
fi
mv ${installer_jes4_dir}/SUNJES.ism ${installer_jes4_dir}/${ref_ism_file}
#mv ${installer_jes4_dir}/SUNJES.ism_new ${installer_jes4_dir}/SUNJES.ism
cp ${common}/SUNJES.ism ${installer_jes4_dir}/SUNJES.ism

# Get the JES4 bits -------------------------------------------------
echo "========================================"
echo "Getting the JES4 bits for reference"
echo "========================================"

# Note: there was no zip files for JES4. Copying directly from bin|lib|include
zip_ref_dir=${installer_build_dir}/zip_ref
create_layout_dir ${zip_ref_dir}
nozip_layout ${reference_build} ${zip_ref_dir}
if [ ! $? -eq 0 ] ;
then
	echo "Unable to copy reference files (nozip) from ${reference_build}"
	exit 1
fi
cp ${jss3_reference_build}/*.zip ${zip_ref_dir}
if [ ! $? -eq 0 ] ;
then
	echo "Unable to copy JSS3 reference zip files from ${jss3_reference_build}"
	exit 1
fi
# Create layout
unzip_layout ${zip_ref_dir}

# Copy the new zip files -------------------------------------------------------
echo "========================================"
echo "Getting the new bits"
echo "========================================"

zip_new_dir=${installer_build_dir}/zip_new
mkdir -p ${zip_new_dir}
echo "Copying new bits from ${MOZDIST}"
cp ${MOZDIST}/*.zip ${zip_new_dir}
if [ ! $? -eq 0 ] ;
then
	echo "Unable to copy new zip files from ${MOZDIST}"
	exit 1
fi
# We keep the same JSS3 version here.
cp ${jss3_reference_build}/*.zip ${zip_new_dir}
if [ ! $? -eq 0 ] ;
then
	echo "Unable to copy JSS3 reference zip files from ${jss3_reference_build}"
	exit 1
fi
# Create layout
create_layout_dir ${zip_new_dir}
unzip_layout ${zip_new_dir}

patch_script_dir=${installer_jes4_dir}/Patch/patch_scripts
# Modify PatchBuildProperties.mk ----------------------------------------------
echo "========================================"
echo "Modifying the build files to create our NSS_NSPR_JSS patch"
echo "========================================"
echo "--- PatchBuildProperties.mk ---"
old_file=${patch_script_dir}/PatchBuildProperties.mk_old
new_file=${patch_script_dir}/PatchBuildProperties.mk
installer_jes4_dir_dos=$(msys2dos $installer_jes4_dir)
patch_script_dir_dos=$(msys2dos ${patch_script_dir})
# Save original file
mv ${new_file} ${old_file}
# Replace values
cat ${old_file} | sed \
  -e "s|<SUNW PRODUCT NAME>|NSS_NSPR_JSS|g" \
  -e "s|<PRODUCT NAME>|NSS_NSPR_JSS|g" \
  -e "s|<PRODUCT VERSION>|${security_version}|g" \
  -e "s|<SHORT NAME OF THE PRODUCT>.*|NSS_NSPR_JSS|g" \
  -e "s|<PATCH ID>|${thispatchnum}|g" \
  -e "s|<PATH TO PATCH_SCRIPTS>|${patch_script_dir_dos}|g" \
  -e "s|<PATH TO REFERENCE MSI>|${installer_jes4_dir_dos}/security/Release 1/DiskImages/DISK1/Sun Java(TM) Enterprise System.msi|g" \
  -e "s|<LOCATION OF TARGET ISM>|${installer_jes4_dir_dos}|g" \
  -e "s|<FEATURE_NAME>|ALL|g" \
  -e "s|<PATCH FLAG>|SHARED_Patch|g" \
  -e "s|<PATCH_REVISION>|${patch_rev}|g" \
> ${new_file}

echo "PatchBuildProperties.mk modified with current patch values"
echo "-------------------------------------------------------------------------"
cat ${new_file}
echo "-------------------------------------------------------------------------"

# Modify UpdatePCP.pl ----------------------------------------------------------
echo "--- UpdatePCP.pl ---"
old_file=${patch_script_dir}/UpdatePCP.pl_old
new_file=${patch_script_dir}/UpdatePCP.pl
# Save original file
mv ${new_file} ${old_file}
# Replace values
cat ${old_file} | sed \
  -e "s/REINSTALLMODE=o/REINSTALLMODE=e/g" \
  -e "s/<GUID_OUT>/\`uuidgen.exe\`/" \
> ${new_file}
echo "UpdatePCP.pl updated with REINSTALLMODE=e"

# Modify BUGLIST.template ------------------------------------------------------
echo "--- BUGLIST.template ---"
old_file=${patch_script_dir}/BUGLIST.template_old
new_file=${patch_script_dir}/BUGLIST.template
# Save original file
mv ${new_file} ${old_file}
# Replace values
cat ${old_file} | sed \
  -e "s/<BUGID>/${thispatchnum}/g" \
> ${new_file}
echo "BUGLIST.template update with Patch ID ${thispatchnum}"

# Create sunjes_JES4RR.ini -----------------------------------------------------
echo "--- sunjes_JES4RR.ini ---"
create_ini_file ${installer_jes4_dir} sunjes_JES4RR.ini ${ref_ism_file}
# Modify sunjes_.ini -----------------------------------------------------------
echo "--- sunjes.ini ---"
create_ini_file ${installer_jes4_dir} sunjes.ini ${new_ism_file}

# Mapping G: drive to JES4 binaries --------------------------------------------
echo "========================================"
echo "Mapping G: drive to JES4 binaries"
echo "========================================"

# ${SUBST} //d G:
# ${SUBST} G: ${zip_ref_dir}
# if [ ! $? -eq 0 ] ;
# then
# 	echo "Unable to subst G: ${zip_ref_dir}"
# 	exit 1
# fi
# cmd //c dir G:\\
rm -rf /g/JES4
cp -r ${zip_ref_dir}/JES4 /g/

# Run IsSABld with reference binaires ------------------------------------------
echo "========================================"
echo "Running IsSABld with JES4 reference bits"
echo "========================================"

IsSABld -i ${installer_jes4_dir_dos}/sunjes_JES4RR.ini
echo "There may be some errors above because we don't bring the whole JES4 distribution."

# Mapping G: drive to new binaries --------------------------------------------
echo "========================================"
echo "Mapping G: drive to new binaries"
echo "========================================"

# ${SUBST} //d G:
# ${SUBST} G: ${zip_new_dir}
# if [ ! $? -eq 0 ] ;
# then
# 	echo "Unable to subst G: ${zip_new_dir}"
# 	exit 1
# fi
# cmd //c dir G:\\
rm -rf /g/JES4
cp -r ${zip_new_dir}/JES4 /g/

# Run installer build ----------------------------------------------------------
echo "========================================"
echo "Building the patch: gmake createWinPatch"
echo "========================================"

cd ${patch_script_dir}
${MAKE} createWinPatch
if [ ! $? -eq 0 ] ;
then
	echo "gmake createWinPatch failed"
	exit 1
fi

# Copy exe and uninstall batch to patch location -------------------------------
echo "========================================"
echo "Copying the files to the patch directory"
echo "========================================"

echo "Copying patch EXE:"
ls ${installer_jes4_dir}/${thispatchnum}/${thispatchnum}.exe
cp ${installer_jes4_dir}/${thispatchnum}/${thispatchnum}.exe ${thispatch}
if [ ! $? -eq 0 ] ;
then
	echo "Error cp patch EXE"
	exit 1
fi

echo "Copying patch Uninstall BAT:"
ls ${installer_jes4_dir}/${thispatchnum}/Uninstall_${thispatchnum}.bat
cp ${installer_jes4_dir}/${thispatchnum}/Uninstall_${thispatchnum}.bat ${thispatch}
if [ ! $? -eq 0 ] ;
then
	echo "error cp patch Uninstall BAT"
	exit 1
fi

# Remove installer build workspace to save space
echo "========================================"
echo "Saving modified files"
echo "========================================"

cp ${patch_script_dir}/PatchBuildProperties.mk ${base_dir}/${patch_build_dir}
cp ${patch_script_dir}/UpdatePCP.pl ${base_dir}/${patch_build_dir}
cp ${patch_script_dir}/BUGLIST.template ${base_dir}/${patch_build_dir}
cp ${installer_jes4_dir}/sunjes_JES4RR.ini ${base_dir}/${patch_build_dir}
cp ${installer_jes4_dir}/sunjes.ini ${base_dir}/${patch_build_dir}

echo "========================================"
echo "Removing installer workspace"
echo "========================================"

cd ${base_dir}
rm -rf ${installer_build_dir}
#${SUBST} //d G:
rm -rf /g/JES4

# -------------------------------------------
echo "----------done creating Windows patches for JES4 --------------"
