#!/bin/bash

# This script is called each time a nightly GS file (binary or otherwise) gets uploaded to www-internal
# to the caveat-emptor folder. This script is called from 
# nzdl@www-internal:[522]~/.ssh$ less authorized_keys


######### GLOBAL VARS #########

# http://stackoverflow.com/questions/1401482/yyyy-mm-dd-format-date-in-shell-script
# we want . as separator to produce: yyyy.mm.dd

today=`date +%Y.%m.%d`

# http://askubuntu.com/questions/367136/how-do-i-read-a-variable-from-a-file

gs2version=`cat /greenstone/greenstone.org/base/next-release.txt`
gs3version=`cat /greenstone/greenstone.org/base/next-release-greenstone3.txt`

# array of string literals of source component/distribution suffixes

source_suffixes=("source-component.tar.gz" "source-component.zip" "source-distribution.tar.gz" "source-distribution.zip")

# static array of string literals representing the caveat file suffixes we're interested in
# see also 'Adding New Elements to the Original Array' 
# at http://www.yourownlinux.com/2013/10/working-with-arrays-in-bash-scripting.html

# Mac Leopard binaries are no longer automatically generated
# (as I can't even log into our Mac Leopard machine)
#suffixes=("linux" "linux-x64" "Lion-MacOS-intel.dmg" "MacOS-intel.dmg" "windows.exe" ${source_suffixes[@]})
#suffixes=("linux" "linux-x64" "Lion-MacOS-intel.dmg" "windows.exe" ${source_suffixes[@]})
#currently have no macs auto building - edit this once we have mac parallels running
binary_suffixes=("linux" "linux-x64" "windows.exe" "windows-x64.exe" "Monterey-MacOS-intel.dmg")
suffixes=(${binary_suffixes[@]} ${source_suffixes[@]})

gs2_bin_prefix=Greenstone-$gs2version-candidate-$today-
gs3_bin_prefix=Greenstone-$gs3version-candidate-$today-

#echo "Date is $today"
#echo "gs2ver is $gs2version"
#echo "gs3ver is $gs3version"
#echo "gs2_bin_prefix is $gs2_bin_prefix" 
#echo "gs3_bin_prefix is $gs3_bin_prefix"

caveat_dir=/greenstone/greenstone.org/base/caveat-emptor/
snapshots_dir=/greenstone/greenstone.org/base/release-snapshots/
latest_dir=${caveat_dir}latest/

###############################

# Function that checks whether all of today's binaries for a gs_version (GS2 or GS3) are 
# present in the caveat folder
# If so, it copies those bins over into the release-snapshots folder under new names

# Non-ambiguous string concatenation: ${varname}string-literal
# stackoverflow.com/questions/4181703/how-can-i-concatenate-string-variables-in-bash

function snapshots_for_gs_version () {

    # Local vs global variables in functions
    # http://www.tldp.org/LDP/abs/html/localvar.html

    local gs_version=$1

    #check if we've found all gs_version nightly binaries
    local foundallbins=true
    
    for suffix in ${suffixes[@]}; do
	local file=$caveat_dir
	if [ "$gs_version" == "2" ]; then
	    file=$file$gs2_bin_prefix$suffix
	else
	    file=$file$gs3_bin_prefix$suffix
	fi

	if [ ! -f $file ]; then
	    echo "File does not exist: $file"
	    foundallbins=false
	#else
	    #echo "File exists: $file"
	fi
    done

    echo ""

    if [ "$foundallbins" == "true" ]; then
	echo "All gs$gs_version binaries for $today generated"
	echo ""

	# delete the old stables
	echo "Deleting ${snapshots_dir}Greenstone-${gs_version}s*"
	rm ${snapshots_dir}Greenstone-${gs_version}s*
	echo ""
	
	# copy the gs2 binaries to release-snapshots folder
	# under the new name Greenstone-${gs_version}sDATE-suffix, where gs_version = 2|3
	# Use hardlinking instead of copy to save space

	for suffix in ${suffixes[@]}; do	
	    local file=$caveat_dir
	    if [ "$gs_version" == "2" ]; then
		file=$file$gs2_bin_prefix$suffix
	    else
		file=$file$gs3_bin_prefix$suffix
	    fi
	    local newfile=${snapshots_dir}Greenstone-${gs_version}s${today}-$suffix
	    
	    # http://askubuntu.com/questions/108771/what-is-the-difference-between-a-hard-link-and-a-symbolic-link
	    # Q & A: The difference between hard and soft links at http://linuxgazette.tuwien.ac.at/105/pitcher.html
	    echo "Hardlinking file $file as $newfile"
	    ln $file $newfile

	done
	
    else
	echo "Not all gs${gs_version} binaries for $today have been generated. (foundallbins: $foundallbins)"
    fi

    echo ""


    # cdrom components only for GS2

    if [ "$gs_version" == "2" ]; then    

	echo "GS2 CD ROM components"
	echo ""

	cd_suffixes=("linux" "linux-x64" "Lion-mac" "mac" "full-windows" "windows")
	cdfile_src=cdrom-components-${gs2version}-candidate-${today}-

	local foundallcds=true

	for suffix in ${cd_suffixes[@]}; do

	    local file=${caveat_dir}$cdfile_src${suffix}.tar.gz

	    if [ ! -f $file ]; then
		foundallcds=false
		echo "Could not find cdrom component $file"
	    fi
	done
	
	# if all cdrom components present, then copy across under new names
	if [ "$foundallcds" == "true" ]; then

	    # delete the old cdrom components from release-snapshots
	    echo "Deleting ${snapshots_dir}cdrom-components-2s*"
	    rm ${snapshots_dir}cdrom-components-2s*
	    echo ""
	    
	    # copy across the new cdrom components
	    # use hardlinking instead of copying to save space

	    for suffix in ${cd_suffixes[@]}; do

		local srcfile=${caveat_dir}$cdfile_src${suffix}.tar.gz
		local destfile=${snapshots_dir}cdrom-components-2s${today}-${suffix}.tar.gz
		echo "Hardlinking $srcfile as $destfile"
		ln $srcfile $destfile
	    done
	fi

	echo ""
    fi
    

}

# Inspect the most recently added file in the caveat folder and iff it's a GS binary or src file,
# create a hardlink for it under the appropriate name in the 'latest' subfolder
# and delete the earlier variant of the same in 'latest'.
# In time may have to start including the GS documented examples archive files generated overnight.
#
# General: http://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash

function make_latest () {
    
    echo ""
    #echo "In MAKE_LATEST"

    # Using local variable to loop through files, seen in http://mywiki.wooledge.org/ParsingLs
    local latest
    local file
    local suffix
    
    # find the latest file in caveat, since this script is called upon each upload to puka's caveat
    # http://stackoverflow.com/questions/5885934/bash-function-to-find-newest-file-matching-pattern
    # http://mywiki.wooledge.org/BashFAQ/003
    # http://tldp.org/LDP/abs/html/fto.html, where f1 -nt f2 means file f1 is newer than file f2 
    # http://superuser.com/questions/687523/get-the-last-file-name-in-a-variable-in-bash

    unset -v latest
    #for file in "${caveat_dir}"*; do
    #then file would be the full path. Instead, cd into the caveat dir to just get the filename
    cd $caveat_dir
    for file in *; do
	[[ -f $file ]] && [[ "$file" == "Greenstone"* ]] && [[ "$file" != *"Greenstone3-latest-source.tar.gz" ]] && [[ $file -nt $latest ]] && latest=$file
    done
    cd -

    # latest will not be undef, because this script is only ever called upon a legitimate
    # file upload into puka's caveat-emptor location    
    # e.g. for testing, latest=Greenstone-3.07-candidate-2015.06.30-linux-x64

    echo "Latest file in caveat is: $latest"

    # splits the filename $latest by hyphens, -, and then gets the 2nd substring
    # in this case the GS2 or GS3 full version number
    # http://stackoverflow.com/questions/428109/extract-substring-in-bash

    local matchfile=`echo $latest| cut -d'-' -f 2`
    echo "Found gs version prefix: $matchfile"

    # Iff this is a GS binary/src file that we want to maintain in the caveat/latest folder,
    # then remove the older version of the same file from caveat/latest folder, if any,
    # and hardlink the latest file into caveat/latest

    # Check whether the latest file ends with the binary/src suffix
    # https://viewsby.wordpress.com/2013/09/06/bash-string-ends-with/
    # single or double square brackets for testing conditions, [] vs [[]]
    # http://stackoverflow.com/questions/669452/is-preferable-over-in-bash-scripts
    # Need double brackets below, [[]], for string expansion with wildcard


    # if the latest file is a src component or src dist, then all src comps and dists
    # would have been uploaded simultaneously for that GS version. Check they're all there
    # and remove any older equivalents in the caveat/latest directory. Then copy all the 
    # *source* files for this GS version over to caveat/latest

    echo ""
    if [[ "$latest" == *"-source-"* ]]; then
	echo "copying source dists to latest"
	for suffix in ${source_suffixes[@]}; do
	    local srcfile=Greenstone-${matchfile}-candidate-${today}-${suffix}
	    local regexfile=Greenstone-${matchfile}-candidate-*-${suffix}
	    if [[ -f ${caveat_dir}$srcfile ]]; then
		echo "Removing ${latest_dir}$regexfile"
		echo "and replacing with ${latest_dir}$srcfile"
		rm ${latest_dir}$regexfile
		ln ${caveat_dir}$srcfile ${latest_dir}$srcfile
	    fi
	done

    elif [[ "$latest" == *"documented-examples-"* ]]; then
	echo "copying DEC dists to latest"

	# both documented examples zip and tar.gz files would have been generated and uploaded together
	
	local file=Greenstone3-documented-examples-${today}
	local re_file=Greenstone3-documented-examples-*
	local dec_exts=(".tar.gz" ".zip")

	for ext in ${dec_exts[@]}; do
	    if [[ -f ${caveat_dir}${file}.tar.gz ]]; then

		echo "Removing ${latest_dir}${re_file}${ext}"
		echo "and replacing with ${latest_dir}${file}${ext}"

		rm ${latest_dir}${re_file}${ext}
		ln ${caveat_dir}${file}${ext} ${latest_dir}${file}${ext}
	    fi
	done
	
    else
	# not src component or dist, but binary file, which are uploaded one at a time.

	for suffix in ${binary_suffixes[@]}; do
	    if [[ "$latest" == *"$suffix" ]]; then
		echo "Found that suffix matched: $suffix"
		
		matchfile=${latest_dir}Greenstone-${matchfile}-candidate-*-${suffix}
		
       	    # remove the matching file from the caveat/latest folder
	    # we don't know it's date, so we substituted that portion with a * as wildcard
	    # E.g. matchfile=<caveat>/latest/Greenstone-2.87-candidate-*-source-component.tar.gz
		
		echo "Removing $matchfile"
		rm $matchfile
		
	    # make a hardlink of the $latest file into the caveat_latest folder
		echo "Making a hardlink to ${caveat_dir}$latest in ${latest_dir}$latest"
		ln ${caveat_dir}$latest ${latest_dir}$latest
	    #else
		#echo "$latest did not match $suffix"
	    fi
	done
    fi

    echo ""
}


# The windows diffcol report has some extra permissions that prevent it from being viewable
# on the caveat page. But if we copy it, it's no longer a problem
function rename_win_diffcol_report () {
    cp diffcol-MSWin32-report-3-${today}.htm diffcol-MSWin32-report-3-${today}.html
    mv diffcol-MSWin32-report-3-${today}.html diffcol-MSWin32-report-3-${today}.htm

    cp diffcol-FAIL-MSWin32-report-3-${today}.htm diffcol-FAIL-MSWin32-report-3-${today}.html
    mv diffcol-FAIL-MSWin32-report-3-${today}.html diffcol-FAIL-MSWin32-report-3-${today}.htm
}

####################

# the 'main'

# This script is called upon each upload to puka's caveat-emptor by 
# the file nzdl@puka:[522]~/.ssh/authorized_keys 

# Check if conditions are true to create snapshots out of today's GS2 bins, these conditions 
# being that all src and bins of GS2 have been generated for today. 
# And if so, hardlink these src and bin files into the release-snapshots dir.
# Repeat for GS3.
# Finally, for each uploaded file that is a Greenstone src or binary file in caveat
# hardlink it into the caveat/latest folder to keep a copy of the most-recent version of that 
# bin/file that was successfully generated.

rename_win_diffcol_report
snapshots_for_gs_version "2"
snapshots_for_gs_version "3"
make_latest
