#!/usr/bin/env bash
# google-secops-setup.sh: give Huntbase access to your Google SecOps instance.
#
# Run it in Google Cloud Shell (or anywhere with gcloud signed in) as someone
# who can manage IAM in the Google Cloud project linked to Google SecOps.
# It is safe to re-run: every step checks what already exists.
#
# It creates, in that project:
#   * service account <prefix>-reader with Chronicle API Viewer
#     (roles/chronicle.viewer): search, alerts, connection checks;
#   * custom role huntbaseSecOpsRuleWriter: the permissions of Chronicle API
#     Editor (roles/chronicle.editor) plus chronicle.rules.delete, without any
#     permission that custom roles can't hold;
#   * service account <prefix>-writer with that custom role: rule writing
#     (watchers as YARA-L rules) and sending endpoint data;
#   * a JSON key for each account, saved next to where you run the script.
#
# Usage:
#   bash google-secops-setup.sh --project <project-id> [options]
#
# Options:
#   --project <id>   Google Cloud project linked to Google SecOps (required).
#   --read-only      Create only the reader account (no custom role, no writer).
#   --no-keys        Don't create JSON keys (for example if you will use keyless
#                    sign-in, or create keys yourself later).
#   --prefix <name>  Service account name prefix. Default: huntbase.
#   --key-dir <dir>  Where to write key files. Default: current directory.
#   --dry-run        Print the commands that change anything, run only reads.
#   -h, --help       Show this help.
#
# Source: https://docs.huntbase.io/scripts/google-secops-setup.sh
# Guide:  https://docs.huntbase.io/docs/integrations/google-secops

set -euo pipefail

ROLE_ID="huntbaseSecOpsRuleWriter"
ROLE_TITLE="Huntbase SecOps rule writer"
ROLE_DESCRIPTION="Chronicle API Editor permissions plus chronicle.rules.delete, for Huntbase rule writing and sending data. Managed by google-secops-setup.sh."
BASE_ROLE="roles/chronicle.editor"
EXTRA_PERMISSIONS=("chronicle.rules.delete")
READER_ROLE="roles/chronicle.viewer"
KEY_POLICY="iam.disableServiceAccountKeyCreation"

PROJECT=""
READ_ONLY=0
NO_KEYS=0
PREFIX="huntbase"
KEY_DIR="."
DRY_RUN=0
KEY_BLOCKED=0

usage() {
  sed -n '2,/^set -euo/p' "$0" 2>/dev/null | sed '$d' | sed 's/^# \{0,1\}//' \
    || say "See https://docs.huntbase.io/docs/integrations/google-secops"
}

say() { printf '%s\n' "$*"; }
step() { printf '\n==> %s\n' "$*"; }
warn() { printf 'WARNING: %s\n' "$*" >&2; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

# Print a command in a copy-pasteable form.
show() {
  local out="" arg
  for arg in "$@"; do out+="$(printf '%q' "$arg") "; done
  printf '  %s\n' "${out% }"
}

# Run a command that changes something, or print it in --dry-run.
run() {
  if [[ "$DRY_RUN" -eq 1 ]]; then
    printf '[dry-run] would run:\n'
    show "$@"
    return 0
  fi
  "$@"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --project) [[ $# -ge 2 ]] || die "--project needs a value"; PROJECT="$2"; shift 2 ;;
    --project=*) PROJECT="${1#*=}"; shift ;;
    --read-only) READ_ONLY=1; shift ;;
    --no-keys) NO_KEYS=1; shift ;;
    --prefix) [[ $# -ge 2 ]] || die "--prefix needs a value"; PREFIX="$2"; shift 2 ;;
    --prefix=*) PREFIX="${1#*=}"; shift ;;
    --key-dir) [[ $# -ge 2 ]] || die "--key-dir needs a value"; KEY_DIR="$2"; shift 2 ;;
    --key-dir=*) KEY_DIR="${1#*=}"; shift ;;
    --dry-run) DRY_RUN=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) die "unknown option: $1 (see --help)" ;;
  esac
done

[[ -n "$PROJECT" ]] || { usage; die "--project is required"; }
[[ "$PREFIX" =~ ^[a-z][a-z0-9-]{0,22}$ ]] \
  || die "--prefix must be lowercase letters, digits or '-', start with a letter, at most 23 characters"
command -v gcloud >/dev/null 2>&1 || die "gcloud not found. Run this in Google Cloud Shell, or install the Google Cloud CLI."

READER="${PREFIX}-reader"
WRITER="${PREFIX}-writer"
READER_EMAIL="${READER}@${PROJECT}.iam.gserviceaccount.com"
WRITER_EMAIL="${WRITER}@${PROJECT}.iam.gserviceaccount.com"
ROLE_NAME="projects/${PROJECT}/roles/${ROLE_ID}"

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

[[ "$DRY_RUN" -eq 1 ]] && say "Dry run: reads run for real, changes are only printed."

# --- 0. Project ----------------------------------------------------------------
step "Checking project ${PROJECT}"
PROJECT_NUMBER="$(gcloud projects describe "$PROJECT" --format='value(projectNumber)' 2>/dev/null)" \
  || die "can't read project '${PROJECT}'. Check the ID and that you're signed in (gcloud auth list)."
say "Project number: ${PROJECT_NUMBER}"
# A project number works for --project, but service account emails need the ID.
if [[ "$PROJECT" =~ ^[0-9]+$ ]]; then
  PROJECT_ID="$(gcloud projects describe "$PROJECT" --format='value(projectId)')"
  READER_EMAIL="${READER}@${PROJECT_ID}.iam.gserviceaccount.com"
  WRITER_EMAIL="${WRITER}@${PROJECT_ID}.iam.gserviceaccount.com"
  ROLE_NAME="projects/${PROJECT_ID}/roles/${ROLE_ID}"
  PROJECT="$PROJECT_ID"
fi

# --- 1. Chronicle API ----------------------------------------------------------
step "Checking the Chronicle API is enabled"
enabled="$(gcloud services list --enabled --project "$PROJECT" \
  --filter='config.name=chronicle.googleapis.com' --format='value(config.name)' 2>/dev/null || true)"
if [[ "$enabled" == "chronicle.googleapis.com" ]]; then
  say "chronicle.googleapis.com is enabled."
else
  warn "chronicle.googleapis.com is not enabled in ${PROJECT}."
  say "Google enables it when it links a project to your SecOps instance. Check that"
  say "this is the linked project (SecOps > Settings > SIEM Settings). If it is, enable it:"
  show gcloud services enable chronicle.googleapis.com --project "$PROJECT"
  die "stopping: Huntbase can't reach SecOps through this project until the API is enabled."
fi

# --- helpers ---------------------------------------------------------------------
sa_exists() { gcloud iam service-accounts describe "$1" --project "$PROJECT" >/dev/null 2>&1; }

ensure_sa() {
  local name="$1" email="$2" display="$3"
  if sa_exists "$email"; then
    say "Service account ${email} exists."
  else
    run gcloud iam service-accounts create "$name" --project "$PROJECT" \
      --display-name "$display" \
      --description "Used by Huntbase to reach Google SecOps. Created by google-secops-setup.sh."
  fi
}

# add-iam-policy-binding is idempotent. A new service account can take a few
# seconds to be visible to IAM, so retry.
ensure_binding() {
  local email="$1" role="$2" i
  if [[ "$DRY_RUN" -eq 1 ]]; then
    run gcloud projects add-iam-policy-binding "$PROJECT" \
      --member "serviceAccount:${email}" --role "$role" --condition=None --quiet
    return 0
  fi
  for i in 1 2 3 4 5 6; do
    if gcloud projects add-iam-policy-binding "$PROJECT" \
        --member "serviceAccount:${email}" --role "$role" --condition=None --quiet >/dev/null 2>"$TMP_DIR/bind.err"; then
      say "Granted ${role} to ${email}."
      return 0
    fi
    say "Waiting for ${email} to be visible to IAM (attempt ${i})..."
    sleep 10
  done
  cat "$TMP_DIR/bind.err" >&2
  die "couldn't grant ${role} to ${email}."
}

key_policy_enforced() {
  local v
  v="$(gcloud resource-manager org-policies describe "$KEY_POLICY" --project "$PROJECT" \
    --effective --format='value(booleanPolicy.enforced)' 2>/dev/null || true)"
  [[ "${v,,}" == "true" ]]
}

print_key_policy_help() {
  say ""
  say "Your organization blocks service account keys (${KEY_POLICY})."
  say "Ask an Organization Policy Administrator (roles/orgpolicy.policyAdmin) to allow"
  say "keys in this project only. The policy stays on everywhere else:"
  show gcloud resource-manager org-policies disable-enforce "$KEY_POLICY" --project "$PROJECT"
  say "The change takes about 2 to 15 minutes to apply. Until then key creation fails"
  say "with FAILED_PRECONDITION. Then run this script again; it skips what's done."
  say "If your organization uses the managed constraint instead"
  say "(iam.managed.disableServiceAccountKeyCreation), add the exception for that one."
}

# Creates a key unless a key file for this account is already in KEY_DIR.
ensure_key() {
  local email="$1" file="$2"
  if [[ -s "$file" ]]; then
    say "Key file ${file} exists; not creating another key."
    return 0
  fi
  if [[ "$KEY_BLOCKED" -eq 1 ]]; then
    say "Skipping key for ${email}: keys are blocked by policy (see below)."
    return 0
  fi
  if [[ "$DRY_RUN" -eq 1 ]]; then
    run gcloud iam service-accounts keys create "$file" --iam-account "$email" --project "$PROJECT"
    return 0
  fi
  if ( umask 077; gcloud iam service-accounts keys create "$file" \
        --iam-account "$email" --project "$PROJECT" ) 2>"$TMP_DIR/key.err"; then
    say "Saved key for ${email} to ${file}."
  elif grep -qiE 'disableServiceAccountKeyCreation|FAILED_PRECONDITION|key creation is not allowed' "$TMP_DIR/key.err"; then
    KEY_BLOCKED=1
    rm -f "$file"
    say "Key creation for ${email} was blocked by policy."
  else
    rm -f "$file"
    cat "$TMP_DIR/key.err" >&2
    die "couldn't create a key for ${email}."
  fi
}

# --- 2. Custom role ----------------------------------------------------------------
if [[ "$READ_ONLY" -eq 0 ]]; then
  step "Building custom role ${ROLE_ID} from ${BASE_ROLE} + ${EXTRA_PERMISSIONS[*]}"
  gcloud iam roles describe "$BASE_ROLE" --format='value(includedPermissions)' \
    | tr ';,' '\n' | sed '/^$/d' > "$TMP_DIR/wanted"
  [[ -s "$TMP_DIR/wanted" ]] || die "couldn't read the permissions of ${BASE_ROLE}."
  printf '%s\n' "${EXTRA_PERMISSIONS[@]}" >> "$TMP_DIR/wanted"
  sort -u -o "$TMP_DIR/wanted" "$TMP_DIR/wanted"

  # Permissions a custom role on this project may hold (not NOT_SUPPORTED).
  gcloud iam list-testable-permissions "//cloudresourcemanager.googleapis.com/projects/${PROJECT}" \
    --format='csv[no-heading](name,customRolesSupportLevel)' \
    | awk -F, '$2 != "NOT_SUPPORTED" { print $1 }' | sort -u > "$TMP_DIR/allowed"

  comm -12 "$TMP_DIR/wanted" "$TMP_DIR/allowed" > "$TMP_DIR/perms"
  comm -23 "$TMP_DIR/wanted" "$TMP_DIR/allowed" > "$TMP_DIR/dropped"
  say "$(wc -l < "$TMP_DIR/perms" | tr -d ' ') permissions in the role."
  if [[ -s "$TMP_DIR/dropped" ]]; then
    say "Left out (not allowed in custom roles on this project):"
    sed 's/^/  - /' "$TMP_DIR/dropped"
  fi
  for p in "${EXTRA_PERMISSIONS[@]}"; do
    grep -qx "$p" "$TMP_DIR/perms" || warn "${p} can't be used in a custom role here; Huntbase can't delete rules it created."
  done

  {
    printf 'title: "%s"\n' "$ROLE_TITLE"
    printf 'description: "%s"\n' "$ROLE_DESCRIPTION"
    printf 'stage: GA\n'
    printf 'includedPermissions:\n'
    sed 's/^/- /' "$TMP_DIR/perms"
  } > "$TMP_DIR/role.yaml"

  role_state="$(gcloud iam roles describe "$ROLE_ID" --project "$PROJECT" --format='value(deleted)' 2>/dev/null || echo missing)"
  case "$role_state" in
    missing)
      run gcloud iam roles create "$ROLE_ID" --project "$PROJECT" --file "$TMP_DIR/role.yaml" --quiet ;;
    True|true)
      run gcloud iam roles undelete "$ROLE_ID" --project "$PROJECT" --quiet
      run gcloud iam roles update "$ROLE_ID" --project "$PROJECT" --file "$TMP_DIR/role.yaml" --quiet ;;
    *)
      gcloud iam roles describe "$ROLE_ID" --project "$PROJECT" --format='value(includedPermissions)' \
        | tr ';,' '\n' | sed '/^$/d' | sort -u > "$TMP_DIR/current" || true
      if cmp -s "$TMP_DIR/current" "$TMP_DIR/perms"; then
        say "Role ${ROLE_ID} is up to date."
      else
        run gcloud iam roles update "$ROLE_ID" --project "$PROJECT" --file "$TMP_DIR/role.yaml" --quiet
      fi ;;
  esac
  if [[ "$DRY_RUN" -eq 1 ]]; then
    say "[dry-run] role file that would be used:"
    sed 's/^/    /' "$TMP_DIR/role.yaml"
  fi
fi

# --- 3. Service accounts -------------------------------------------------------------
step "Service account for reading: ${READER_EMAIL}"
ensure_sa "$READER" "$READER_EMAIL" "Huntbase (read)"
ensure_binding "$READER_EMAIL" "$READER_ROLE"

if [[ "$READ_ONLY" -eq 0 ]]; then
  step "Service account for rule writing and sending data: ${WRITER_EMAIL}"
  ensure_sa "$WRITER" "$WRITER_EMAIL" "Huntbase (rule writing, send data)"
  ensure_binding "$WRITER_EMAIL" "$ROLE_NAME"
fi

# --- 4. Keys ---------------------------------------------------------------------------
READER_KEY="${KEY_DIR%/}/${READER}-key.json"
WRITER_KEY="${KEY_DIR%/}/${WRITER}-key.json"
if [[ "$NO_KEYS" -eq 0 ]]; then
  step "JSON keys"
  [[ "$DRY_RUN" -eq 1 ]] || mkdir -p "$KEY_DIR"
  if key_policy_enforced; then
    KEY_BLOCKED=1
    say "The ${KEY_POLICY} policy is enforced on this project."
  fi
  ensure_key "$READER_EMAIL" "$READER_KEY"
  [[ "$READ_ONLY" -eq 1 ]] || ensure_key "$WRITER_EMAIL" "$WRITER_KEY"
  [[ "$KEY_BLOCKED" -eq 0 ]] || print_key_policy_help
fi

# --- 5. Next steps ---------------------------------------------------------------------
step "Next steps"
say "1. In SecOps, open Settings > SIEM Settings > Profile and copy the Customer ID."
say "2. In Huntbase, go to Connections > New connection > Google SecOps and enter:"
say "     Region:               where your instance runs (us, eu, europe-west2, ...)"
say "     Google Cloud project: ${PROJECT}"
say "     SecOps customer ID:   the Customer ID from step 1"
if [[ "$NO_KEYS" -eq 1 ]]; then
  say "3. Keys were not created (--no-keys)."
elif [[ "$KEY_BLOCKED" -eq 1 && ! -s "$READER_KEY" ]]; then
  say "3. Allow keys as shown above, run this script again, then add the keys."
else
  say "3. Service account key (JSON): upload or paste ${READER_KEY}"
  if [[ "$READ_ONLY" -eq 0 ]]; then
    say "4. Optional, after the connection is created: on the connection page add"
    say "   ${WRITER_KEY} as a Rule writing credential (watchers as YARA-L rules)"
    say "   and/or as a Send data credential (send endpoint data to SecOps)."
  fi
fi
say ""
say "Key files are secrets. Delete them from this machine once they're in Huntbase:"
say "  rm -f ${READER_KEY}$([[ "$READ_ONLY" -eq 1 ]] || printf ' %s' "$WRITER_KEY")"
