#!/bin/sh

#  The logging routine
Log() {
	logger -p install.info -t 'Parallels Installer' "$@"
}

# Copy receipts to Parallels Receipts directory
SWD=`cd "${0%/*}"; pwd`
. "${SWD}"/receipt.sh

# Import variables
. "${SWD}"/var.inc

# Get product version
ver="$CURRENT_PROD_VERSION"
if [ -z "$ver" ]; then
	Log "Can not determinate product version"
	exit 0
fi

# Get product name without spaces
prod=$(echo "${CURRENT_PROD_NAME}" | sed s/\ //g)
if [ -z "$prod" ]; then
	Log "Can not determinate product name"
	exit 0
fi

stats_dir="/var/db/Parallels/Stats"
mkdir -p "$stats_dir"
# Create the installation receipt to CEP tool
date "+%Y-%m-%d %H:%M:%S %z" > "$stats_dir/$prod.$ver"


current_volume="${0%/*}/../../../../../.."
dispatcher_info_plist="/Library/Parallels/Parallels Service.app/Contents/Info.plist"
major_ver=$(python -c "import plistlib; print plistlib.readPlist(\"$dispatcher_info_plist\")[\"CFMajorVersion\"]")
stm_volume="/Volumes/Parallels Desktop ${major_ver} Switch to Mac"
desktop_volume="/Volumes/Parallels Desktop ${major_ver}"

iso_stuff_copy()
{
	kaspersky_file="$1"
	kaspersky_file_copy="$2"
	if [ -e "$stm_volume/$kaspersky_file" ]; then
		cp -f "$stm_volume/$kaspersky_file" "$kaspersky_file_copy"
	elif [ -e "$desktop_volume/$kaspersky_file" ]; then
		cp -f "$desktop_volume/$kaspersky_file" "$kaspersky_file_copy"
	elif [ -e "$current_volume/$kaspersky_file" ]; then
		cp -f "$current_volume/$kaspersky_file" "$kaspersky_file_copy"
	fi
}

learn_your_mac="Learn your Mac.app"
# Copy Learn your Mac
if [ -d "$stm_volume/$learn_your_mac" ]; then
	cp -RHf "$stm_volume/$learn_your_mac" "/Applications/$learn_your_mac"
elif [ -d  "$current_volume/$learn_your_mac" ]; then
	cp -RHf "$current_volume/$learn_your_mac" "/Applications/$learn_your_mac"
fi

transporter_agent_exe="Parallels Transporter Agent for Windows.exe"
library_transporter_agent="/Library/Parallels/$transporter_agent_exe"
# Copy Parallels Transporter Agent for Windows
if [ -e "$stm_volume/.$transporter_agent_exe" ]; then
	cp -f "$stm_volume/.$transporter_agent_exe" "$library_transporter_agent"
	chmod 664 "$library_transporter_agent"
elif [ -e "$current_volume/.$transporter_agent_exe" ]; then
	cp -f "$current_volume/.$transporter_agent_exe" "$library_transporter_agent"
	chmod 664 "$library_transporter_agent"
fi

# Copy KIS & KAV
iso_stuff_copy ".HostAntiVirus.dmg" "/Library/Parallels/Downloads/HostAntiVirus-$major_ver.dmg"
iso_stuff_copy ".GuestAntiVirus.msi" "/Library/Parallels/Downloads/GuestAntiVirus-$major_ver"


# Just to finish installation with good mood
true
