#!/usr/bin/env bash
# @file macOS Security Settings
# @brief Prompts user for various security prompts as early as possible (to make headless automation more manageable)
# @description
#     This script performs various tasks on macOS that have required manual security prompts so that the
#     user can run the installation process as headlessly as possible. This script only runs when the `HEADLESS_INSTALL` variable
#     is set. The various tasks include:
#
#     1. Add the `$HOME/.local/etc/ssl/cloudflare/Cloudflare_CA.crt` to the `System.keychain` for CloudFlare Zero Trust / WARP
#     2. Configure system VNC service to allow connections via the `USER` with the `VNC_PASSWORD`

{{ includeTemplate "universal/profile" }}
{{ includeTemplate "universal/logg" }}

if [ -n "$HEADLESS_INSTALL" ] && [ -z "$SSH_CONNECTION" ] && [ -d /System ] && [ -d /Applications ]; then
    ### Ensure certificate is installed
    # Source: https://developers.cloudflare.com/cloudflare-one/static/documentation/connections/Cloudflare_CA.crt
    # Source: https://developers.cloudflare.com/cloudflare-one/static/documentation/connections/Cloudflare_CA.pem
    ### Ensure certificate installed on macOS
    logg info '**macOS Manual Security Permission** Requesting security authorization for Cloudflare trusted certificate'
    sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$HOME/.local/etc/ssl/cloudflare/Cloudflare_CA.crt"

    # Source: https://apple.stackexchange.com/questions/30238/how-to-enable-os-x-screen-sharing-vnc-through-ssh
    # To disable, run: sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -deactivate -configure -access -off
    # Only enable when computer is not a corporate / work computer
    logg info '**macOS Manual Security Permission** Enabling VNC using the VNC_PASSWORD variable which is vncpass when nothing is specified'
    sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -allowAccessFor -specifiedUsers -clientopts -setreqperm -reqperm yes -setvnclegacy -vnclegacy yes -setvncpw -vncpw "{{- if and (stat (joinPath .host.home ".config" "age" "chezmoi.txt")) (stat (joinPath .chezmoi.sourceDir ".chezmoitemplates" "secrets" "VNC_PASSWORD")) }}{{ includeTemplate "secrets/VNC_PASSWORD" | decrypt | trim }}{{ else }}{{ default "vncpass" (env "VNC_PASSWORD") }}{{ end }}" -restart -agent -privs -all -users "$USER" && logg success 'Finished running the macOS Remote Management kickstart executable'
fi
