#!/bin/bash
# Semgrep Guardian headless login for Claude Code cloud sessions.
# Paste into: cloud environment menu > Edit > Setup script.
#
# Installs:
#   semgrep CLI (pip, pinned)     and the Semgrep Guardian Claude Code plugin
#   ~/.local/bin/xdg-open        saves Guardian's sign-in link instead of opening a
#                                 browser (kept in /tmp, never in the workspace)
#   /opt/company/semgrep-login.py  start  - SessionStart hook: begins the legacy login
#                                          and shows the SSO step + link at session start
#                                 prompt - UserPromptSubmit hook: repeats them on each
#                                          prompt until the user is logged in
#                                 daemon - background legacy login (ends the plugin's
#                                          automatic OAuth attempt, which cannot finish
#                                          in a cloud session and blocks other logins)
# Each user signs in as themselves; no shared SEMGREP_APP_TOKEN is used.
set -euo pipefail

# --- Notice shown (in bold) above the sign-in steps. Edit freely. ----------
NOTICE="It is the expectation of the security team that all code generated by Claude Code \
is run through the Semgrep Guardian plug-in. This has been installed for you in this \
session but it requires login to be activated to use the company licence and ruleset."

OPT=/opt/company
SEMGREP_VERSION=1.183.0   # pinned; bump deliberately after testing
PLUGIN=semgrep@claude-plugins-official
MARKETPLACE=anthropics/claude-plugins-official
mkdir -p "$OPT" "$HOME/.local/bin" "$HOME/.claude"

# --- Semgrep CLI ------------------------------------------------------------
if [ "$(semgrep --version 2>/dev/null)" != "$SEMGREP_VERSION" ]; then
  python3 -m pip install --quiet --root-user-action=ignore "semgrep==$SEMGREP_VERSION" \
    || python3 -m pip install --quiet --root-user-action=ignore --break-system-packages \
         "semgrep==$SEMGREP_VERSION"
fi
echo "Semgrep CLI: $(semgrep --version)"

# --- Semgrep Guardian plugin for Claude Code --------------------------------
# Org managed settings may also install it; a user-scope install alongside is
# harmless (same files) and makes sure it is there before the first session.
if command -v claude >/dev/null 2>&1; then
  claude plugin marketplace add "$MARKETPLACE" >/dev/null 2>&1 || true  # already added is fine
  claude plugin install "$PLUGIN" --scope user
else
  echo "WARNING: claude CLI not found; Semgrep plugin not installed" >&2
fi

# --- Headless browser stand-in ----------------------------------------------
cat > "$HOME/.local/bin/xdg-open" <<'EOF'
#!/bin/sh
# Headless stand-in for Semgrep Guardian login: save the sign-in link instead of
# opening a browser. Only legacy cli-token links are kept.
( sleep 1
  url=$(curl -sS --noproxy '*' "$1" 2>/dev/null \
    | grep -oE 'https://semgrep\.dev/login\?cli-token=[^"]+' | head -1)
  [ -n "$url" ] || case "$1" in *cli-token=*) url="$1" ;; esac
  [ -n "$url" ] && echo "$url" > /tmp/semgrep-login-url.txt
) >/dev/null 2>&1 &
exit 0
EOF
chmod +x "$HOME/.local/bin/xdg-open"

# --- Login helper -----------------------------------------------------------
printf '%s\n' "$NOTICE" > "$OPT/semgrep-notice.txt"
cat > "$OPT/semgrep-login.py" <<'PYEOF'
#!/usr/bin/env python3
"""Semgrep Guardian legacy login for headless Claude Code sessions.

  semgrep-login.py start   SessionStart hook
  semgrep-login.py prompt  UserPromptSubmit hook
  semgrep-login.py daemon  background login loop (started by `start`)
"""
import glob, json, os, signal, subprocess, sys, time

SSO_URL = "https://semgrep.example.com"
URL_FILE = "/tmp/semgrep-login-url.txt"
PID_FILE = "/tmp/semgrep-login-daemon.pid"
TOKEN_FILE = os.path.expanduser("~/.semgrep/settings.yml")
DAEMON_MAX_WAIT = 900   # seconds the background login keeps trying
START_WAIT = 25         # seconds the SessionStart hook waits for the link

NOTICE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           "semgrep-notice.txt")

def notice():
    """The notice text set at the top of the setup script (empty if none)."""
    try:
        with open(NOTICE_FILE) as f:
            return " ".join(f.read().split())
    except OSError:
        return ""

def logged_in_quick():
    try:
        with open(TOKEN_FILE) as f:
            return any(l.startswith("api_token:") for l in f)
    except OSError:
        return False

def current_link():
    try:
        with open(URL_FILE) as f:
            url = f.read().strip()
        return url if "cli-token=" in url else None
    except OSError:
        return None

def body(url):
    if url:
        return ("Semgrep sign-in needed for this session:\n"
                f"  1. SSO into the Semgrep app first: {SSO_URL}\n"
                f"  2. Then open this link to authorize this session: {url}")
    return (f"Semgrep sign-in needed: SSO into the Semgrep app first at {SSO_URL}. "
            "The authorization link is being prepared and will be shown with "
            "your next prompt.")

def emit(event, url):
    text = notice()
    # Terminal banner: plain text (markdown is not rendered there).
    msg = (text + "\n\n" if text else "") + body(url)
    # Claude's reply renders markdown, so the notice is shown in bold there.
    shown = (f"**{text}**\n\n" if text else "") + body(url)
    if url:
        ctx = ("Semgrep Guardian is not logged in for this session. Before anything "
               "else in your reply, show the user the following exactly, keeping the "
               "bold notice and both links:\n" + shown + "\nAfter they approve it, "
               "call the Semgrep Guardian status tool to confirm scanning is on.")
    else:
        ctx = ("Semgrep Guardian is not logged in yet. Before anything else in your "
               "reply, show the user the following exactly, keeping the bold "
               "notice:\n" + shown)
    print(json.dumps({"systemMessage": msg, "hookSpecificOutput": {
        "hookEventName": event, "additionalContext": ctx}}))

def daemon_running():
    try:
        with open(PID_FILE) as f:
            os.kill(int(f.read().strip()), 0)
        return True
    except (OSError, ValueError):
        return False

def start_daemon():
    if daemon_running():
        return
    p = subprocess.Popen([sys.executable, "-I", os.path.abspath(__file__), "daemon"],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL, start_new_session=True)
    with open(PID_FILE, "w") as f:
        f.write(str(p.pid))

def cmd_start():
    sys.stdin.read() if not sys.stdin.isatty() else None
    if logged_in_quick():
        return
    try:
        os.remove(URL_FILE)  # never show a link from an earlier session
    except OSError:
        pass
    start_daemon()
    deadline = time.time() + START_WAIT
    while time.time() < deadline and not current_link() and not logged_in_quick():
        time.sleep(1)
    if not logged_in_quick():
        emit("SessionStart", current_link())

def cmd_prompt():
    sys.stdin.read() if not sys.stdin.isatty() else None
    if logged_in_quick():
        return
    start_daemon()  # restarts the login if an earlier attempt gave up
    emit("UserPromptSubmit", current_link())

def end_plugin_oauth():
    """End the plugin's automatic OAuth attempt, which holds the login lock."""
    for p in glob.glob("/proc/[0-9]*/cmdline"):
        try:
            with open(p, "rb") as f:
                args = f.read().split(b"\0")
        except OSError:
            continue
        if b"auto" in args and b"SessionStart" in args and \
                any(b"guardian" in a or b"scripts/hook" in a for a in args):
            try:
                os.kill(int(p.split("/")[2]), signal.SIGTERM)
            except OSError:
                pass

def cmd_daemon():
    roots = sorted(glob.glob(os.path.expanduser(
        "~/.claude/plugins/cache/claude-plugins-official/semgrep/*/")))
    if not roots:
        return
    root = roots[-1].rstrip("/")
    srv = subprocess.Popen([f"{root}/scripts/hook", "claude", "mcp"],
                           env=dict(os.environ, CLAUDE_PLUGIN_ROOT=root),
                           stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                           stderr=subprocess.DEVNULL, text=True, bufsize=1)
    ids = [0]

    def call(method, params=None, notify=False):
        msg = {"jsonrpc": "2.0", "method": method}
        if params is not None:
            msg["params"] = params
        if not notify:
            ids[0] += 1
            msg["id"] = ids[0]
        srv.stdin.write(json.dumps(msg) + "\n")
        srv.stdin.flush()
        if notify:
            return None
        for line in srv.stdout:  # blocks until the reply (login: until approved)
            try:
                reply = json.loads(line)
            except ValueError:
                continue
            if reply.get("id") == ids[0]:
                return reply
        raise SystemExit("guardian server exited")

    def tool(name, args=None):
        r = call("tools/call", {"name": name, "arguments": args or {}})
        res = r.get("result", {})
        text = "".join(c.get("text", "") for c in res.get("content", []))
        return bool(res.get("isError") or "error" in r), text

    def logged_in():
        err, text = tool("status")
        try:
            return not err and json.loads(text).get("state") == "ok"
        except ValueError:
            return False

    call("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
                        "clientInfo": {"name": "semgrep-login", "version": "2"}})
    call("notifications/initialized", notify=True)
    deadline = time.time() + DAEMON_MAX_WAIT
    try:
        while time.time() < deadline:
            if logged_in():
                return
            err, text = tool("login", {"method": "legacy"})
            if err and "already in progress" in text:
                end_plugin_oauth()
                time.sleep(2)
            elif err:
                time.sleep(10)
    finally:
        srv.terminate()
        for f in (URL_FILE, PID_FILE):
            try:
                os.remove(f)
            except OSError:
                pass

if __name__ == "__main__":
    {"start": cmd_start, "prompt": cmd_prompt, "daemon": cmd_daemon}[sys.argv[1]]()
PYEOF
chmod +x "$OPT/semgrep-login.py"

# --- Register the hooks (merged into existing settings) ---------------------
python3 -I - "$HOME/.claude/settings.json" "$OPT/semgrep-login.py" <<'PYEOF'
import json, os, sys
path, helper = sys.argv[1], sys.argv[2]
try:
    with open(path) as f:
        cfg = json.load(f)
except (OSError, ValueError):
    cfg = {}
hooks = cfg.setdefault("hooks", {})
def keep(h):
    cmd = h.get("command", "")
    # drop earlier copies of these hooks, the previous login hooks, and the
    # old check that told users to set a shared SEMGREP_APP_TOKEN
    return not any(s in cmd for s in (helper, "/opt/company/semgrep-",
                                      "semgrep show identity"))
for event in ("SessionStart", "UserPromptSubmit"):
    groups = []
    for g in hooks.get(event, []):
        g["hooks"] = [h for h in g.get("hooks", []) if keep(h)]
        if g["hooks"]:
            groups.append(g)
    hooks[event] = groups
hooks["SessionStart"].append({"matcher": "startup|resume", "hooks": [
    {"type": "command", "timeout": 40, "command": f"python3 -I {helper} start"}]})
hooks["UserPromptSubmit"].append({"hooks": [
    {"type": "command", "timeout": 10, "command": f"python3 -I {helper} prompt"}]})
cfg.setdefault("enabledPlugins", {})["semgrep@claude-plugins-official"] = True
cfg.setdefault("extraKnownMarketplaces", {}).setdefault("claude-plugins-official", {
    "source": {"source": "github", "repo": "anthropics/claude-plugins-official"}})
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
    json.dump(cfg, f, indent=2)
PYEOF

echo "Semgrep login setup installed."
