#!/bin/bash

profile_path=$1

profile_id=`/usr/libexec/PlistBuddy -c "print :PayloadIdentifier" $1 2>/dev/null`

if (($? != 0)); then
		echo "Unable to read profile id"
		exit 1
fi
tmp_location='/var/tmp/'${RANDOM}/
mkdir $tmp_location

cp $1 $tmp_location'pma_config_profile'
cd $tmp_location
tar -czf 'pma_config_profile.tar.gz' 'pma_config_profile' > /dev/null
cd - > /dev/null
profile_base64=$(cat $tmp_location'pma_config_profile.tar.gz' | openssl base64)
rm -r $tmp_location

remediation_script=`cat <<EOF
#! /bin/bash -s --

read -r -d '' profile_base64 << EOF2
${profile_base64}
EOF2

if [ "\\$1" == "profile_not_installed" ];
then
	profile_location=/var/tmp/\\${RANDOM}/
	mkdir \\$profile_location
	echo "\\${profile_base64}" | openssl base64 -d > \\$profile_location'pma_config_profile.tar.gz' 
	tar -xf \\$profile_location'pma_config_profile.tar.gz' -C  \\$profile_location

	profiles -I -F \\${profile_location}'pma_config_profile'
	rm -r "\\${profile_location}"
	echo "profile_has_been_installed"
else
	echo "profile_already_installed"
fi

exit 0

EOF`

discovery_script=`cat <<EOF
#! /bin/bash --

profile_id="${profile_id}"

/usr/bin/profiles -L | /usr/bin/grep "\\${profile_id}" > /dev/null

if [ \\$? -eq 0 ]; then
	printf "profile_installed"
else
	printf "profile_not_installed"
fi

EOF`

echo "${remediation_script}" > remediation.sh
echo "${discovery_script}" > discovery.sh
