#!/usr/bin/env bash
set -euo pipefail
set +x
cd /opt/openclaw/ops

# Load nextcloud-bot secrets from Infisical without printing values.
eval "$('/usr/bin/python3' <<'PY'
import json, urllib.request, urllib.parse, shlex, sys
from pathlib import Path

env_path = Path('/opt/openclaw/ops/.env.nextcloud-bot')
vals = {}
for line in env_path.read_text().splitlines():
    s = line.strip()
    if s and not s.startswith('#') and '=' in s:
        k, v = s.split('=', 1)
        vals[k.strip()] = v.strip().strip('"').strip("'")

required = ['INFISICAL_URL', 'INFISICAL_PROJECT_ID', 'INFISICAL_CLIENT_ID', 'INFISICAL_CLIENT_SECRET']
missing = [k for k in required if not vals.get(k)]
if missing:
    raise SystemExit('Missing in .env.nextcloud-bot: ' + ', '.join(missing))

base = vals['INFISICAL_URL'].rstrip('/')
project = vals['INFISICAL_PROJECT_ID']

def call(method, url, body=None, token=None):
    headers = {'Content-Type': 'application/json'}
    if token:
        headers['Authorization'] = 'Bearer ' + token
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    return json.loads(urllib.request.urlopen(req, timeout=20).read().decode() or '{}')

login = call('POST', base + '/api/v1/auth/universal-auth/login', {
    'clientId': vals['INFISICAL_CLIENT_ID'],
    'clientSecret': vals['INFISICAL_CLIENT_SECRET'],
})
access_token = login.get('accessToken') or login.get('data', {}).get('accessToken')
if not access_token:
    raise SystemExit('Infisical login failed')

qs = urllib.parse.urlencode({
    'workspaceId': project,
    'environment': 'prod',
    'secretPath': '/nextcloud-bot',
})
raw = call('GET', base + '/api/v3/secrets/raw?' + qs, token=access_token)
items = raw.get('secrets') or raw.get('data') or []
if isinstance(items, dict):
    items = items.get('secrets') or []

secret_map = {}
for item in items:
    if not isinstance(item, dict):
        continue
    k = item.get('secretKey') or item.get('key') or item.get('secretName')
    v = item.get('secretValue') or item.get('value')
    if k and v:
        secret_map[k] = v

needed = ['SLACK_BOT_TOKEN', 'SLACK_APP_TOKEN', 'SEARXNG_BASE_URL']
missing = [k for k in needed if not secret_map.get(k)]
if missing:
    raise SystemExit('Missing in Infisical /nextcloud-bot prod: ' + ', '.join(missing))

for k in needed:
    print(f'export {k}={shlex.quote(secret_map[k])}')
for k in ['INFISICAL_CLIENT_ID', 'INFISICAL_CLIENT_SECRET']:
    print(f'export {k}={shlex.quote(vals[k])}')
PY
)"

# Verify token identity before recreating, but do not print token values.
/usr/bin/python3 <<'PY'
import os, json, urllib.request
req = urllib.request.Request(
    'https://slack.com/api/auth.test',
    data=b'',
    headers={'Authorization': 'Bearer ' + os.environ['SLACK_BOT_TOKEN'], 'Content-Type': 'application/x-www-form-urlencoded'},
)
res = json.loads(urllib.request.urlopen(req, timeout=20).read().decode() or '{}')
print('Slack token identity:', {k: res.get(k) for k in ['ok', 'user', 'user_id', 'bot_id', 'team', 'error']})
if res.get('user_id') != 'U0AS1BYEC3U':
    raise SystemExit('Refusing to recreate: token is not nextcloudbot/U0AS1BYEC3U')
PY

docker compose up -d --force-recreate nextcloud-bot
