some more gitea

This commit is contained in:
2025-11-21 22:40:03 +00:00
parent 76e9166a04
commit 5c12c467b7
5 changed files with 1204 additions and 0 deletions

227
scripts/GITEA_MIGRATION.md Normal file
View File

@@ -0,0 +1,227 @@
# Gitea Repository Migration Guide
This guide explains how to migrate your existing Git repositories from `/home/mleku/Documents/github` to your Gitea installation.
## Prerequisites
1. **Gitea is installed and running** on your VPS (use `giteainstall.sh`)
2. **You have completed the Gitea setup wizard** and created an admin account
3. **SSH access** to your VPS (if migrating to remote server)
4. **Git is installed** on your local machine
## Step 1: Generate Gitea API Token
1. Log in to your Gitea instance at `http://your-vps-ip:3000`
2. Click on your avatar → **Settings**
3. Navigate to **Applications****Manage Access Tokens**
4. Click **Generate New Token**
5. Give it a name (e.g., "migration")
6. Select the following scopes:
- `read:repository`
- `write:repository`
- `read:user`
- `write:user`
- Or simply select **all** scopes for convenience
7. Click **Generate Token**
8. **Copy the token** (you won't be able to see it again!)
## Step 2: Configure Environment Variables
On your **local machine** (where the repositories are), set up the configuration:
```bash
# Gitea API token (required)
export GITEA_TOKEN="your-token-here"
# Gitea URL (update with your VPS IP or domain)
export GITEA_URL="http://your-vps-ip:3000"
# VPS SSH connection (if migrating to remote server)
# Format: user@hostname or user@ip
export VPS_HOST="mleku@your-vps-ip"
# Source directory (default is /home/mleku/Documents/github)
export SOURCE_DIR="/home/mleku/Documents/github"
```
### For Local Gitea Installation
If Gitea is installed locally (on the same machine as the repos):
```bash
export GITEA_TOKEN="your-token-here"
export GITEA_URL="http://localhost:3000"
# Don't set VPS_HOST
```
## Step 3: Test with Dry Run
Before actually migrating, do a dry run to see what would happen:
```bash
DRY_RUN=true ./scripts/gitea-migrate-repos.sh
```
This will:
- Check connectivity to Gitea
- List all repositories to be migrated
- Show what would be created
- **Not make any actual changes**
## Step 4: Run the Migration
Once you've verified the dry run looks good:
```bash
./scripts/gitea-migrate-repos.sh
```
The script will:
1. Connect to Gitea and verify your token
2. Scan for all Git repositories in the source directory
3. Ask for confirmation before proceeding
4. For each repository:
- Check if it already exists in Gitea
- Create the repository via API (if it doesn't exist)
- Push all branches and tags to Gitea
- Report success or failure
5. Display a summary at the end
## Step 5: Verify Migration
After the migration completes:
1. Visit your Gitea instance: `http://your-vps-ip:3000`
2. Check that all repositories are visible
3. Browse a few repositories to verify the content
4. Check that branches and tags were migrated
## Configuration Options
The script supports several environment variables:
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `GITEA_TOKEN` | Gitea API token | - | Yes |
| `GITEA_URL` | Gitea server URL | `http://localhost:3000` | No |
| `VPS_HOST` | SSH host for VPS | - | No (if local) |
| `SOURCE_DIR` | Source repo directory | `/home/mleku/Documents/github` | No |
| `DRY_RUN` | Dry run mode | `false` | No |
## SSH Configuration for Remote VPS
If migrating to a remote VPS, ensure SSH access is configured:
```bash
# Test SSH connection
ssh mleku@your-vps-ip
# Set up SSH key if not already done
ssh-copy-id mleku@your-vps-ip
```
### SSH Port Configuration
By default, Gitea uses SSH port **2222** (to avoid conflicts with system SSH on port 22).
If you need to use a different SSH port, you'll need to:
1. Update Gitea configuration in `/home/mleku/gitea/custom/conf/app.ini`:
```ini
[server]
SSH_LISTEN_PORT = 2222 # Change this to your preferred port
```
2. Restart Gitea:
```bash
sudo systemctl restart gitea
```
## Troubleshooting
### "Cannot connect to Gitea"
- Check that Gitea is running: `sudo systemctl status gitea`
- Verify the URL is correct
- Check firewall rules if accessing remotely
### "Invalid Gitea token"
- Regenerate the token in Gitea settings
- Make sure you copied the entire token
- Verify the token has the necessary scopes
### "Failed to push"
- Check SSH connectivity: `ssh -p 2222 mleku@your-vps-ip`
- Verify SSH keys are set up correctly
- Check Gitea logs: `sudo journalctl -u gitea -f`
### "Repository already exists"
The script will skip repositories that already exist. You can:
- Answer "y" when prompted to push updates to existing repos
- Delete the repo in Gitea and run the script again
- Manually push updates using git
## Example: Complete Migration
Here's a complete example for migrating to a VPS:
```bash
# 1. Set up environment
export GITEA_TOKEN="a1b2c3d4e5f6g7h8i9j0"
export GITEA_URL="http://192.168.1.100:3000"
export VPS_HOST="mleku@192.168.1.100"
# 2. Test connection and do dry run
DRY_RUN=true ./scripts/gitea-migrate-repos.sh
# 3. Review output, then run actual migration
./scripts/gitea-migrate-repos.sh
# 4. Confirm when prompted
# Press 'y' to continue
# 5. Wait for migration to complete
# The script will show progress for each repository
# 6. Review summary
# Check for any failures and investigate
```
## Post-Migration
After successful migration:
1. **Update remote URLs** in your local development repositories:
```bash
cd /home/mleku/Documents/github/your-repo
git remote set-url origin http://your-vps-ip:3000/mleku/your-repo.git
```
2. **Set up SSH URLs** for password-less push (recommended):
```bash
git remote set-url origin ssh://mleku@your-vps-ip:2222/mleku/your-repo.git
```
3. **Test push/pull**:
```bash
git pull origin main
git push origin main
```
## Statistics
Your migration includes:
- **86 repositories** found in `/home/mleku/Documents/github`
- All branches will be migrated
- All tags will be migrated
- Repository descriptions will be extracted from README.md or .git/description
## Support
If you encounter issues:
1. Check Gitea logs: `sudo journalctl -u gitea -f`
2. Enable verbose Git output: `GIT_TRACE=1 ./scripts/gitea-migrate-repos.sh`
3. Check the script output for specific error messages

208
scripts/GITEA_QUICKSTART.md Normal file
View File

@@ -0,0 +1,208 @@
# Gitea Quick Start Guide
Quick reference for installing and using Gitea with your repositories.
## Installation
### 1. Install Gitea on Your Server
```bash
# Run the installation script
./scripts/giteainstall.sh
# Install systemd service
sudo cp scripts/gitea.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable gitea
sudo systemctl start gitea
# Check status
sudo systemctl status gitea
```
### 2. Complete Web Setup
Visit `http://your-server-ip:3000` and complete the installation wizard.
## SSH Configuration (Optional)
To use system SSH on port 22 instead of Gitea's built-in SSH on port 2222:
```bash
# Run on the server as the mleku user
./scripts/gitea-ssh-setup.sh
# Restart Gitea
sudo systemctl restart gitea
```
See [GITEA_SSH_SETUP.md](GITEA_SSH_SETUP.md) for detailed SSH configuration.
## Repository Migration
### Quick Migration (HTTP - Recommended)
```bash
# 1. Generate API token in Gitea (Settings → Applications)
# 2. Configure environment
export GITEA_TOKEN="your-token-here"
export GITEA_URL="http://your-server-ip:3000"
export VPS_HOST="mleku@your-server-ip"
# 3. Run migration
./scripts/gitea-migrate-repos.sh
```
### SSH Migration (After SSH Setup)
```bash
# After configuring SSH (see above)
export GITEA_TOKEN="your-token-here"
export GITEA_URL="http://your-server-ip:3000"
export VPS_HOST="mleku@your-server-ip"
export USE_SSH=true
./scripts/gitea-migrate-repos.sh
```
## Available Scripts
| Script | Purpose |
|--------|---------|
| `giteainstall.sh` | Install Gitea to `/home/mleku/gitea` |
| `gitea-ssh-setup.sh` | Configure system SSH (port 22) |
| `gitea-migrate-repos.sh` | Migrate repositories from local directory |
## Configuration Files
| File | Purpose |
|------|---------|
| `/home/mleku/gitea/custom/conf/app.ini` | Gitea configuration |
| `scripts/gitea.service` | Systemd service file |
| `/etc/systemd/system/gitea.service` | Installed service file |
## Common Commands
### Service Management
```bash
# Start/stop/restart
sudo systemctl start gitea
sudo systemctl stop gitea
sudo systemctl restart gitea
# View status
sudo systemctl status gitea
# View logs
sudo journalctl -u gitea -f
```
### Database Location
```bash
# SQLite database
/home/mleku/gitea/data/gitea.db
# Repositories
/home/mleku/gitea/data/gitea-repositories/
```
### Backup
```bash
# Backup entire Gitea directory
tar -czf gitea-backup-$(date +%Y%m%d).tar.gz /home/mleku/gitea
# Backup database only
cp /home/mleku/gitea/data/gitea.db ~/backups/
```
## URLs and Ports
| Service | URL/Port | Purpose |
|---------|----------|---------|
| Web UI | `http://server:3000` | Gitea web interface |
| HTTP Git | `http://server:3000/user/repo.git` | HTTP clone |
| SSH (system) | `git@server:user/repo.git` | SSH clone (port 22) |
| SSH (built-in) | `git@server:2222/user/repo.git` | SSH clone (port 2222) |
## Environment Variables for Migration
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `GITEA_TOKEN` | Yes | - | API token from Gitea |
| `GITEA_URL` | No | `http://localhost:3000` | Gitea server URL |
| `VPS_HOST` | No | - | SSH host (e.g., `mleku@server`) |
| `SOURCE_DIR` | No | `/home/mleku/Documents/github` | Source repository directory |
| `USE_SSH` | No | `false` | Use SSH instead of HTTP |
| `DRY_RUN` | No | `false` | Test without making changes |
## Troubleshooting
### Gitea won't start
```bash
# Check logs
sudo journalctl -u gitea -n 50
# Check configuration
cat /home/mleku/gitea/custom/conf/app.ini
# Check permissions
ls -la /home/mleku/gitea
```
### Migration fails
```bash
# Test connection
curl http://your-server:3000/api/v1/version
# Verify token
curl -H "Authorization: token ${GITEA_TOKEN}" \
http://your-server:3000/api/v1/user
# Try dry run first
DRY_RUN=true ./scripts/gitea-migrate-repos.sh
```
### SSH not working
```bash
# Test SSH
ssh -T git@your-server
# Check Gitea SSH config
grep SSH /home/mleku/gitea/custom/conf/app.ini
# Check SSH keys in Gitea
# Settings → SSH/GPG Keys
```
## Security Notes
1. **Firewall**: Open required ports (3000 for HTTP, 22 for SSH)
2. **API Token**: Keep your API token secure, never commit it
3. **SSH Keys**: Add your public SSH key to Gitea for SSH access
4. **Backups**: Regularly backup `/home/mleku/gitea`
5. **HTTPS**: Consider setting up TLS for production use
## Next Steps
After installation:
1. ✅ Create admin account (via web interface)
2. ✅ Generate API token (Settings → Applications)
3. ✅ Configure SSH (optional, see GITEA_SSH_SETUP.md)
4. ✅ Migrate repositories (see GITEA_MIGRATION.md)
5. ✅ Set up backups (automated cron job recommended)
6. ✅ Configure HTTPS (for production)
## Getting Help
- **Gitea Documentation**: See [GITEA_MIGRATION.md](GITEA_MIGRATION.md) and [GITEA_SSH_SETUP.md](GITEA_SSH_SETUP.md)
- **Gitea Logs**: `sudo journalctl -u gitea -f`
- **Configuration**: `/home/mleku/gitea/custom/conf/app.ini`
- **Official Docs**: https://docs.gitea.com/

343
scripts/GITEA_SSH_SETUP.md Normal file
View File

@@ -0,0 +1,343 @@
# Gitea SSH Setup Guide
This guide explains how to configure Gitea to use your system's SSH server on port 22 instead of running its own SSH server on port 2222.
## Overview
By default, Gitea runs its own SSH server on port 2222 to avoid conflicts with the system SSH server. However, you can configure it to use the system SSH daemon on port 22, which provides:
- **Single SSH Port**: No need to remember port 2222
- **Standard Git URLs**: Use standard `git@host:repo.git` format
- **Centralized SSH Management**: All SSH traffic through system sshd
- **Better Integration**: Works seamlessly with existing SSH infrastructure
## Quick Setup (Automated)
Use the provided script to configure everything automatically:
```bash
# Run as the gitea user (mleku)
./scripts/gitea-ssh-setup.sh
```
The script will:
- Configure Gitea to use system SSH
- Update `app.ini` with correct SSH settings
- Back up your existing configuration
- Display next steps
## Manual Setup
If you prefer to configure manually, follow these steps:
### Step 1: Update Gitea Configuration
Edit `/home/mleku/gitea/custom/conf/app.ini` and update the `[server]` section:
```ini
[server]
# ... other settings ...
# Disable Gitea's built-in SSH server
START_SSH_SERVER = false
# SSH domain (use your server's hostname or IP)
SSH_DOMAIN = your-server.com
# SSH port (system SSH port)
SSH_PORT = 22
# Don't disable SSH protocol support
DISABLE_SSH = false
```
### Step 2: Restart Gitea
```bash
sudo systemctl restart gitea
```
### Step 3: Verify Configuration
Check that Gitea is no longer listening on port 2222:
```bash
# Should not show Gitea on port 2222
sudo netstat -tlnp | grep 2222
# System SSH should be on port 22
sudo netstat -tlnp | grep :22
```
## Adding SSH Keys to Gitea
Once configured, users need to add their SSH public keys to Gitea:
### Generate SSH Key (if needed)
```bash
# Generate a new ED25519 key (recommended)
ssh-keygen -t ed25519 -C "your-email@example.com"
# Or generate RSA key (older systems)
ssh-keygen -t rsa -b 4096 -C "your-email@example.com"
```
### Add Key to Gitea
1. **Copy your public key:**
```bash
cat ~/.ssh/id_ed25519.pub
# or
cat ~/.ssh/id_rsa.pub
```
2. **Add to Gitea:**
- Log in to Gitea web interface
- Click your avatar → **Settings**
- Navigate to **SSH / GPG Keys**
- Click **Add Key**
- Paste your public key
- Give it a name (e.g., "My Laptop")
- Click **Add Key**
### Test SSH Connection
```bash
# Test SSH authentication
ssh -T git@your-server.com
# Expected output:
# Hi there, username! You've successfully authenticated, but Gitea does not provide shell access.
```
## Using SSH with Git
Once SSH is configured and your key is added, you can use standard Git SSH URLs:
### Clone Repository
```bash
# Standard SSH URL format
git clone git@your-server.com:username/repo-name.git
# Example
git clone git@your-server.com:mleku/orly.git
```
### Add Remote to Existing Repository
```bash
cd /path/to/your/repo
git remote add origin git@your-server.com:mleku/repo-name.git
```
### Push/Pull
```bash
git push origin main
git pull origin main
```
## Update Migration Script for SSH
If you want to use SSH for repository migration instead of HTTP, update the environment:
```bash
# Don't set VPS_HOST - SSH will use standard port 22
export GITEA_TOKEN="your-token"
export GITEA_URL="http://your-server:3000" # Still needed for API
# Update migration script to use SSH
# (You would need to modify the script to support this)
```
## Troubleshooting
### "Permission denied (publickey)"
**Problem**: SSH key not added or not being used
**Solutions**:
1. Verify key is added to Gitea: Settings → SSH/GPG Keys
2. Ensure SSH agent has your key:
```bash
ssh-add -l
ssh-add ~/.ssh/id_ed25519 # Add if not listed
```
3. Test with verbose output:
```bash
ssh -vvv -T git@your-server.com
```
### "Could not resolve hostname"
**Problem**: DNS or hostname issue
**Solutions**:
1. Use IP address instead:
```bash
git clone git@192.168.1.100:mleku/repo.git
```
2. Add entry to `/etc/hosts`:
```
192.168.1.100 your-server.com
```
### SSH Uses Wrong Port
**Problem**: Git trying to use port 2222
**Solutions**:
1. Verify `app.ini` has `SSH_PORT = 22`
2. Restart Gitea: `sudo systemctl restart gitea`
3. Check repository remote URL:
```bash
git remote -v
# Should show: git@host:user/repo.git (not port 2222)
```
### Gitea Still Listening on Port 2222
**Problem**: Built-in SSH server still running
**Solutions**:
1. Verify `START_SSH_SERVER = false` in `app.ini`
2. Restart Gitea: `sudo systemctl restart gitea`
3. Check logs: `sudo journalctl -u gitea -f`
## SSH Configuration Files
### Gitea Configuration
Location: `/home/mleku/gitea/custom/conf/app.ini`
Relevant settings:
```ini
[server]
START_SSH_SERVER = false # Don't run built-in SSH
SSH_DOMAIN = localhost
SSH_PORT = 22 # System SSH port
DISABLE_SSH = false # Allow SSH protocol
```
### System SSH Configuration
Location: `/etc/ssh/sshd_config`
No changes needed - Gitea works with standard SSH configuration.
## Advanced: SSH Config File
For convenience, add an SSH config entry:
Create/edit `~/.ssh/config`:
```
Host gitea
HostName your-server.com
User git
Port 22
IdentityFile ~/.ssh/id_ed25519
Host gitea-vpn
HostName 10.0.0.1
User git
Port 22
IdentityFile ~/.ssh/id_ed25519
```
Usage:
```bash
# Clone using SSH alias
git clone gitea:mleku/repo.git
# Or VPN alias
git clone gitea-vpn:mleku/repo.git
```
## Security Considerations
### SSH Key Best Practices
1. **Use ED25519 keys** (modern, secure, fast)
2. **Protect private keys** with passphrase
3. **Use different keys** for different servers
4. **Rotate keys** periodically
5. **Remove old keys** from Gitea when no longer needed
### Firewall Configuration
Ensure port 22 is accessible:
```bash
# UFW
sudo ufw allow 22/tcp
# iptables
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
```
### Restrict SSH Access
In `/etc/ssh/sshd_config`:
```
# Only allow specific users
AllowUsers mleku git
# Disable password authentication (keys only)
PasswordAuthentication no
PubkeyAuthentication yes
# Disable root login
PermitRootLogin no
```
Restart SSH:
```bash
sudo systemctl restart sshd
```
## Comparison: Built-in vs System SSH
| Feature | Built-in SSH (Port 2222) | System SSH (Port 22) |
|---------|--------------------------|----------------------|
| Port | 2222 | 22 |
| Configuration | Gitea-managed | System sshd |
| URLs | `git@host:2222/user/repo.git` | `git@host:user/repo.git` |
| Setup | Automatic | Requires configuration |
| Isolation | Separate from system | Shared with system |
| Management | Via Gitea | Via sshd config |
## Migration: 2222 → 22
If you already have repositories using port 2222, update them:
```bash
# Update single repository
cd /path/to/repo
git remote set-url origin git@your-server.com:mleku/repo.git
# Bulk update script
for repo in ~/Documents/github/*/; do
cd "$repo"
if git remote get-url origin | grep -q ":2222/"; then
new_url=$(git remote get-url origin | sed 's/:2222\//:/g')
git remote set-url origin "$new_url"
echo "Updated: $(basename $repo)"
fi
done
```
## Summary
Using system SSH with Gitea provides a cleaner, more standard Git experience:
✅ Standard SSH port (22)
✅ Standard Git URLs (`git@host:user/repo.git`)
✅ Centralized SSH management
✅ Works with existing SSH infrastructure
✅ No special port forwarding needed
The trade-off is slightly more complex initial setup compared to using Gitea's built-in SSH server.

319
scripts/gitea-migrate-repos.sh Executable file
View File

@@ -0,0 +1,319 @@
#!/usr/bin/env bash
set -euo pipefail
# Gitea Repository Migration Script
# Migrates Git repositories from local directory to Gitea server
# Configuration (edit these values)
GITEA_URL="${GITEA_URL:-http://localhost:3000}" # Gitea URL
GITEA_TOKEN="${GITEA_TOKEN:-}" # Gitea API token (required)
SOURCE_DIR="${SOURCE_DIR:-/home/mleku/Documents/github}"
VPS_HOST="${VPS_HOST:-}" # SSH host for VPS (e.g., user@vps.example.com)
USE_SSH="${USE_SSH:-false}" # Set to true to use SSH instead of HTTP for push
DRY_RUN="${DRY_RUN:-false}" # Set to true for dry run
# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'
# Stats
TOTAL_REPOS=0
CREATED_REPOS=0
PUSHED_REPOS=0
SKIPPED_REPOS=0
FAILED_REPOS=0
echo -e "${GREEN}=== Gitea Repository Migration Script ===${NC}"
echo ""
# Validate configuration
if [ -z "$GITEA_TOKEN" ]; then
echo -e "${RED}Error: GITEA_TOKEN is required${NC}"
echo ""
echo "To generate a Gitea API token:"
echo "1. Log in to Gitea at ${GITEA_URL}"
echo "2. Go to Settings -> Applications -> Generate New Token"
echo "3. Give it a name (e.g., 'migration') and select all scopes"
echo "4. Copy the token and run:"
echo " export GITEA_TOKEN='your-token-here'"
echo ""
exit 1
fi
if [ ! -d "$SOURCE_DIR" ]; then
echo -e "${RED}Error: Source directory does not exist: ${SOURCE_DIR}${NC}"
exit 1
fi
echo "Configuration:"
echo " Gitea URL: ${GITEA_URL}"
echo " Source directory: ${SOURCE_DIR}"
echo " VPS Host: ${VPS_HOST:-<local installation>}"
echo " Push method: $([ "$USE_SSH" = "true" ] && echo "SSH" || echo "HTTP with token")"
echo " Dry run: ${DRY_RUN}"
echo ""
# Function to check if Gitea is accessible
check_gitea() {
echo -e "${YELLOW}Checking Gitea accessibility...${NC}"
if ! curl -sf "${GITEA_URL}/api/v1/version" > /dev/null; then
echo -e "${RED}Error: Cannot connect to Gitea at ${GITEA_URL}${NC}"
echo "Make sure Gitea is running and accessible."
exit 1
fi
# Verify token
if ! curl -sf -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_URL}/api/v1/user" > /dev/null; then
echo -e "${RED}Error: Invalid Gitea token${NC}"
exit 1
fi
GITEA_USER=$(curl -sf -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_URL}/api/v1/user" | grep -o '"login":"[^"]*"' | cut -d'"' -f4)
echo -e "${GREEN}✓ Connected to Gitea as: ${GITEA_USER}${NC}"
}
# Function to find all Git repositories
find_repos() {
echo -e "${YELLOW}Scanning for Git repositories...${NC}"
mapfile -t REPOS < <(find "${SOURCE_DIR}" -maxdepth 2 -name .git -type d | sed 's|/.git$||')
TOTAL_REPOS=${#REPOS[@]}
echo -e "${GREEN}✓ Found ${TOTAL_REPOS} repositories${NC}"
echo ""
}
# Function to get repository name from path
get_repo_name() {
basename "$1"
}
# Function to get repository description from Git config
get_repo_description() {
local repo_path="$1"
local desc=""
# Try to get description from .git/description
if [ -f "${repo_path}/.git/description" ]; then
desc=$(cat "${repo_path}/.git/description" | grep -v "^Unnamed repository" || true)
fi
# If empty, try README
if [ -z "$desc" ] && [ -f "${repo_path}/README.md" ]; then
desc=$(head -n 1 "${repo_path}/README.md" | sed 's/^#*\s*//')
fi
echo "$desc"
}
# Function to check if repo exists in Gitea
repo_exists() {
local repo_name="$1"
curl -sf -H "Authorization: token ${GITEA_TOKEN}" \
"${GITEA_URL}/api/v1/repos/${GITEA_USER}/${repo_name}" > /dev/null
}
# Function to create repository in Gitea
create_repo() {
local repo_name="$1"
local description="$2"
if [ "$DRY_RUN" = "true" ]; then
echo -e "${BLUE}[DRY RUN]${NC} Would create: ${repo_name}"
return 0
fi
local json_data=$(cat <<EOF
{
"name": "${repo_name}",
"description": "${description}",
"private": false,
"auto_init": false
}
EOF
)
if curl -sf -X POST \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "$json_data" \
"${GITEA_URL}/api/v1/user/repos" > /dev/null; then
return 0
else
return 1
fi
}
# Function to push repository to Gitea
push_repo() {
local repo_path="$1"
local repo_name="$2"
if [ "$DRY_RUN" = "true" ]; then
echo -e "${BLUE}[DRY RUN]${NC} Would push: ${repo_name}"
return 0
fi
cd "$repo_path"
# Check if gitea remote already exists
if git remote | grep -q "^gitea$"; then
git remote remove gitea 2>/dev/null || true
fi
# Build Git URL based on SSH or HTTP preference
local git_url
if [ "$USE_SSH" = "true" ]; then
# Use SSH URL
if [ -n "$VPS_HOST" ]; then
# Extract host from VPS_HOST (format: user@host or just host)
local ssh_host=$(echo "$VPS_HOST" | grep -oP '@\K.*' || echo "$VPS_HOST")
git_url="git@${ssh_host}:${GITEA_USER}/${repo_name}.git"
else
# Use local host
local gitea_host=$(echo "$GITEA_URL" | sed -E 's|https?://||' | cut -d':' -f1)
git_url="git@${gitea_host}:${GITEA_USER}/${repo_name}.git"
fi
else
# Use HTTP URL with token authentication (more reliable for automation)
# Extract the base URL (http:// or https://)
local protocol=$(echo "$GITEA_URL" | grep -oP '^https?')
local url_without_protocol=$(echo "$GITEA_URL" | sed -E 's|^https?://||')
# Build authenticated URL: http://username:token@host:port/username/repo.git
git_url="${protocol}://${GITEA_USER}:${GITEA_TOKEN}@${url_without_protocol}/${GITEA_USER}/${repo_name}.git"
fi
# Add Gitea remote with URL
git remote add gitea "$git_url"
# Push all branches and tags
local push_success=true
# Push all branches
if ! git push gitea --all 2>&1; then
push_success=false
fi
# Push all tags
if ! git push gitea --tags 2>&1; then
push_success=false
fi
# Clean up - remove the remote to avoid storing token in git config (HTTP only)
if [ "$USE_SSH" != "true" ]; then
git remote remove gitea 2>/dev/null || true
fi
if [ "$push_success" = true ]; then
return 0
else
return 1
fi
}
# Main migration function
migrate_repos() {
echo -e "${GREEN}Starting migration...${NC}"
echo ""
local count=0
for repo_path in "${REPOS[@]}"; do
count=$((count + 1))
local repo_name=$(get_repo_name "$repo_path")
echo -e "${BLUE}[${count}/${TOTAL_REPOS}]${NC} Processing: ${repo_name}"
# Check if repo already exists
if repo_exists "$repo_name"; then
echo -e " ${YELLOW}${NC} Repository already exists in Gitea"
SKIPPED_REPOS=$((SKIPPED_REPOS + 1))
# Ask if user wants to push updates
if [ "$DRY_RUN" = "false" ]; then
if push_repo "$repo_path" "$repo_name"; then
echo -e " ${GREEN}${NC} Pushed updates"
PUSHED_REPOS=$((PUSHED_REPOS + 1))
else
echo -e " ${RED}${NC} Failed to push"
FAILED_REPOS=$((FAILED_REPOS + 1))
fi
fi
echo ""
continue
fi
# Get description
local description=$(get_repo_description "$repo_path")
if [ -n "$description" ]; then
echo -e " Description: ${description}"
fi
# Create repository
echo -e " Creating repository in Gitea..."
if create_repo "$repo_name" "$description"; then
echo -e " ${GREEN}${NC} Repository created"
CREATED_REPOS=$((CREATED_REPOS + 1))
# Push repository
echo -e " Pushing repository data..."
if push_repo "$repo_path" "$repo_name"; then
echo -e " ${GREEN}${NC} Repository pushed"
PUSHED_REPOS=$((PUSHED_REPOS + 1))
else
echo -e " ${RED}${NC} Failed to push"
FAILED_REPOS=$((FAILED_REPOS + 1))
fi
else
echo -e " ${RED}${NC} Failed to create repository"
FAILED_REPOS=$((FAILED_REPOS + 1))
fi
echo ""
done
}
# Print summary
print_summary() {
echo ""
echo -e "${GREEN}=== Migration Summary ===${NC}"
echo "Total repositories: ${TOTAL_REPOS}"
echo "Created: ${CREATED_REPOS}"
echo "Pushed: ${PUSHED_REPOS}"
echo "Skipped: ${SKIPPED_REPOS}"
echo "Failed: ${FAILED_REPOS}"
echo ""
if [ "$DRY_RUN" = "true" ]; then
echo -e "${YELLOW}This was a dry run. No changes were made.${NC}"
echo "Run without DRY_RUN=true to perform actual migration."
elif [ $FAILED_REPOS -eq 0 ]; then
echo -e "${GREEN}✓ Migration completed successfully!${NC}"
echo ""
echo "Visit your Gitea instance at: ${GITEA_URL}"
else
echo -e "${YELLOW}⚠ Migration completed with some failures${NC}"
echo "Check the output above for details on failed repositories."
fi
}
# Main execution
check_gitea
find_repos
# Confirm before proceeding
if [ "$DRY_RUN" = "false" ]; then
echo -e "${YELLOW}Ready to migrate ${TOTAL_REPOS} repositories.${NC}"
read -p "Continue? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Migration cancelled."
exit 0
fi
echo ""
fi
migrate_repos
print_summary

107
scripts/gitea-ssh-setup.sh Executable file
View File

@@ -0,0 +1,107 @@
#!/usr/bin/env bash
set -euo pipefail
# Gitea SSH Configuration Script
# Configures Gitea to use the system SSH server on port 22
GITEA_BASE_DIR="/home/mleku/gitea"
GITEA_USER="mleku"
SSH_DIR="/home/${GITEA_USER}/.ssh"
# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'
echo -e "${GREEN}=== Gitea SSH Configuration Script ===${NC}"
echo "Configuring Gitea to use system SSH on port 22"
echo ""
# Check if running as the correct user
if [ "$(whoami)" != "$GITEA_USER" ]; then
echo -e "${RED}Error: This script must be run as user '${GITEA_USER}'${NC}"
echo "Run: sudo -u ${GITEA_USER} $0"
exit 1
fi
# Ensure SSH directory exists
echo -e "${YELLOW}Setting up SSH directory...${NC}"
mkdir -p "${SSH_DIR}"
chmod 700 "${SSH_DIR}"
# Create SSH key if it doesn't exist
if [ ! -f "${SSH_DIR}/id_ed25519" ]; then
echo -e "${YELLOW}Generating SSH key for Gitea...${NC}"
ssh-keygen -t ed25519 -C "gitea@$(hostname)" -f "${SSH_DIR}/id_ed25519" -N ""
echo -e "${GREEN}✓ SSH key generated${NC}"
else
echo -e "${GREEN}✓ SSH key already exists${NC}"
fi
# Update Gitea configuration
echo -e "${YELLOW}Updating Gitea configuration...${NC}"
GITEA_CONFIG="${GITEA_BASE_DIR}/custom/conf/app.ini"
if [ ! -f "$GITEA_CONFIG" ]; then
echo -e "${RED}Error: Gitea configuration not found at ${GITEA_CONFIG}${NC}"
exit 1
fi
# Backup existing config
cp "${GITEA_CONFIG}" "${GITEA_CONFIG}.backup.$(date +%Y%m%d_%H%M%S)"
# Update SSH settings in app.ini
# We'll use sed to update or add the SSH settings
if grep -q "^\[server\]" "$GITEA_CONFIG"; then
# Section exists, update settings
sed -i '/^\[server\]/,/^\[/ {
/^DISABLE_SSH/d
/^SSH_DOMAIN/d
/^SSH_PORT/d
/^SSH_LISTEN_HOST/d
/^SSH_LISTEN_PORT/d
/^START_SSH_SERVER/d
}' "$GITEA_CONFIG"
# Add updated settings after [server] section
sed -i '/^\[server\]/a\
START_SSH_SERVER = false\
SSH_DOMAIN = localhost\
SSH_PORT = 22\
DISABLE_SSH = false' "$GITEA_CONFIG"
else
echo -e "${RED}Error: [server] section not found in config${NC}"
exit 1
fi
echo -e "${GREEN}✓ Gitea configuration updated${NC}"
# Print next steps
echo ""
echo -e "${GREEN}=== Configuration Complete ===${NC}"
echo ""
echo "Gitea has been configured to use system SSH on port 22."
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo ""
echo "1. Restart Gitea to apply changes:"
echo " sudo systemctl restart gitea"
echo ""
echo "2. Add your SSH public key to Gitea:"
echo " - Log in to Gitea web interface"
echo " - Go to Settings → SSH/GPG Keys"
echo " - Click 'Add Key'"
echo " - Paste your public key (from ~/.ssh/id_ed25519.pub or id_rsa.pub)"
echo ""
echo "3. Test SSH access:"
echo " ssh -T git@localhost -p 22"
echo " (You should see: 'Hi there! You've successfully authenticated...')"
echo ""
echo "4. Clone repositories using SSH:"
echo " git clone git@your-server:mleku/repo-name.git"
echo ""
echo -e "${BLUE}Configuration backup saved to:${NC}"
echo " ${GITEA_CONFIG}.backup.$(date +%Y%m%d_%H%M%S)"
echo ""