#!/bin/bash

#Create variable with download url of the installer
DownloadUrl="ENTER_DOWNLOAD_URL"
#Create variable with app name
AppName='Falcon'
#License Key
LicenseKey="ENTER_LICENSE_KEY"
#Write content of variable to console output
echo "App Name: $AppName"

echo "Testing to ensure App is not already installed"
#Create variable with results of search in Application folder for $AppName
ExistingSearch=$(find "/Applications/" -name "$AppName")
#If variable is not null (If search found the app in the application folder)
if [[ -n "$ExistingSearch" ]]
then
    echo "$AppName already present in /Applications folder, exiting."
    exit 1
else
    # Runs if app name wasn't found in application folder
    echo "$AppName not present in /Applications folder, installing"
    
    # Check if the CrowdStrike profile is present
    echo "checking to see if the CrowdStrike profile is present"
    # variable containing the installed profiles on the device
    ProfileSearch=$(profiles list -output stdout-xml)
    # Team identifier of CrowdStrike
    ProfileCompare="X9E956P446"
    # If statement that checks whether or not the CrowdStrike profile is installed
    if [[ $ProfileSearch = *"$ProfileCompare"* ]]
    then
        echo "The CrowdStrike profile is present, installing CrowdStrike Falcon"
        # Install CrowdStrike
        #download installer from S3 bucket and output it to /tmp folder
        curl "$DownloadUrl" --output /private/tmp/FalconSensorMacOS.pkg
        #Run the installer
        installer -verboseR -package /private/tmp/FalconSensorMacOS.pkg -target /
        # Activate Falcon with our license
        echo "Licensing app..."
        /Applications/Falcon.app/Contents/Resources/falconctl license "$LicenseKey"
        echo "Install finished, deleting install files..."
        #delete left over installation files no longer needed
        rm /private/tmp/FalconSensorMacOS.pkg
        echo "The following files were deleted: /private/tmp/FalconSensorMacOS.pkg" 
        echo "displaying agents stats: (if blank agent isn't running)"
        /Applications/Falcon.app/Contents/Resources/falconctl stats agent_info
    else
        echo "The CrowdStrike profile is NOT present, CrowdStrike Falcon will NOT be installed."
    fi
fi
