# Cloudflare Automation with .env Credentials

## ✅ Credentials Configuration

Cloudflare credentials are automatically loaded from `.env` file:

- `CLOUDFLARE_ZONE_ID` - Your Cloudflare Zone ID
- `CLOUDFLARE_ACCOUNT_ID` - Your Cloudflare Account ID  
- `CLOUDFLARE_API_TOKEN` - Your Cloudflare API Token

## Automated Features

### 1. DNS Record Creation

When credentials are available, scripts automatically create DNS records via Cloudflare API:

```bash
# Scripts will automatically:
# 1. Create CNAME record pointing to tunnel
# 2. Enable proxy (orange cloud)
# 3. Set TTL to 3600 seconds
```

### 2. Credential Loading

All scripts automatically:
- ✅ Detect `.env` file location
- ✅ Load Cloudflare credentials
- ✅ Use API token for DNS operations
- ✅ Skip manual credential entry

### 3. Scripts Updated

- ✅ `setup-cloudflare-tunnel.sh` - Uses API for DNS creation
- ✅ `setup-cloudflare-tunnel-backend.sh` - Uses account ID from .env
- ✅ `automated-cloudflare-setup.sh` - Validates and provides instructions

## Usage

### Quick Setup

```bash
# Run automated setup (validates credentials, provides instructions)
cd terraform/phases/phase1
./scripts/automated-cloudflare-setup.sh rpc.yourdomain.com
```

### Manual Setup with Auto-Credentials

```bash
# SSH to Nginx proxy
ssh besuadmin@20.160.58.99

# Script automatically loads credentials
./setup-cloudflare-tunnel.sh rpc.yourdomain.com
```

## What Gets Automated

### ✅ Fully Automated
- DNS record creation (via API)
- Credential loading from .env
- Validation of credentials

### ⚠️ Still Requires Manual Steps
- Browser authentication for tunnel login (cloudflared requirement)
- Tunnel creation (one-time setup)
- Service start (after configuration)

## API Token Permissions Required

Your Cloudflare API token needs:

- **Zone**: DNS Edit, Zone Read
- **Account**: Cloudflare Tunnel Edit  
- **Account**: Account Read

## Verification

Test that credentials work:

```bash
# Test API access
curl -X GET "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}" \
  -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
  -H "Content-Type: application/json"
```

## Troubleshooting

### Credentials Not Loading

1. Check .env file exists: `ls -la /home/intlc/projects/smom-dbis-138/.env`
2. Verify format: `grep CLOUDFLARE /home/intlc/projects/smom-dbis-138/.env`
3. Check script path resolution (scripts look for .env in project root)

### API Token Invalid

1. Verify token in Cloudflare Dashboard
2. Check token permissions
3. Regenerate if needed
4. Update .env file

### DNS Creation Fails

Scripts will:
1. Try API method first (if credentials available)
2. Fall back to CLI method (`cloudflared tunnel route dns`)
3. Show warning if both fail

## Security

- ✅ `.env` is in `.gitignore` (not committed)
- ✅ Credentials only loaded when scripts run
- ✅ API token has limited permissions
- ⚠️ Never commit `.env` to version control

