#!/bin/sh
#
# Synchronize InterMapper Settings directory from remote host via InterMapper SDK

set -e
set +x

InterMapperVersion="6.5.3"

# These are all POSIX standard utilities.
utilities="basename dirname uname id expr printf date sed awk"

# This is the manadatory workhorse command.
utilities="${utilities} curl"

# We can survive without these by quietly downgrading
# our user-friendliness or efficiency.
# utilities="${utilities} strings man ul ping nslookup"

program="$0"
for u in ${utilities} ; do
	if type "${u}" >/dev/null 2>&1 ; then
		if [ "x${u}" = "xbasename" ] ; then
			eval program=\`${u} \"\$0\"\`
		elif [ "x${u}" = "xcurl" ] ; then
			curlVersion=`eval "$u" --version 2>/dev/null |
						 sed -n -e "s/^${u} \\([.0-9][.0-9]*\\) .*\$/\\1/p"`
		fi
	else
		echo 1>&2 "${program}: cannot find \"${u}\" (PATH=\"${PATH}\")"
		exit 1
	fi
done

case `uname -s` in
	CYGWIN_NT*)
		platform="cygwin"
		regroot="/proc/registry/HKEY_LOCAL_MACHINE/Software/WOW6432Node"
		;;
	Darwin*)
		platform="macos"
		regroot=""
		;;
	Linux*)
		platform="linux"
		regroot=""
		;;
	*)
		echo 1>&2 "${program}: unrecognised platform \"`uname -s`\""
		exit 1
		;;
esac

case "${IM_2017_TEST}" in
    [1-9]*)
		limit=`echo "${IM_2017_TEST}" | tr -c -d '0-9'`
		case "${InterMapperVersion}" in
			@*@)
				;;
			*)
				echo 1>&2 "${program}: artificially limiting download to ${limit} items per directory"
				;;
		esac
		;;
	*)
		case "${InterMapperVersion}" in
			@*@)
				limit=10
				;;
			*)
				limit=
				;;
		esac
		;;
esac

local=`uname -n`
protocol="http"
port=""
user="admin"
password="password"
remote="intermapper1"
ipver="-4"
connectTime="20"
bounce=
needRestart=
inaccessibleMaps=
upgradableMaps=
quiet=
assumeCompatibility=
targetDir=
setTarget=""
logFile="/var/log/CloneIM.log"

if ( set -- -c ; getopts c "c" ) >/dev/null 2>&1 ; then
	:
else
	echo 1>&2 "${program}: cannot execute \"getopts\" command in this shell"
	exit 1
fi

USAGE="\
Usage: ${program} [-[bs]] [-S] [-q] [-C] [-v] [-h] [-r <remote-host>] \\
        [-P <protocol>] [-t <port>] [-u <user> [-p <password>]] \\
        [-D <target-dir>] [-L <log-file>] \\
            [<category> ...]"
secure=
showVersion=
setUser=
setPassword=
setProtocolOrPort=
while getopts 'bsSqChr:t:P:u:p:D:L:v' OPTION ; do
	case "$OPTION" in
		[bs])
			bounce="true"
			;;
		S)
			if [ -n "${setProtocolOrPort}" ] &&
					( [ "x${protocol}" = "xhttp" ] || [ "${port:-0}" -eq 80 ] ) ; then
				echo 1>&2 "${program}: cannot specify secure option (\"-S\") with protocol \"http\" or port #80"
				exit 1
			else
				secure="true"
				protocol="https"
			fi
			;;
		q)
			quiet="true"
			;;
		C)
			assumeCompatibility="true"
			;;
		L)
			case "${OPTARG}" in
				"-")
					logFile=""
					;;
				/*)
					if [ ! -e "${OPTARG}" ] ; then
						echo 1>&2 "${program}: warning log file \"${OPTARG}\" does not yet exist"
						logFile="${OPTARG}"
					elif [ ! -f "${OPTARG}" ] || [ ! -w "${logFile}" ] ; then
						echo 1>&2 "${program}: log file \"${OPTARG}\" is not a writable regular file"
						exit 1
					else
						logFile="${OPTARG}"
					fi
					;;
				*)
					echo 1>&2 "${program}: log file (\"${OPTARG}\") not specified by absolute path name"
					exit 1
					;;
			esac
			;;
		v)
			showVersion="true"
			;;
		r)
			remote="$OPTARG"
			;;
		P)
			if [ -n "${secure}" ] && [ "x${OPTARG}" = "xhttp" ] ; then
				echo 1>&2 "${program}: cannot specify protocol as \"http\" with secure (\"-S\") option"
				exit 1
			elif [ "x${OPTARG}" != "xhttp" ] && [ "x${OPTARG}" != "xhttps" ] ; then
				echo 1>&2 "${program}: protocol should be \"http\" or \"https\""
				exit 1
			else
				protocol="${OPTARG}"
				setProtocolOrPort="true"
			fi
			;;
		t)
			case "$OPTARG" in
				""|*[!0-9]*)
					echo 1>&2 "${program}: invalid Web service port (\"${OPTARG}\") - unsigned decimal number expected"
					exit 1
					;;
				*)
					if [ "${OPTARG}" -le 0 ] 2>/dev/null ; then
						echo 1>&2 "${program}: Web service port must be strictly positive"
						exit 1
					elif [ "${OPTARG}" -ge 65536 ] 2>/dev/null ; then
						echo 1>&2 "${program}: Web service port must be less than 65536"
						exit 1
					elif [ -n "${secure}" ] && [ "${OPTARG}" -eq 80 ] ; then
						echo 1>&2 "${program}: cannot specify port as #80 with secure (\"-S\") option"
						exit 1
					else
						port="${OPTARG}"
						setProtocolOrPort="true"
					fi
					;;
			esac
			;;
		u)
			user="$OPTARG"
			setUser="true"
			;;
		p)
			password="$OPTARG"
			setPassword="true"
			;;
		D)
			if [ -n "${OPTARG}" ] ; then
				setTarget="true"
				targetDir="$OPTARG"
			else
				echo 1>&2 "${program}: must supply a non-empty (directory) argument to \"-D\""
				exit 1
			fi
			;;
		h)
			echo "${USAGE}
    -b  --  bounce local IM server across synchonization (if appropriate)
    -s  --  synonym for \"-b\"
    -S  --  secure (enable certificate check and default to \"-P https -t 443\")
    -q  --  operate quietly
    -C  --  assume compatibility
    -v  --  print the version number
    -h  --  print this \"help\" message
    -r  --  remote host with which to synchronize
    -P  --  protocol - either \"http\" (usual default), or \"https\" (implied by \"-S\")
    -t  --  remote IM server's Web service listener port (defaulted from protocol)
    -u  --  user as whom to invoke the Web service (default \"admin\")
    -p  --  user's password for the destination IM server (default \"password\")
    -L  --  log file to which to append execution details (\"-\" for none)
    -D  --  local destination directory (default: local InterMapper installation)
Categories are: icons, sounds, mibs, probes, tools, webpages, fonts, extensions,
     maps and translations."
			case "${InterMapperVersion}" in
				@*@)
					;;
				*)
					echo "Version: ${InterMapperVersion}"
					;;
			esac
			exit 0
			;;
		\?)
			echo 1>&2 "${USAGE}
Use the \"-h\" option for \"help\""
			exit 2
			;;
	esac
done
shift `expr "${OPTIND:-1}" - 1`		# In case we want to add processing of positional parameters

webDirToFileDir()
{
	v="${2:-6.1}"
	case "${1}" in
		icons)
			echo "Custom Icons"
			;;
		sounds)
			echo "Sounds"
			;;
		mibs)
			echo "MIB Files"
			;;
		probes)
			echo "Probes"
			;;
		tools)
			echo "Tools"
			;;
		webpages)
			echo "Web Pages"
			;;
		fonts)
			echo "Fonts"
			;;
		extensions)
			echo "Extensions"
			;;
		maps)
			echo "Maps/${v}/Enabled"
			;;
		translations)
			echo "Translations"
			;;
	esac
}

getGroupForWebDir()
{
	case "x-${1}-${platform}" in
		x-extensions-cygwin)
			echo "Domain Users"
			;;
		*)
			echo "${grp}"
			;;
	esac
}

lineGroups()
{
    case "${platform}" in
        cygwin)     z="-z"  ; f=\\000    ;;
        *)          z=""    ; f=\\040    ;;
    esac
    id -Gn $z | tr $f '\012'
}

if [ $# -eq 0 ] ; then
	selected=
else
	selected=:
	for argument in "$@" ;  do
		check=`webDirToFileDir "${argument}"`
		if [ -z "${check}" ] ; then
			echo 1>&2 "${program}: unrecognised download category (\"${argument}\")"
			exit 1
		else
			selected="${selected}${argument}:"
		fi
	done
fi
isSelected()
{
	[ -z "${selected}" ] ||
		echo "${selected}" | grep ":${1}:" >/dev/null
}

#
# Following logic is pre-requisite of all executions, and the sole substance
# of the dummy execution ("-v").
#
if [ -n "${showVersion}" ] ; then
	echo "${program}: A script for duplicating the data area of an InterMapper server"
	case "${InterMapperVersion}" in
		@*@)
			echo "Version: N/A"
			;;
		*)
			echo "Version: ${InterMapperVersion}"
			;;
	esac
	if [ -n "${curlVersion}" ] ; then
		echo "Target version of \"curl\" is v${curlVersion}"
	fi
fi
if [ -z "${assumeCompatibility}" ] ; then
	unsupported=
	if [ "x${platform}" = "xcygwin" ] ; then
		v=`if type cygcheck >/dev/null 2>&1 ; then cygcheck -V | sed -n -e '1s/^.* \([0-9.]*\)$/\1/p' ; fi`
		case "${v}" in
			[3-9]*|[12][0-9]*)
				;;
			*)
				unsupported="true"
				echo 1>&2 "${program}: versions of Cygwin earlier than version 3 are unsupported"
				;;
		esac
	fi
	if [ -n "${BASH_VERSION}" ] ; then
		set -- `echo "${BASH_VERSION}" | sed -n -e 's/\(^[1-9][0-9]*\)\.\([0-9][0-9]*\).*$/\1 \2/p'`
		major="${1:-0}"
		minor="${2:-0}"
		if [ "${major}" -lt 3 ] || ( [ "${major}" -eq 3 ] && [ "${minor}" -lt 2 ] ) ; then
			unsupported="true"
			echo 1>&2 "${program}: versions of \"bash\" earlier than version 3.2 are unsupported"
		fi
	elif [ -x /bin/dash ] && [ /bin/sh -ef /bin/dash ] ; then
		:
	else
		unsupported="true"
		echo 1>&2 "${program}: shells other than \"bash\" and \"dash\" are unsupported"
	fi
	if [ -n "${unsupported}" ] ; then
		echo 1>&2 "${program}: you may use the \"-C\" option to force this script to run unsupported"
		exit 1
	fi
fi
if [ -n "${showVersion}" ] ; then
	exit 0
fi

isAdmin()
{
	case "${platform}" in
		cygwin)
			id -G | grep -q -E '\<(114|544)\>'
			return $?
			;;
		*)
			[ `id -u` -eq 0 ]
			return $?
			;;
	esac
}

checkedChGrp()
{
	if [ $# -eq 2 ] && [ -e "${2}" ] &&
		( isAdmin ||
				[ "x`id -gn`" = "x${1}" ] ||
				lineGroups | grep "^${1}\$" >/dev/null 2>&1 ) ; then
		chgrp "${1}" "${2}"
	fi
}

#
# Initialize the log file if required
#
if [ -n "${logFile}" ] && [ ! -f "${logFile}" ] ; then
	parent="`dirname "${logFile}"`"
	if isAdmin || ( [ -d "${parent}" ] && [ -w "${parent}" ] ) ; then
		if [ ! -d "${parent}" ] ; then
			# Not necessarily within the InterMapper tree so leave directory overship alone
			mkdir -p -m 755 "${parent}"
		fi
		touch "${logFile}"
		if grep '^intermapper:' /etc/group >/dev/null ; then
			checkedChGrp intermapper "${logFile}"
			chmod 660 "${logFile}"
		else
			chmod 600 "${logFile}"
		fi
	else
		echo 1>&2 "${program}: cannot create log file \"${logFile}\""
		exit 1
	fi
fi

log()
{
	if [ -n "${logFile}" ] && [ -w "${logFile}" ] && ( [ -n "$1" ] || [ $# -gt 1 ] ) ; then
		printf >>"${logFile}" '%s %s %s[%s]: %s\n' \
			"`LANG=C LC_ALL=C TZ=UTC0 date '+%Y-%m-%dT%H:%M:%SZ'`" \
			"${local}" \
			"${program}" \
			"$$" \
				"$*"
	fi
	return 0
}

errorAndLog()
{
	log "$*"
	printf 1>&2 "${program}: %s\\n" "$*"
}

echoOrLog()
{
	if [ -n "${quiet}" ] ; then
		log "$*"
	else
		printf '%s\n' "$*"
	fi
}

#
# Now that command line processing and the dummy executions ("-v" and "-h")
# have been dispatched, we flag the script as having started execution.
# We first carry out remaining command line argument validation *not*
# requiring privilege, then check for privilege, then the remaining
# command line argument validation that *does* require privilege.
#
case "${TMPDIR}" in
	/*)
		if [ -d "${TMPDIR}" ] || [ ! -e "${TMPDIR}" ] ; then
			:
		elif [ -d /var/tmp ] && [ -w /var/tmp ] ; then
			TMPDIR="/var/tmp" ; export TMPDIR
		elif [ -d /tmp ] && [ -w /tmp ] ; then
			TMPDIR=/tmp ; export TMPDIR
		else
			echo 1>&2 "${program}: cannot use \$TMPDIR (\"${TMPDIR}\") as temporary directory"
			exit 1
		fi
		;;
	*)
		if [ -d /var/tmp ] && [ -w /var/tmp ] ; then
			TMPDIR=/var/tmp ; export TMPDIR
		elif [ -d /tmp ] && [ -w /tmp ] ; then
			TMPDIR=/tmp ; export TMPDIR
		else
			echo 1>&2 "${program}: cannot find temporary directory (either \"/var/tmp\" or \"/tmp\")"
			exit 1
		fi
		;;
esac

restart()
{
	echoOrLog "Restarting InterMapper server (\"intermapperd\") on local host)"
	set +e ; case "${platform}" in
		macos)
			/usr/local/share/intermapper/Start.sh
			;;
		linux)
			/etc/init.d/intermapperd start
			;;
		cygwin)
			net start InterMapper
			;;
	esac ; status=$? ; needRestart="" ; set -e
	if [ "${status}" -ne 0 ] ; then
		errorAndLog "Could not restart InterMapper server on local host (\"${local}\")"
		exit 1
	else
		echoOrLog "Restarted InterMapper server on local host (\"${local}\")"
	fi
}

tmpdir="${TMPDIR}/${program}.$$"
mkdir -m 0700 -p "${tmpdir}"

summary()
{
	if [ "${inaccessibleMaps:-0}" -gt 0 ] ; then
		echo "You have downloaded ${inaccessibleMaps} map(s) from a more evolved version of InterMapper."
		echo "These maps will not be accessible to the local InterMapper installation"
		echo "until it has been upgraded from v${localVersionFull} to v${version}."
	elif [ "${upgradableMaps:-0}" -gt 0 ] ; then
		echo "You have downloaded ${upgradableMaps} map(s) from a less evolved version of InterMapper."
		echo "These maps will be updated to v${localVersionFull} from v${version} in the local InterMapper installation,"
		echo "but the original files will be preserved in the \"`webDirToFileDir maps \"${shortVersion}\"`\" directory."
	else
		:
	fi
}

cleanUp()
{
	dir="${1}"
	summary
	if [ -n "${bounce}" ] && [ -n "${needRestart}" ] ; then
		restart
	fi
	if [ -n "${dir}" ] && [ -d "${dir}" ] &&
			echo "${dir}" | grep "^/.*${program}.[1-9][0-9]*\$" >/dev/null 2>&1 ; then
		chmod -R a+w "${dir}"
		rm -rf "${dir}"
	fi
}

log "Starting script execution"
trap "if [ \$? -eq 0 ] ; then s=\"on success\" ; else s=\"on error\" ; fi ; \
      cleanUp \"${tmpdir}\" ; \
      log \"Finishing script execution \${s}\"" 0
for spec in INT:2 QUIT:3 HUP:1 TERM:15 ; do
	s=`echo "${spec}" | sed -e 's/:.*$//'`
	v=`echo "${spec}" | sed -e 's/^.*://'`
	v=`expr ${v} + 128`
	trap "log \"Script terminated by signal SIG${s}: exiting with status ${v}\" ; exit ${v}" "${s}"
done

if printf '%s\n' "${user}:${password}" | grep '[ 	]' >/dev/null 2>&1 ; then
	echo 1>&2 "${program}: neither user nor password may contain a space"
	exit 1
elif [ -n "${setPassword}" ] && [ -z "${setUser}" ] ; then
	echo 1>&2 "${program}: if specifying a password you must specify a user too"
	exit 1
elif [ -n "${user}" ] ; then
	auth="--user ${user}${password:+:}${password}"
else
	auth=""
fi

if [ -n "${secure}" ] ; then
	if [ "${port:-0}" -eq 0 ] ; then
		port="443"
	fi
	insecure=
else
	case "${protocol}" in
		http)
			if [ -z "${port}" ] ; then
				port="80"
			elif [ "${port}" -eq 443 ] ; then
				echo 1>&2 "${program}: warning: using protocol \"http\" on port #443"
			fi
			;;
		https)
			if [ -z "${port}" ] ; then
				port="443"
			elif [ "${port}" -eq 80 ] ; then
				echo 1>&2 "${program}: warning: using protocol \"https\" on port #80"
			fi
			;;
	esac
	insecure="-k"
fi

makedir()
{
	if [ -z "${1}" ] || [ -d "${1}" ] ; then
		return 0
	else
		# Caution: only positional parameters (not variables)
		# are maintained across recursive function calls.
		parent="`dirname \"${1}\"`"
		if [ ! -d "${parent}" ] ; then
			if makedir "${parent}" "${2}" "${3}" "${4}" ; then
				:
			else
				return $?
			fi
		fi
		if mkdir -m "${2:-0755}" "${1}" ; then
			if [ -z "${3}${4}" ] ; then
				:
			elif isAdmin ; then
				chown "${3}${4:+:}${4}" "${1}"
			elif [ -n "${4}" ] ; then
				checkedChGrp "${4}" "${1}"
			fi
			return 0
		else
			return $?
		fi
	fi
}

case "${platform}" in
	cygwin)
		if ! isAdmin ; then
			echo 1>&2 "${program}: insufficient privilege (not an administrator)"
			exit 1
		fi
		;;
	*)
		if ! isAdmin && [ "x`id -u -n`" != "xintermapper" ] ; then
			echo 1>&2 "${program}: must be run as effective UID \"root\" or \"intermapper\""
			exit 1
		fi
		;;
esac

pseudoStrings()
{
	if type strings >/dev/null 2>&1 ; then
		strings "$@"
	else
		if [ "x${1}" = "x-a" ] ; then
			shift
		fi
		cat "${1:--}" | tr -d -c ' -~' | ( cat ; echo )
	fi
}

if [ -n "${targetDir}" ] ; then
	if [ ! -d "${targetDir}" ] ; then
		# Guard against mistyped user name
		putativeUser=`dirname "${targetDir}" | sed -n -e '/^~[a-zA-Z][a-zA-Z0-9]*/s/^~\([a-zA-Z][a-zA-Z0-9]*\).*$/\1/p'`
		if [ -n "$putativeUser" ] ; then
			echo 1>&2 "${program}: failed tilde-expansion (\"~${putativeUser}\") - not creating directory \"${targetDir}\""
			exit 1
		fi
		if [ -z "${quiet}" ] ; then
			echo "Creating directory \"${targetDir}\""
		fi
		mkdir -p -m 755 "${targetDir}"
		if isAdmin ; then
			if [ -r /etc/passwd ] &&
				    [ -r /etc/group ] &&
				grep '^intermapper:' /etc/passwd >/dev/null 2>&1 ; then
				ug="intermapper"
				if grep '^intermapper:' /etc/group >/dev/null 2>&1 ; then
					ug="${ug}:intermapper"
					m=2755
				else
					m=755
				fi
				chmod "${m}" "${targetDir}"
				chown "${ug}" "${targetDir}"
			fi
		elif [ "x`id -u -n`" = "xintermapper" ] ; then
			chmod 2755 "${targetDir}"
		fi
	fi
	if [ ! -w "${targetDir}" ] ; then
		echo 1>&2 "${program}: no write permission to directory \"${targetDir}\""
		exit 1
	else
		case "${targetDir}" in
			/*)
				localSettingsRoot="${targetDir}"
				;;
			*)
				localSettingsRoot="`/bin/pwd -P`/${targetDir}"
				;;
		esac
	fi
else
	localSettingsRoot=
fi
if [ -r /usr/local/etc/intermapperd.conf ] ; then
	settings=`sed -n -e 's/^[ 	]*SettingsFolder[ 	]*"\([^"]*\)"[ 	]*$/\1/p' /usr/local/etc/intermapperd.conf`
elif [ "x${platform}" = "xcygwin" ] ; then
	settings=`cat "${regroot}/HelpSystems, LLC/IMsettingsDir/FullPath" 2>/dev/null | pseudoStrings -a`
	if [ -n "$settings" ] ; then
		settings=`cygpath -u "${settings}"`
	elif [ -d "/cygdrive/c/ProgramData/InterMapper/InterMapper Settings" ] ; then
		settings="/cygdrive/c/ProgramData/InterMapper/InterMapper Settings"
	fi
else
	settings=""
fi
if [ -z "${settings}" ] ; then
	echo 1>&2 "${program}: could not determine InterMapper settings directory for local host (\"${local}\")"
	exit 1
elif [ ! -d "${settings}" ] ; then
	echo 1>&2 "${program}: InterMapper settings directory (\"${settings}\") not found on local host  (\"${local}\")"
	exit 1
elif [ ! -w "${settings}" ] ; then
	echo 1>&2 "{program}: execution user (\"`id -u -n`\") lacks write permission to InterMapper settings directory (\"${settings}\")"
	exit 1
elif [ -z "${localSettingsRoot}" ] ; then
    needInactiveLocalServer="true"
	localSettingsRoot="${settings}"
elif [ "${settings}" -ef "${localSettingsRoot}" ] ; then
	needInactiveLocalServer="true"
else
    needInactiveLocalServer=""
fi

if [ -d "${targetDir}" ] &&
		isAdmin &&
		[ "x`echo \"${targetDir}/\"*`" != "x${targetDir}/*" ] ; then
	if [ "${targetDir}" -ef "${settings}" ] ; then
		echo 1>&2 "${program}: overwriting local settings in (\"${settings}\") as privileged user (\"`id -u -n`\") in deference to \"-D\" option"
	elif [ -t 0 ] ; then
		while : ; do
			printf "Overwrite non-empty pre-existing directory (\"${targetDir}\") (y/N)? "
			read REPLY
			case "${REPLY}" in
				"")
					;;
				[yY]*)
					break
					;;
				[Nn]*)
					log "Destination directory non-empty - download abandoned by user choice"
					exit 0
					;;
				*)
					log "Destination directory non-empty - download abandoned on user choice (\"${REPLY}\")"
					exit 1
					;;
			esac
		done
	else
		echo 1>&2 "${program}: will not write to non-empty, pre-existing target directory (\"${targetDir}\") as privileged user \"`id -u -n`\""
		exit 1
	fi
fi

canon()
{
	if [ -n "$1" ] ; then
		if type nslookup >/dev/null 2>&1 ; then
			c=`nslookup "$1" 2>/dev/null | sed -n -e '/^Name:/s/^[^ 	]*[ 	]*//p'`
		else
			c=""
		fi
		echo "${c:-$1}"
	fi
}

if [ -n "${needInactiveLocalServer}" ] ; then
	c1=`canon "${local}"`
	c2=`canon "${remote}"`
	if [ "x${c1}" = "x${c2}" ] ; then
		echo 1>&2 "${program}: local and remote hosts match - cannot clone from a host to itself"
		exit 1
	fi
fi

getCurlErrorDescription()
{
	if expr "$1" : '[1-9][0-9]*$' >/dev/null ; then
		if type man >/dev/null 2>&1 && type ul >/dev/null 2>&1 ; then
			code="$1"
		else
			return
		fi
	else
		return
	fi
	TERM=dumb PAGER=cat man curl 2>/dev/null | ul -t dumb | awk '
			BEGIN	{
				code = '$code';
				matching = 0; matched = 0;
			}
				{
					if ( $0 ~ /^[   ]*(AUTHORS|EXIT CODES).*$/ ) {
						if ( ++matching > 1 ) {
							exit(0);
						}
					} else if ( matching ) {
						if ( $1 ~ /[1-9][0-9]*/ ) {
							if ( matched ) {
								matched = 0
							} else if ( $1 == code ) {
								matched = 1
								printf("%s\n", $0);
							}
						} else {
							if ( matched ) {
								printf("%s\n", $0);
							}
						}
				}
		}'
}

IsServiceRunning()
{
	case "${platform}" in
		cygwin)
			sc query intermapper | grep 'STATE.*RUNNING' >/dev/null ; return $?
			;;
		*)
			ps -A -opid,args | grep '[i]ntermapperd ' >/dev/null ; return $?
			;;
	esac
}

if type ping >/dev/null 2>&1 ; then
	if ping -c 1 "${remote}" >/dev/null 2>&1 ; then
		:
	else
		echo 1>&2 "${program}: cannot access remote host \"${remote}\" over ICMP (\"ping\")"
		exit 1
	fi
fi

if [ -n "${needInactiveLocalServer}" ] && IsServiceRunning ; then
	if [ -z "${bounce}" ] ; then
		echo 1>&2 "${program}: InterMapper server \"intermapperd\" is executing on local host (\"${local}\")"
		echo 1>&2 "    use the \"-s\" option to bounce it across synchronization with remote host \"${remote}\""
		exit 1
	else
		echoOrLog "Stopping InterMapper server (\"intermapperd\") on local host"
		set +e ; case "${platform}" in
			macos)
				/usr/local/share/intermapper/Stop.sh
				;;
			linux)
				/etc/init.d/intermapperd stop
				;;
			cygwin)
				net stop InterMapper
				;;
		esac ; status=$? ; set -e
		if [ "${status}" -ne 0 ] ; then
			errorAndLog "Could not stop InterMapper server on local host (\"${local}\")"
			exit 1
		else
			echoOrLog "Stopped InterMapper server on local host (\"${local}\")"
			needRestart="true"
		fi
	fi
else
	bounce=""
fi

getLocalVersion()
{
	eval \"${1}\" --version 2>&1 |
		tr -d '\015' |
		sed -n -e 's/^\([1-9][0-9]*\)\.\([0-9][^ ]*\)\(\(\.[0-9][^ ]*\)\{0,1\}\).*$/\1.\2\3/p'
}

trimVersion()
{
	case "${1}" in
		*.*.*)
			echo "${1}" | sed -e 's:\.[^.]*$::'
			;;
		*.*)
			echo "${1}" | sed -e 's:[^0-9.].*$::'
			;;
	esac
}

if [ -x /usr/local/bin/intermapperd ] ; then
	localVersionFull=`getLocalVersion "/usr/local/bin/intermapperd"`
	localVersion=`trimVersion "${localVersionFull}"`
elif [ "x${platform}" = "xcygwin" ] ; then
	application="InterMapper"
	key="DisplayName"
	attribute="InstallLocation"
	match="${application} [56]"
	regkey="${regroot}/Microsoft/Windows/CurrentVersion/Uninstall"

	regpath=$(find "${regkey}" -name "${key}" -print | \
		while read f ; do \
			if pseudoStrings -a "${f}" | grep -i "${match}" >/dev/null ; then \
				printf '%s\n' "${f}" ; \
				exit 0 ; \
			fi ; \
		done | sed -e 's:^/proc/registry/::' -e "s:/${key}\$::" -e 's:/:\\:g')

	value=$(reg query "${regpath}" /v "${attribute}" 2>/dev/null |
				tr -d '\015' |
				sed -n -e "/^[    ][  ]*${attribute}/s/^[  ][  ]*${attribute}[  ][  ]*REG_SZ[   ]*//p")

	if [ -n "${value}" ] ; then
		server=$(cygpath -u "${value}\\InterMapper.exe")
		if [ -x "${server}" ] ; then
			localVersionFull=`getLocalVersion "${server}"`
			localVersion=`trimVersion "${localVersionFull}"`
		else
			localVersionFull=
			localVersion=
		fi
	else
		localVersionFull=
		localVersion=
	fi
else
	localVersionFull=
	localVersion=
fi

if [ -z "${localVersion}" ] ; then
	echo 1>&2 "${program}: cannot determine version of local InterMapper installation"
	exit 1
fi

compareVersions()
{
	left="${1}" ; right="${2}"

	saveIFS="${IFS}" ; IFS=. ; export IFS
	set -- ${left} ; left1="$1" ; left2="$2"
	set -- ${right} ; right1="$1" ; right2="$2"
	IFS="${saveIFS}" ; export IFS

	if [ "${left1:-0}" -gt "${right1:-0}" ] ; then
		echo 1
	elif [ "${left1:-0}" -lt "${right1:-0}" ] ; then
		printf -- '%d\n' '-1'
	elif [ "${left2:-0}" -gt "${right2:-0}" ] ; then
		echo 1
	elif [ "${left2:-0}" -lt "${right2:-0}" ] ; then
		printf -- '%d\n' '-1'
	else
		echo 0
	fi
}

isOkay()
{
	if [ -z "$1" ] ; then
		return 0
# An error code of 56 is similarly innocuous when using
# https and *not* supplying "-k".
#	elif [ -z "${insecure}" ] ; then
#		return "$1"
	elif [ "$1" -eq 56 ] ; then
		return 0
	else
		return "$1"
	fi
}

prefix="${protocol}://${remote}:${port}"

#
# Here we catch curl's handling of errors emitted by the IM Server at its
# general stream server level.  Ani encounted the "Access Denied" error
# when access is blocked by the IM server's peer address ACL (IM-2049).
#
set +e
curl --silent ${connectTime:+--connect-timeout ${connectTime}} -k "${prefix}/~intermapperweb/prodinfo" >/dev/null 2>&1 ; statusCode=$?
if [ $statusCode -ne 28 ] ; then
	statusText=`curl --silent ${auth} -k "${prefix}/~intermapperweb/prodinfo" 2>/dev/null`
else
	statusText=""
fi
set -e
statusText=`printf '%s\n' "${statusText}" | tr -d '\015' | sed -e 's,\.$,,'`
if [ "x${statusText}" = "xAccess Denied" ] ||
	( [ "${statusCode}" -ne 0 ] &&
		( [ "${statusCode}" -ne 56 ] ||
				! echo "${statusText}" | grep >/dev/null 2>&1 '^{"Result":' ) ) ; then
	if [ "${statusCode}" -eq 0 ] ; then
		errorAndLog "curl command to probe host \"${remote}\" on port #${port} failed with exit code #${statusCode} (${statusText})."
	else
		errorText=`getCurlErrorDescription "${statusCode}" | sed -e "s/[ 	][ 	]*${statusCode}[ 	][ 	]*//" -e 's/\.$//'`
		errorAndLog "curl command to probe host \"${remote}\" on port #${port} failed with exit code #${statusCode} (${errorText})."
	fi
	exit 1
elif curl $auth $ipver -s "${prefix}/~files" ${insecure} -f >/dev/null 2>&1 || isOkay $? ; then
	version=`curl ${insecure} -G $auth "${prefix}/~intermapperweb/prodinfo" 2>/dev/null |
			 sed -n -e 's/^.*"Version"[    ]*:[    ]*"\([^"]*\)".*$/\1/p'`
	if [ -n "${version}" ] ; then
		longVersion="IM-v${version}"
		shortVersion="`trimVersion \"${version}\"`"
	fi
	if [ -z "${quiet}" ] ; then
		if [ -n "${longVersion}" ] ; then
			echo "Test connection succeeded; Web service on remote host \"${remote}\" is responding (version \"${longVersion}\")"
		else
			echo "Test connection succeeded; Web service on remote host \"${remote}\" is responding (server pre-dates \"IM-v6.3\")"
		fi
	fi
	skew=`compareVersions "${shortVersion}" "${localVersion}"`
	if [ "${skew:-0}" -ne 0 ] ; then
		echo 1>&2 "Version mismatch: remote IM installation is v${version}, local IM installation is v${localVersionFull}"
		if [ -z "${setTarget}" ] ; then
			echo 1>&2 "Use \"-D\" to force update or specify a distinct download directory"
			exit 1
		elif [ -n "${needInactiveLocalServer}" ] ; then
			if [ -t 0 ] ; then
				while : ; do
					printf "Overwrite local installation (v${localVersionFull}) with data from v${version} (y/N)? "
					read REPLY
					case "${REPLY}" in
						"")
							;;
						[yY]*)
							break
							;;
						[Nn]*)
							log "Version skew - download abandoned by user choice"
							exit 0
							;;
						*)
							log "Version skew - download abandoned on user choice (\"${REPLY}\")"
							exit 1
							;;
					esac
				done
			fi
			log "Version skew - overwriting local installation (v${localVersionFull}) with data from version v${version}"
		fi
	fi
else
	errorCode=$?
	if [ "${errorCode}" -eq 22 ] ; then
		set +e
		# Retry without "-f" to see if we get a more informative code...
		curl $auth $ipver -s "${prefix}/~files" ${insecure} >/dev/null 2>&1 ; e=$?
		if [ "${e}" -ne 0 ] ; then
			errorCode="${e}"
		elif curl $auth $ipver -s "${prefix}/~files" ${insecure} 2>&1 |
				tr -d '\015' |
				grep 'THIS IS THE ~GuestHTML' >/dev/null 2>&1 ; then
			# The IM server sends us a Guest page if it does not like our login.
			# We respond by pretending curl returned its code for a generic login
			# authentication failure.
			errorCode="67"
		fi
		set -e
	fi

	errorText=`getCurlErrorDescription "${errorCode}"`
	echo "${program}: curl command to probe host \"${remote}\" on port #${port} failed with exit code #${errorCode}."
	if [ -n "${errorText}" ] ; then
		printf '%s\n' "${errorText}"
	else
		echo "    Use the command \"man curl\" to find the meaning of exit code #${errorCode};"
		echo "    see the section \"EXIT CODES\" at the bottom of the page)."
	fi 1>&2
	if [ -n "${errorText}" ] ; then
		singleLine=`printf '%s' "${errorText}" | sed -e 's/^[ 	][ 	]*/ /' | tr -d '\012'`
		log "curl command to probe host \"${remote}\" on port #${port} failed with exit code #${errorCode} (${singleLine})."
	else
		log "curl command to probe host \"${remote}\" on port #${port} failed with exit code #${errorCode}."
	fi
	exit 1
fi

getAwkUnescape()
{
	case "`awk --version 2>/dev/null | sed 1q`" in
		GNU*)
			strtonum="strtonum"
			;;
		*)
			strtonum="0+"
			;;
	esac
	# For every line containing a percent character, replace the leftmost instance
	# of an HTML %-escape with the corresponding character until none is left.
	#
	echo '/%/{while(match($0,/%[0-9a-fA-F][0-9a-fA-F]/)){$0=substr($0,1,RSTART-1)sprintf("%c",'"$strtonum"'("0x"substr($0,RSTART+1,2)))substr($0,RSTART+3);}}{print}'
}

decode()
{
	if [ -n "${2}" ] ; then
		command="${2}"
	else
		command=`getAwkUnescape`
	fi
	if [ -n "$1" ] ; then
		# Replace pluses with spaces, strip <cr>s and delegate
		# other %-escapes to the "awk" fragment returned by
		# the previous function.
		#
		printf '%s\n' "${1}" |
			sed -e 's/+/ /g' -e 's/\%0[dD]//g' |
			awk "${command}"
	fi
}

prettyElapsed()
{
	if [ "${1}" -lt 60 ] ; then
		echo "${1}s"
	elif [ "${1}" -lt 3600 ] ; then
		echo "`expr \"${1}\" / 60`m`expr \"${1}\" % 60`s"
	else
		echo "`expr \"${1}\" / 3600`h`expr \"${1}\" / 60 % 60`m`expr \"${1}\" % 60`s"
    fi
}

awkCommand=`getAwkUnescape`

userAccountOkayForMac()
{
	u="${1}"
	if [ `id -u` -eq 0 ] && [ -d /var/tmp ] && [ -w /var/tmp ] && (
			f="CloneIMt.$$" ; \
			status=1 ; \
			cd /var/tmp ; \
			touch "${f}" ; \
			chown "${u}" "${f}" >/dev/null 2>&1 ; status=$? ; \
			rm -f "${f}" ; \
			exit "${status}" ) ; then
		return 0
	else
		return 1
	fi
}

groupAccountOkayForLinux()
{
	if [ `id -u` -eq 0 ] ; then
		return 0
	elif [ "x`id -gn`" = "x${1}" ] ||
			lineGroups | grep "^${1}\$" >/dev/null 2>&1 ; then
		return 0
	else
		return 1
	fi
}

case "${platform}" in
	macos)
		if userAccountOkayForMac "__USER__" ; then
			usr="__USER__"
		elif userAccountOkayForMac "intermapper" ; then
			usr="intermapper"
		else
			usr="`id -un`"
		fi
		grp="intermapper"
		dirMode="751"
		fileMode="600"
		;;
	linux)
		usr="intermapper"
		if groupAccountOkayForLinux "root" ; then
			grp="root"
		elif groupAccountOkayForLinux "intermapper" ; then
			grp="intermapper"
		else
			grp="`id -gn`"
		fi
		dirMode="751"
		fileMode="600"
		;;
	cygwin)
		usr="Administrators"
		grp="SYSTEM"
		dirMode="775"
		fileMode="660"
		;;
esac
if topdirs=`curl $auth $ipver -s "${prefix}/~files" ${insecure} | tr '\r' '\n'` ; then
	for dir in $topdirs ; do
		filelist=`curl $auth $ipver -s "${dir}" ${insecure} | tr '\r' '\n'`
		webdir=`basename "${dir}"`
		if printf '%s\n' "${filelist}" | grep "does not exist" >/dev/null 2>&1 ; then
			:
		elif isSelected "${webdir}" ; then
			fl=`printf '%s\n' "$filelist" | tr -d '\015' | sed -e '/^[ 	]*$/d'`
			if [ -z "${fl}" ] ; then
				expectedCount="0"
			else
				expectedCount=`printf '%s\n' "${fl}" | wc -l`
			fi
			echo "Processing \"${webdir}\" (${expectedCount} file(s) found) ..."

			w=`webDirToFileDir "${webdir}" "${shortVersion}"`
			dirStartTime="`date +%s`"
			dGroup=`getGroupForWebDir "${webdir}"`
			fileCount= ; for f in ${filelist} ; do
				codedFile="${f}"
				codedBase=`basename "${codedFile}"`
				case "${codedBase}" in
					*.log|*.log.*|*.pid|CloneIM|CloneIM.vbs)
						# Skip unwanted files
						continue
						;;
					*)
						;;
				esac

				decodedBase=`decode "${codedBase}" "${awkCommand}"`
				codedLocal=`echo "${codedFile}" | sed -n -e "s;^${protocol}://[^/][^/]*/~files/${webdir}/;;p"`
				codedLocalDir=`dirname "${codedLocal}"`
				destDir="${localSettingsRoot}/${w}"
				if [ "x${codedLocalDir}" != "x." ] ; then
					decodedLocalDir=`decode "${codedLocalDir}" "${awkCommand}"`
					destDir="${destDir}/${decodedLocalDir}"
				fi
				destination="${destDir}/${decodedBase}"

				rm -f "${tmpdir}/${codedBase}"
				for attempt in "" "-L" ; do
					( cd "${tmpdir}" ; curl $auth $ipver $attempt -s -O "${codedFile}" ${insecure} || isOkay $? )
					if [ -e "${tmpdir}/${codedBase}" ] ;  then
						break
					fi
				done
				if [ ! -e "${tmpdir}/${codedBase}" ] ;  then
					echo 1>&2 "${program}: curl did not download file \"${decodedBase}\" to \"${tmpdir}/${codedBase}\" - skipped"
					continue
				elif [ -z "${quiet}" ] ; then
					echo "  ${decodedBase} => ${destination}"
				fi
				makedir "${destDir}" "${dirMode}" "${usr}" "${dGroup}"
				mv "${tmpdir}/${codedBase}" "${destination}"

				chmod "${fileMode}" "${destination}"
				if [ -n "${usr}${dGroup}" ] && isAdmin ; then
					chown "${usr}${dGroup:+:}${dGroup}" "${destination}"
				elif [ -n "${dGroup}" ] ; then
					checkedChGrp "${dGroup}" "${destination}"
				fi

				case "${webdir}" in
					maps)
						if [ "${skew:-0}" -ne 0 ] ; then
							if [ "${skew:-0}" -lt 0 ] ; then
								localW=`webDirToFileDir "${webdir}" "${localVersion}"`
								toUpgrade=`printf '%s\n' "${destination}" | sed -n -e "s@${w}@${localW}@p"`
								if [ -n "${toUpgrade}" ] ; then
									d=`dirname "${toUpgrade}"`
									makedir "${d}" "${dirMode}" "${usr}" "${dGroup}"
									cp -f -p "${destination}" "${toUpgrade}"
									upgradableMaps=`expr "${upgradableMaps:-0}" + 1`
								fi
							else
								inaccessibleMaps=`expr "${inaccessibleMaps:-0}" + 1`
							fi
						fi
						;;
				esac

				fileCount=`expr "${fileCount:-0}" + 1`
				if [ -n "${limit}" ] && [ "${fileCount}" -ge "${limit}" ] ; then
					break;
				fi
			done
			if [ "${fileCount:-0}" -ne 0 ] ; then
				dirFinishTime="`date +%s`"
				if [ "${dirFinishTime}" -eq "${dirStartTime}" ] ; then
					elapsedSeconds="0"
				else
					elapsedSeconds="`expr \"${dirFinishTime}\" - \"${dirStartTime}\"`"
				fi
				log "Downloaded ${fileCount} file(s) from directory \"${webdir}\" in `prettyElapsed \"${elapsedSeconds}\"`"
			fi
		fi
	done
else
	echo 1>&2 "${program}: failed to get file list from Web Server embedded in IM server at host \"${remote}\", port #${port}"
	exit 1
fi

#
# The "Preferences" file is handled separately, because it is stored in the
# top level of the Intermapper Settings directory.  We write this as a loop
# for better abstraction and in case we get another top level file later.
# NB: we do not handle top level files with names that need escaping; that
# will need implementing following the pattern above if you add such a file
# at top level.
#
fileMode="644"
if [ -z "${quiet}" ] ; then
	echo "Processing top level files ..."
fi
for f in Preferences ; do
	destination="${localSettingsRoot}/${f}"
	rm -f "${tmpdir}/${f}"
	for attempt in "" "-L" ; do
		( cd "${tmpdir}" ; curl $auth $ipver $attempt -s -O "${prefix}/~files/${f}" ${insecure} || isOkay $? )
		if [ -e "${tmpdir}/${f}" ] ;  then
			break
		fi
	done
	if [ ! -e "${tmpdir}/${f}" ] ; then
		echo 1>&2 "${program}: curl did not download file \"${f}\" to \"${tmpdir}/${f}\" - skipped"
		continue
	elif [ -z "${quiet}" ] ; then
		echo "  ${f} => ${destination}"
	fi
	mv "${tmpdir}/${f}" "${destination}"
	chmod "${fileMode}" "${destination}"
	if [ -n "${usr}${grp}" ] && isAdmin ; then
		chown "${usr}${grp:+:}${grp}" "${destination}"
	elif [ -n "${grp}" ] ; then
		checkedChGrp "${grp}" "${destination}"
	fi
done

exit 0
