#!/usr/bin/env bash

# If should enable FileVault then set "yes" else "no"
SHOULD_ENABLE="yes"

# ====== DO NOT EDIT BELOW CODE ======

brandIcon="/Applications/Scalefusion-MDM Client.app/Contents/Resources/AppIcon.icns"
title="Scalefusion: Disable FileVault"
if [[ "$SHOULD_ENABLE" = "yes" ]]; then
title="Scalefusion: Enable FileVault"
fi

## Get the logged in user's name
userName=$(/usr/bin/stat -f%Su /dev/console)

## Grab the UUID of the User
userNameUUID=$(dscl . -read /Users/$userName/ GeneratedUID | awk '{print $2}')

## Get the OS build
BUILD=`/usr/bin/sw_vers -buildVersion | awk {'print substr ($0,0,2)'}`

## This first user check sees if the logged in account is already authorized with FileVault 2
userCheck=`fdesetup list | awk -v usrN="$userNameUUID" -F, 'match($0, usrN) {print $1}'`

if [ "${userCheck}" != "${userName}" ]; then
echo "This user is not a FileVault 2 enabled user."
exit 3
fi

## Check to see if the encryption process is complete
encryptCheck=`fdesetup status`
echo "${encryptCheck}"
statusCheck=$(echo "${encryptCheck}" | grep "FileVault is On.")
onStatus="FileVault is On."
if [ "${statusCheck}" == "${onStatus}" ]; then

    if [[ "$SHOULD_ENABLE" == "yes" ]]; then
    echo "FileVault is already enabled"
    exit 0
    fi

else

    if [[ "$SHOULD_ENABLE" != "yes" ]]; then
    echo "FileVault is already disabled"
    exit 0
    fi

fi

passwordPrompt () {
## Get the logged in user's password via a prompt
echo "Prompting ${userName} for their login password."
text="Admin has requested to disable FileVault"
if [[ "$SHOULD_ENABLE" = "yes" ]]; then
text="Admin has request to enable FileVault"
fi

userPass=$(/usr/bin/osascript <<EOF
on run
    set userInput to text returned of (display dialog "$text" & return & "Enter login password for '$userName'" default answer "" with title "$title" buttons {"Cancel", "Ok"} default button 2 with icon POSIX file "$brandIcon" with hidden answer)
    return userInput
end run
EOF
)

# Check if the user canceled the dialog
if [ "$?" == "1" ]; then
    echo "User Canceled"
    exit 0
fi

# Use the retrieved password
if [[ ! -z "$userPass" ]]; then
echo "User Password is not empty"
else 
echo "User password is empty"
exit 4;
fi

if [[ "$SHOULD_ENABLE" = "yes" ]]; then
echo "Attempting to enable FV with the entered credentials"
sudo fdesetup enable -user "$userName" -password "$userPass"
else
echo "Attempting to disable FV with the entered credentials"
sudo fdesetup disable -user "$userName" -password "$userPass"
fi
}

passwordPrompt

exit