#!/bin/bash

# This script helps set up the environment for using the Google Cloud Build Go client

# Extract access token from command line or environment
if [ "$1" != "" ]; then
  ACCESS_TOKEN="$1"
else
  # Try to extract from clipboard if it contains a token
  if command -v xclip &> /dev/null; then
    CLIPBOARD=$(xclip -selection clipboard -o 2>/dev/null | grep -oE 'Bearer [A-Za-z0-9._-]+' | cut -d ' ' -f 2)
    if [ -n "$CLIPBOARD" ] && [[ $CLIPBOARD =~ ^ya29\..+ ]]; then
      ACCESS_TOKEN="$CLIPBOARD"
      echo "Found access token in clipboard"
    fi
  fi
  
  # If still empty, ask for it
  if [ -z "$ACCESS_TOKEN" ]; then
    read -p "Enter your Google Cloud access token: " ACCESS_TOKEN
  fi
fi

# Create .env file
cat > .env << EOF
# Google Cloud Build authentication
# Created: $(date)
GOOGLE_ACCESS_TOKEN=$ACCESS_TOKEN

# Project configuration (edit as needed)
CLOUDBUILD_PROJECT_ID=vison-code
CLOUDBUILD_LOCATION=asia-east1
EOF

echo "Created .env file with access token and project configuration"
echo "To use these settings in your terminal session, run:"
echo "  export GOOGLE_ACCESS_TOKEN=$ACCESS_TOKEN"
echo "  export CLOUDBUILD_PROJECT_ID=vison-code"
echo "  export CLOUDBUILD_LOCATION=asia-east1"

# Make the file only readable by the owner
chmod 600 .env

# Offer to create the example connection
read -p "Do you want to create a sample GitLab connection using this token? (y/N): " CREATE_CONNECTION

if [[ $CREATE_CONNECTION =~ ^[Yy] ]]; then
  export GOOGLE_ACCESS_TOKEN=$ACCESS_TOKEN
  go run main.go --action create-gitlab --config config/config.json
fi
