#!/bin/sh
# Salesforce access review: export the key queries to CSV files.
# From the Clientell AI Access Review Kit
# https://www.getclientell.com/resources/salesforce-access-review-guide
# Last checked: 28 Oct 2026.
#
# Needs the Salesforce CLI (sf), logged in to the org:  sf org login web -a my-org
# Run:   sh export-access-review.sh my-org
# Every query only reads. Nothing in the org changes.
# Read each query before you run it, and run it on a sandbox first if you are unsure.
#
# Each run writes to its own new folder named after the org alias, the org ID and the
# date and time, for example access-review-my-org-00D5g000001abcd-20261028-143005.
# The script never writes into a folder that already exists and never overwrites a file.
# If a query fails, the script stops, deletes the half-written file, leaves RUN-FAILED.txt
# in the folder and exits with an error. Do not use a failed folder as evidence.

set -eu
set -C   # noclobber: a plain > never overwrites an existing file

ORG="${1:?Usage: sh export-access-review.sh <org-alias>}"

ORG_ID=$(sf data query -o "$ORG" -q "SELECT Id FROM Organization" --result-format csv | tail -n 1 | tr -d '\r"')
case "$ORG_ID" in
  00D*) ;;
  *) echo "Could not read the org ID for $ORG. Check that you are logged in." >&2; exit 1 ;;
esac

SAFE_ORG=$(printf '%s' "$ORG" | tr -c 'A-Za-z0-9._-' '_')
OUT="access-review-$SAFE_ORG-$ORG_ID-$(date +%Y%m%d-%H%M%S)"

if ! mkdir "$OUT"; then
  echo "Folder $OUT already exists. Nothing was written. Wait a second and run again." >&2
  exit 1
fi

run() {
  # $1 = file name, $2 = query
  echo "Running $1"
  if ! sf data query -o "$ORG" -q "$2" --result-format csv > "$OUT/$1.csv"; then
    rm -f "$OUT/$1.csv"
    echo "Query $1 failed. This run is incomplete." > "$OUT/RUN-FAILED.txt"
    echo "Query $1 failed. Stopped. See $OUT/RUN-FAILED.txt." >&2
    exit 1
  fi
}

run "1.1-active-users" "SELECT COUNT() FROM User WHERE IsActive = true"
run "2.1-users-by-profile" "SELECT Profile.Name, COUNT(Id) c FROM User WHERE IsActive = true GROUP BY Profile.Name"
run "A.1-modify-all-data-by-source" "SELECT PermissionSet.Type, COUNT(Id) c FROM PermissionSetAssignment WHERE PermissionSet.PermissionsModifyAllData = true AND Assignee.IsActive = true GROUP BY PermissionSet.Type"
run "3.2-view-all-data-holders" "SELECT Assignee.Name, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsViewAllData = true AND Assignee.IsActive = true"
run "4.2-modify-all-data-holders" "SELECT Assignee.Name, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile, Assignee.LastLoginDate FROM PermissionSetAssignment WHERE PermissionSet.PermissionsModifyAllData = true AND Assignee.IsActive = true"
run "4.4-hard-delete-holders" "SELECT Assignee.Name, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsBulkApiHardDelete = true AND Assignee.IsActive = true"
run "5.1-export-reports-holders" "SELECT Assignee.Name, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsExportReport = true AND Assignee.IsActive = true"
run "5.2-weekly-data-export-holders" "SELECT Assignee.Name, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsDataExport = true AND Assignee.IsActive = true"
run "6.1-stale-users" "SELECT Name, Username, Profile.Name, LastLoginDate FROM User WHERE IsActive = true AND UserType = 'Standard' AND (LastLoginDate < LAST_N_DAYS:90 OR LastLoginDate = null) ORDER BY LastLoginDate"
run "6.4-integration-users" "SELECT Name, Profile.Name, LastLoginDate FROM User WHERE IsActive = true AND UserType = 'Standard' AND Profile.PermissionsApiUserOnly = true"
run "7.2-permission-set-changes-30d" "SELECT CreatedDate, CreatedBy.Name, Action, Section, Display FROM SetupAuditTrail WHERE CreatedDate = LAST_N_DAYS:30 AND Action LIKE 'permSet%' ORDER BY CreatedDate DESC"

echo "Done. Files are in $OUT/. Log each one in access-review-evidence-log.csv."
