#!/bin/bash
cd "${0%/*}" || exit
. ${WM_PROJECT_DIR:?}/bin/tools/RunFunctions

function getValue()
{
	what=$1
	from=$2
	grep ^$what $from | awk '{$1=$1;print}' | cut -d' ' -f2 | tr -d ';'
}

### SERIAL

mkdir -p constant/triSurface pre
runApplication surfaceConvert input/buildings.obj constant/triSurface/buildings.stl

# forest from the mesher becomes a porous canopy zone
if [ -f input/forest.obj ]; then
	awk -f awk/forestshell.awk input/forest.obj > constant/triSurface/forest.stl
	cp constant/fvOptions.forest constant/fvOptions.tree
	cp system/forestGeometry system/forestRegion pre/
else
	# parallel snappyHexMesh aborts on a missing #includeIfPresent file
	: > pre/forestGeometry
	: > pre/forestRegion
fi

cellMax=$(getValue cellMax uap_simple.cfg)
height=$(getValue minHeight uap_simple.cfg)

# create ground.stl
# echo "awk -f awk/genground.awk -v cs=$cellMax -v xg=4 constant/triSurface/buildings.stl > constant/triSurface/ground.stl"
awk -f awk/genground.awk -v cs=$cellMax -v xg=4 constant/triSurface/buildings.stl > constant/triSurface/ground.stl

# create central refinement volume
awk -f awk/genrefinement.awk -v cs=$cellMax -v xg=4 constant/triSurface/buildings.stl > constant/triSurface/central_box_constraint.stl

# bbox
awk -f awk/stlminmax.awk constant/triSurface/buildings.stl > pre/bbox_buildings
awk -f awk/stlminmax.awk constant/triSurface/ground.stl > pre/bbox_ground

# various params
awk -f awk/blockmeshparams.awk -v cs=$cellMax -v vh=$height constant/triSurface/ground.stl  > pre/blockmeshparams
awk -f awk/locationInMesh.awk -v cs=$cellMax -v vh=$height constant/triSurface/ground.stl > pre/locationInMesh
awk -f awk/boxCentre.awk -v cs=$cellMax -v vh=$height constant/triSurface/ground.stl > pre/boxCentre

# prep geo for meshing
runApplication surfaceFeatureExtract


# blockMesh
runApplication blockMesh
runApplication -s block checkMesh

# decomposition

runApplication decomposePar

### PARALLEL

runParallel snappyHexMesh -overwrite	# generate mesh
runParallel -s snappy checkMesh		# check mesh
runParallel renumberMesh -overwrite	# index renumbering
if [ -f constant/triSurface/forest.stl ]; then
	runParallel topoSet			# forest cellZone
fi

restore0Dir -processor			# set up initial conditions
cp uap*.cfg processor*			# copy headers
runParallel potentialFoam -writephi	# simulation kickin
runParallel simpleFoam			# Simulation

