#!/bin/bash

set -e

if [ "$#" -ne 3 ]; then
	echo "Usage: $0 <first_name> <last_name> <username>"
	exit 1
fi

FIRST_NAME=$1
LAST_NAME=$2
NEW_USER=$3
FULL_NAME="$FIRST_NAME $LAST_NAME"
TEMP_PASS="Ch@ng3Me"

echo "--- Starting macOS Provisioning for $FULL_NAME ---"

# 1. Device Naming
sudo scutil --set ComputerName "$FULL_NAME"
sudo scutil --set HostName "$NEW_USER"
sudo scutil --set LocalHostName "$NEW_USER"

# 2. Homebrew & App Install
if [[ "$(uname -m)" == "arm64" ]]; then
	eval "$(/opt/homebrew/bin/brew shellenv)" 2>/dev/null || true
else
	eval "$(/usr/local/bin/brew shellenv)" 2>/dev/null || true
fi

if ! command -v brew &>/dev/null; then
	echo "Homebrew not found. Installing..."
	/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
	[[ "$(uname -m)" == "arm64" ]] && eval "$(/opt/homebrew/bin/brew shellenv)" || eval "$(/usr/local/bin/brew shellenv)"
fi

echo "Ensuring packages are installed..."
brew install --cask google-chrome microsoft-office microsoft-teams microsoft-auto-update zoom
brew install dockutil defaultbrowser

# 3. User Creation
if id "$NEW_USER" &>/dev/null; then
	echo "User '$NEW_USER' already exists. Skipping creation..."
else
	echo "Creating account..."
	sudo sysadminctl -addUser "$NEW_USER" -fullName "$FULL_NAME" -password "$TEMP_PASS" -home "/Users/$NEW_USER"

	echo "----------------------------------------------------------"
	echo "IMPORTANT: FileVault Authorization"
	echo "1. Enter YOUR admin username (rootreeit)"
	echo "2. Enter YOUR admin password"
	echo "3. Enter the NEW user's temp password ($TEMP_PASS)"
	echo "----------------------------------------------------------"
	sudo fdesetup add -usertoadd "$NEW_USER"
fi

# 4. Permissions
echo "Setting permissions for $NEW_USER..."
sudo dseditgroup -o edit -a "$NEW_USER" -t user lpadmin
sudo defaults write /Library/Preferences/com.apple.RemoteManagement.plist ScreenSharingAllowed -bool yes
sudo dseditgroup -o create -rt com.apple.access_screensharing
sudo dseditgroup -o edit -a "$NEW_USER" -t user com.apple.access_screensharing

echo "Note: Screen Recording/Accessibility/Camera/Microphone permissions and the"
echo "Homebrew maintenance login item are pushed automatically via Apple Business"
echo "MDM (see macos-permissions-profile.mobileconfig) since this device is"
echo "ADE-enrolled - no manual profile install needed here."

echo "Please log in as the new user, complete initial set up, and then return to the admin to run part 2"
