#!/bin/bash
echo "=== Forgejo Repository Setup ==="
echo "This will create the 'canvas' repository and push your code."
echo ""
read -p "Forgejo Username: " USERNAME
read -s -p "Forgejo Password: " PASSWORD
echo ""
echo "--------------------------------"

# Create repository using Basic Auth
echo "Creating repository 'canvas' under @$USERNAME..."
HTTP_STATUS=$(curl -s -o /tmp/repo_response.json -w "%{http_code}" -u "$USERNAME:$PASSWORD" -X POST https://registry.spaceoperator.org/api/v1/user/repos -H "Content-Type: application/json" -d '{"name": "canvas", "private": false}')

if [ "$HTTP_STATUS" -eq 201 ] || [ "$HTTP_STATUS" -eq 200 ]; then
    echo "✅ Repository created successfully!"
elif grep -q "repository already exists" /tmp/repo_response.json; then
    echo "ℹ️ Repository already exists, proceeding to push..."
else
    echo "❌ Failed to create repository (HTTP $HTTP_STATUS)"
    cat /tmp/repo_response.json
    echo ""
    exit 1
fi

# Set up git remote and push
echo "Pushing code to Forgejo..."
cd /home/amir/code/space-operator/canvas || exit 1

# Encode password for URL to prevent issues with special characters
# (Simple approach for git remote)
git remote remove origin 2>/dev/null
git remote add origin "https://$USERNAME:$PASSWORD@registry.spaceoperator.org/$USERNAME/canvas.git"

echo "Pushing main branch..."
git push -u origin main
if [ $? -ne 0 ]; then
    echo "Pushing master branch instead..."
    git push -u origin master
fi

# Clean up credentials from remote URL to leave working copy secure
git remote set-url origin "https://registry.spaceoperator.org/$USERNAME/canvas.git"
echo "✅ Done! Your code is now pushed to https://registry.spaceoperator.org/$USERNAME/canvas"
