# copy_baseos_files_awk
#
# This script is used to update the files on the boot partition of the 16M flash card
# that are not part of the base cramfs image.  The baseOS SDF is parsed
# to determine which files to copy into the boot partition.

$1 !~ /[Hh][Ee][Aa][Dd]/ {                   
	# Not the HEAD statement in the SDF.  Loop through the tags and values.
	type = toupper($1)
	i = 2
        compressed="FALSE"
                          
	while (i <= NF)
	{
		# Get the next tag and value
		tag = toupper($i)
		i++
		value = $i

		# If the value starts with a quote then append into value 
		# from the current line until the closing quote is found.
		if (substr(value,1,1) == "'")	
		{
			valLen = length(value)
			while (substr(value,valLen,valLen) != "'")
			{
				i++
				temp = value
				value = sprintf("%s %s",temp,$i)	
				valLen = length(value)
			}
		}

		# Save the value depending on which tag it is.
		if (tag == "COMPRESSED")
		{
			compressed = toupper(value)
		} 
		if (tag == "SRC")
		{
			# Note: svrmount is the mount point
			# on the server to get the files from.
			# This is passed in thru the awk -v option.
			src = sprintf("%s%s",svrmount,value)
		}
		if (tag == "DEST")
		{
			dest = value
			# Strip off the file from the dest path 
			# and save the dest directory to be created
			# on the client.
		        if (match(dest, /^.*\//) > 0)
			{
				mkdir = substr(dest,1,RLENGTH-1)
			}
		}
		if (tag == "PERM")
		{
			perms = value
		}
		if (tag == "PRE")
		{
			pre = value
		}
		if (tag == "POST")
		{
			post = value
		}

		i++
	}

	# Check if this file is not part of the cramfs image
	if (compressed == "FALSE")
	{
		# Not part of the image.  Need to process the file.

		# If a pre script was specified, run it.
		if (length(pre) > 0)
		{
			gsub(/'/, "", pre)
			system(pre)
		}
	
		# If src and dest were specified, then process the file
		# depending on whether its type is FILE or TAR.
		if (length(src) > 0 && length(dest) > 0)
		{
			if (type == "FILE")
			{
				# FILE type
				# Make destination directory
	 			if (length(mkdir) > 0)
 				{
 					system("mkdir -p " mkdir)
 				}
				# Copy src to dest
	 			system("cp -afR " src " " dest)
			}
			else if (type == "TAR")
			{
				# TAR type
				# Untar to the dest directory
 				system("tar -xzf " src " -C " dest)
			}
		}

		# If perms were specified then chmod the dest file.
		if (length(perms) > 0)
		{
			system("chmod " perms " " dest)
		}

		# If a post script was specified, run it.
		if (length(post) > 0)
		{
			gsub(/'/, "", post)
			system(post)
		}
	}
}
