#!/bin/bash
# Skrypt commitowania projektu na Gitea
# Użycie: ./git-init.sh [gitea_user] [gitea_repo]

set -e
set -x

# Parametry
GITEA_USER="${1:-ms}"
GITEA_REPO="${2:-ksef-pdf-generator}"
GITEA_URL="https://10.1.1.1:30008/${GITEA_USER}/${GITEA_REPO}.git"

# Kolory
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m'

echo -e "${YELLOW}🚀 Git initialization for Gitea${NC}"
echo "Gitea URL: $GITEA_URL"
echo ""

# Krok 1: Konfiguracja git (ignorowanie cert dla self-signed)
echo -e "${YELLOW}1️⃣  Configuring git...${NC}"
git config --global http.sslVerify false
git config user.name "Mirek SIC"
git config user.email "mirek@sic.pl"
echo -e "${GREEN}✓ Git configured${NC}"
echo ""

# Krok 2: Inicjalizacja repozytorium
echo -e "${YELLOW}2️⃣  Initializing repository...${NC}"
if [ ! -d ".git" ]; then
  git init
  git checkout -b main
else
  echo "Repository already initialized"
fi
echo -e "${GREEN}✓ Repository ready${NC}"
echo ""

# Krok 3: Dodanie remote
echo -e "${YELLOW}3️⃣  Adding remote origin...${NC}"
if git remote | grep -q origin; then
  echo "Removing existing origin..."
  git remote remove origin
fi
git remote add origin "$GITEA_URL"
echo -e "${GREEN}✓ Remote added: $GITEA_URL${NC}"
echo ""

# Krok 4: Stage i commit
echo -e "${YELLOW}4️⃣  Staging and committing...${NC}"
git add .
git commit -m "Initial commit: KSEF PDF Generator from GitHub" --allow-empty || true
echo -e "${GREEN}✓ Changes committed${NC}"
echo ""

# Krok 5: Push do Gitea
echo -e "${YELLOW}5️⃣  Pushing to Gitea...${NC}"
git push -u origin main 2>&1 || (
  echo ""
  echo -e "${YELLOW}⚠️  Push failed. Debug info:${NC}"
  echo "URL: $GITEA_URL"
  echo "Credentials: mirek@sic.pl"
  echo ""
  echo "Opcje debugowania:"
  echo "  GIT_TRACE=1 git push -u origin main"
  echo "  git remote -v"
  exit 1
)
echo -e "${GREEN}✓ Push successful${NC}"
echo ""

echo -e "${GREEN}✅ Git setup complete!${NC}"
echo ""
echo "Repository: $GITEA_URL"
echo ""
echo "Dalsze komendy:"
echo "  git status"
echo "  git log --oneline"
echo "  git push origin main"
echo "  git pull origin main"
