refactor: remove unused server-side sync scripts

- Deleted cron-setup.sh for automated sync scheduling
- Removed init-backend.sh database initialization script
- Removed server-sync.sh for platform synchronization
This commit is contained in:
Yusuf İpek
2025-11-12 00:35:37 +03:00
parent 1cb13f5314
commit cce1098282
6 changed files with 47 additions and 522 deletions
-199
View File
@@ -1,199 +0,0 @@
#!/bin/bash
# Cron job setup script for RepoHub auto-sync
# This script sets up automatic sync using cron jobs
set -e
# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SYNC_SCRIPT="$SCRIPT_DIR/server-sync.sh"
CRON_FILE="/etc/cron.d/repohub-sync"
LOG_FILE="/var/log/repohub-sync.log"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Check if running as root
check_root() {
if [ "$EUID" -ne 0 ]; then
log_error "This script must be run as root to setup cron jobs"
echo "Please run: sudo $0"
exit 1
fi
}
# Check if sync script exists
check_sync_script() {
if [ ! -f "$SYNC_SCRIPT" ]; then
log_error "Sync script not found: $SYNC_SCRIPT"
exit 1
fi
# Make sure sync script is executable
chmod +x "$SYNC_SCRIPT"
log_info "Sync script is ready: $SYNC_SCRIPT"
}
# Get sync frequency from environment or default to daily
get_sync_frequency() {
local frequency="${AUTO_SYNC_DAYS:-1}"
echo "$frequency"
}
# Setup cron job
setup_cron() {
local frequency=$(get_sync_frequency)
local cron_schedule="0 2 */$frequency * *" # Run at 2 AM every N days
log_info "Setting up cron job to run every $frequency day(s)"
log_info "Cron schedule: $cron_schedule"
# Create cron file
cat > "$CRON_FILE" << EOF
# RepoHub Auto Sync - Runs every $frequency day(s) at 2 AM
# Environment variables
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
API_URL=${API_URL:-http://localhost:3002}
SYNC_SECRET_KEY=$SYNC_SECRET_KEY
AUTO_SYNC_DAYS=$frequency
# Cron job
$cron_schedule root $SYNC_SCRIPT auto-sync >> $LOG_FILE 2>&1
# Manual sync status check (every hour)
0 * * * * root $SYNC_SCRIPT status >> $LOG_FILE 2>&1
EOF
# Set proper permissions
chmod 644 "$CRON_FILE"
# Reload cron service
if command -v systemctl >/dev/null 2>&1; then
systemctl reload cron || systemctl reload crond || true
elif command -v service >/dev/null 2>&1; then
service cron reload || service crond reload || true
fi
log_info "Cron job installed successfully: $CRON_FILE"
}
# Remove cron job
remove_cron() {
if [ -f "$CRON_FILE" ]; then
rm -f "$CRON_FILE"
log_info "Cron job removed: $CRON_FILE"
# Reload cron service
if command -v systemctl >/dev/null 2>&1; then
systemctl reload cron || systemctl reload crond || true
elif command -v service >/dev/null 2>&1; then
service cron reload || service crond reload || true
fi
else
log_warn "No cron job found to remove"
fi
}
# Show cron status
show_status() {
if [ -f "$CRON_FILE" ]; then
log_info "Cron job is installed:"
cat "$CRON_FILE"
else
log_warn "No cron job found"
fi
if [ -f "$LOG_FILE" ]; then
log_info "Recent sync logs:"
tail -20 "$LOG_FILE"
else
log_warn "No log file found: $LOG_FILE"
fi
}
# Test sync script
test_sync() {
log_info "Testing sync script..."
if [ -z "$SYNC_SECRET_KEY" ]; then
log_error "SYNC_SECRET_KEY environment variable is required for testing"
exit 1
fi
# Run a status check to test connectivity
"$SYNC_SCRIPT" status
}
# Show usage
show_usage() {
echo "Usage: $0 [COMMAND]"
echo ""
echo "Commands:"
echo " install Install cron job for auto-sync"
echo " remove Remove cron job"
echo " status Show cron job status and recent logs"
echo " test Test sync script connectivity"
echo " help Show this help message"
echo ""
echo "Environment variables:"
echo " API_URL API base URL (default: http://localhost:3002)"
echo " SYNC_SECRET_KEY Secret key for sync authorization"
echo " AUTO_SYNC_DAYS Sync frequency in days (default: 1)"
echo " LOG_FILE Log file path (default: /var/log/repohub-sync.log)"
echo ""
echo "Examples:"
echo " $0 install # Install daily cron job"
echo " AUTO_SYNC_DAYS=7 $0 install # Install weekly cron job"
echo " $0 status # Check cron job status"
echo " $0 test # Test sync script"
}
# Main script logic
main() {
case "${1:-}" in
"install")
check_root
check_sync_script
setup_cron
;;
"remove")
check_root
remove_cron
;;
"status")
show_status
;;
"test")
check_sync_script
test_sync
;;
"help"|"-h"|"--help")
show_usage
;;
*)
log_error "Unknown command: ${1:-}"
show_usage
exit 1
;;
esac
}
# Run main function
main "$@"
-117
View File
@@ -1,117 +0,0 @@
#!/bin/bash
# RepoHub Backend Initialization Script
# This script sets up the database and initializes the backend
set -e
echo "🚀 Initializing RepoHub Backend..."
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Configuration
DB_HOST=${DB_HOST:-localhost}
DB_PORT=${DB_PORT:-5432}
DB_NAME=${DB_NAME:-repohub}
DB_USER=${DB_USER:-postgres}
DB_PASSWORD=${DB_PASSWORD:-postgres}
echo -e "${BLUE}📋 Configuration:${NC}"
echo " Host: $DB_HOST"
echo " Port: $DB_PORT"
echo " Database: $DB_NAME"
echo " User: $DB_USER"
# Check if PostgreSQL is running
echo -e "\n${YELLOW}🔍 Checking PostgreSQL connection...${NC}"
if ! pg_isready -h $DB_HOST -p $DB_PORT; then
echo -e "${RED}❌ PostgreSQL is not running on $DB_HOST:$DB_PORT${NC}"
echo "Please start PostgreSQL and try again."
exit 1
fi
echo -e "${GREEN}✅ PostgreSQL is running${NC}"
# Check if database exists
echo -e "\n${YELLOW}🗄️ Checking database...${NC}"
if psql -h $DB_HOST -p $DB_PORT -U $DB_USER -lqt | cut -d \| -f 1 | grep -qw $DB_NAME; then
echo -e "${GREEN}✅ Database '$DB_NAME' already exists${NC}"
else
echo -e "${YELLOW}⚠️ Database '$DB_NAME' does not exist. Creating...${NC}"
createdb -h $DB_HOST -p $DB_PORT -U $DB_USER $DB_NAME
echo -e "${GREEN}✅ Database '$DB_NAME' created${NC}"
fi
# Check if tables exist
echo -e "\n${YELLOW}📊 Checking database tables...${NC}"
TABLES_EXIST=$(psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -tAc "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'platforms');")
if [ "$TABLES_EXIST" = "t" ]; then
echo -e "${GREEN}✅ Database tables already exist${NC}"
read -p "Do you want to reset the database? This will delete all data. (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo -e "${YELLOW}🔄 Resetting database...${NC}"
psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -f src/lib/database/schema.sql
echo -e "${GREEN}✅ Database reset completed${NC}"
else
echo -e "${BLUE}️ Keeping existing data${NC}"
fi
else
echo -e "${YELLOW}⚠️ Database tables do not exist. Creating schema...${NC}"
psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -f src/lib/database/schema.sql
echo -e "${GREEN}✅ Database schema created${NC}"
fi
# Check if node_modules exists
echo -e "\n${YELLOW}📦 Checking dependencies...${NC}"
if [ ! -d "node_modules" ]; then
echo -e "${YELLOW}⚠️ Dependencies not found. Installing...${NC}"
pnpm install
echo -e "${GREEN}✅ Dependencies installed${NC}"
else
echo -e "${GREEN}✅ Dependencies already exist${NC}"
fi
# Check if .env file exists
echo -e "\n${YELLOW}⚙️ Checking environment configuration...${NC}"
if [ ! -f ".env" ]; then
echo -e "${YELLOW}⚠️ .env file not found. Creating from example...${NC}"
cp .env.example .env
echo -e "${GREEN}✅ .env file created${NC}"
echo -e "${YELLOW}⚠️ Please edit .env file with your database credentials${NC}"
echo " Current configuration:"
echo " DB_HOST=$DB_HOST"
echo " DB_PORT=$DB_PORT"
echo " DB_NAME=$DB_NAME"
echo " DB_USER=$DB_USER"
echo " DB_PASSWORD=$DB_PASSWORD"
else
echo -e "${GREEN}✅ .env file already exists${NC}"
fi
# Test database connection
echo -e "\n${YELLOW}🔗 Testing database connection...${NC}"
if pnpm run test:db 2>/dev/null; then
echo -e "${GREEN}✅ Database connection successful${NC}"
else
echo -e "${YELLOW}⚠️ Database connection test failed. This is expected if test script doesn't exist yet.${NC}"
fi
# Display next steps
echo -e "\n${GREEN}🎉 Backend initialization completed!${NC}"
echo -e "\n${BLUE}📋 Next steps:${NC}"
echo "1. Review and update .env file if needed"
echo "2. Start the development server:"
echo " ${YELLOW}pnpm dev${NC}"
echo "3. Test the API endpoints:"
echo " ${YELLOW}curl http://localhost:3000/api/platforms${NC}"
echo "4. Sync Ubuntu packages:"
echo " ${YELLOW}curl -X POST http://localhost:3000/api/sync -H 'Content-Type: application/json' -d '{\"platform_id\": \"ubuntu\"}'${NC}"
echo -e "\n${GREEN}✨ Ready to start development!${NC}"
-185
View File
@@ -1,185 +0,0 @@
#!/bin/bash
# Server-side sync script for RepoHub
# This script can only be run from the server itself when SYNC_SERVER_ONLY=true
set -e
# Configuration
API_URL="${API_URL:-http://localhost:3002}"
SYNC_SECRET="${SYNC_SECRET_KEY}"
LOG_FILE="/var/log/repohub-sync.log"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Logging function
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
log_info() {
echo -e "${GREEN}$(date '+%Y-%m-%d %H:%M:%S') - INFO: $1${NC}" | tee -a "$LOG_FILE"
}
log_warn() {
echo -e "${YELLOW}$(date '+%Y-%m-%d %H:%M:%S') - WARN: $1${NC}" | tee -a "$LOG_FILE"
}
log_error() {
echo -e "${RED}$(date '+%Y-%m-%d %H:%M:%S') - ERROR: $1${NC}" | tee -a "$LOG_FILE"
}
# Check if required environment variables are set
check_env() {
if [ -z "$SYNC_SECRET" ]; then
log_error "SYNC_SECRET_KEY environment variable is required"
exit 1
fi
log_info "Environment variables validated"
}
# Perform sync for a specific platform
sync_platform() {
local platform="$1"
log_info "Starting sync for platform: $platform"
response=$(curl -s -w "\n%{http_code}" -X POST \
-H "Content-Type: application/json" \
-H "x-sync-secret: $SYNC_SECRET" \
-d '{}' \
"$API_URL/api/sync-$platform")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | head -n -1)
if [ "$http_code" -eq 200 ]; then
log_info "Successfully synced $platform: $body"
return 0
else
log_error "Failed to sync $platform (HTTP $http_code): $body"
return 1
fi
}
# Perform auto sync
auto_sync() {
log_info "Starting automatic sync for all platforms"
response=$(curl -s -w "\n%{http_code}" -X POST \
-H "Content-Type: application/json" \
-H "x-sync-secret: $SYNC_SECRET" \
-d '{}' \
"$API_URL/api/auto-sync")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | head -n -1)
if [ "$http_code" -eq 200 ]; then
log_info "Auto sync completed successfully: $body"
return 0
else
log_error "Auto sync failed (HTTP $http_code): $body"
return 1
fi
}
# Get sync status
get_status() {
log_info "Getting sync status"
response=$(curl -s -w "\n%{http_code}" -X GET \
-H "x-sync-secret: $SYNC_SECRET" \
"$API_URL/api/sync")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | head -n -1)
if [ "$http_code" -eq 200 ]; then
log_info "Sync status: $body"
return 0
else
log_error "Failed to get sync status (HTTP $http_code): $body"
return 1
fi
}
# Show usage
show_usage() {
echo "Usage: $0 [COMMAND] [OPTIONS]"
echo ""
echo "Commands:"
echo " auto-sync Perform automatic sync for all platforms"
echo " sync-all Sync all platforms individually"
echo " sync-winget Sync Windows packages"
echo " sync-homebrew Sync macOS packages"
echo " sync-fedora Sync Fedora packages"
echo " sync-arch Sync Arch Linux packages"
echo " status Get current sync status"
echo ""
echo "Environment variables:"
echo " API_URL API base URL (default: http://localhost:3002)"
echo " SYNC_SECRET_KEY Secret key for sync authorization"
echo " LOG_FILE Log file path (default: /var/log/repohub-sync.log)"
echo ""
echo "Examples:"
echo " $0 auto-sync # Auto sync all platforms"
echo " $0 sync-winget # Sync only Windows packages"
echo " API_URL=https://api.repohub.com $0 status # Check status on production"
}
# Main script logic
main() {
# Create log file if it doesn't exist
mkdir -p "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"
log_info "RepoHub Server Sync Script started"
check_env
case "${1:-}" in
"auto-sync")
auto_sync
;;
"sync-all")
log_info "Syncing all platforms individually"
sync_platform "winget"
sync_platform "homebrew"
sync_platform "fedora"
sync_platform "arch"
;;
"sync-winget")
sync_platform "winget"
;;
"sync-homebrew")
sync_platform "homebrew"
;;
"sync-fedora")
sync_platform "fedora"
;;
"sync-arch")
sync_platform "arch"
;;
"status")
get_status
;;
"help"|"-h"|"--help")
show_usage
;;
*)
log_error "Unknown command: ${1:-}"
show_usage
exit 1
;;
esac
log_info "RepoHub Server Sync Script completed"
}
# Run main function with all arguments
main "$@"
+2 -2
View File
@@ -205,7 +205,7 @@ export function PackageBrowserV2({
</CardHeader> </CardHeader>
<CardContent className="pt-0"> <CardContent className="pt-0">
<div className="text-center py-8 text-muted-foreground"> <div className="text-center py-8 text-muted-foreground">
Please select a platform first {t('platform.please_select')}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -219,7 +219,7 @@ export function PackageBrowserV2({
<PackageIcon className="h-5 w-5" /> <PackageIcon className="h-5 w-5" />
{t('packages.title')} {t('packages.title')}
<span className="text-sm font-normal text-muted-foreground"> <span className="text-sm font-normal text-muted-foreground">
({packages.length} of {totalCount} packages for {selectedPlatform?.name || 'Unknown Platform'}) {t('packages.count_label', { current: packages.length, total: totalCount, platform: selectedPlatform?.name || 'Unknown Platform' })}
</span> </span>
</CardTitle> </CardTitle>
<CardDescription className="text-sm"> <CardDescription className="text-sm">
+31 -13
View File
@@ -17,6 +17,16 @@ export function PlatformSelector({ selectedPlatform, onPlatformSelect }: Platfor
const [platforms, setPlatforms] = useState<Platform[]>([]) const [platforms, setPlatforms] = useState<Platform[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const iconSlug: Record<string, string> = {
debian: 'debian',
ubuntu: 'ubuntu',
fedora: 'fedora',
arch: 'archlinux',
windows: 'windows',
macos: 'apple'
}
const iconBase = (slug: string) => `https://cdn.jsdelivr.net/npm/simple-icons@latest/icons/${slug}.svg`
useEffect(() => { useEffect(() => {
const loadPlatforms = async () => { const loadPlatforms = async () => {
try { try {
@@ -62,29 +72,37 @@ export function PlatformSelector({ selectedPlatform, onPlatformSelect }: Platfor
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="pt-0"> <CardContent className="pt-0">
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3"> <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6 gap-2">
{platforms.map((platform) => ( {platforms.map((platform) => (
<Button <Button
key={platform.id} key={platform.id}
variant={selectedPlatform?.id === platform.id ? "default" : "outline"} variant="outline"
className="h-auto p-3 flex flex-col items-center space-y-1" className={`h-12 px-2 py-1 flex flex-col items-center justify-center gap-1 rounded-md border transition-colors
${selectedPlatform?.id === platform.id
? 'border-primary ring-2 ring-primary/60 bg-primary/5'
: 'border-border hover:bg-secondary/60'}`}
onClick={() => onPlatformSelect(platform)} onClick={() => onPlatformSelect(platform)}
> >
<div className="text-xl">{platform.icon}</div> <div
className={`h-5 w-5 ${selectedPlatform?.id === platform.id ? 'text-foreground' : 'text-muted-foreground'}`}
style={{
WebkitMaskImage: `url(${iconBase(iconSlug[platform.id] || 'linux')})`,
maskImage: `url(${iconBase(iconSlug[platform.id] || 'linux')})`,
WebkitMaskRepeat: 'no-repeat',
maskRepeat: 'no-repeat',
WebkitMaskSize: 'contain',
maskSize: 'contain',
WebkitMaskPosition: 'center',
maskPosition: 'center',
backgroundColor: 'currentColor'
} as React.CSSProperties}
/>
<div className="text-center"> <div className="text-center">
<div className="font-semibold text-sm">{platform.name}</div> <div className="font-medium text-xs leading-tight truncate max-w-[90px]">{platform.name}</div>
<div className="text-xs text-muted-foreground">{platform.packageManager}</div>
</div> </div>
</Button> </Button>
))} ))}
</div> </div>
{selectedPlatform && (
<div className="mt-3 p-3 bg-secondary rounded-md">
<p className="text-xs">
<strong>{t('platform.selected')}:</strong> {selectedPlatform.name} ({selectedPlatform.packageManager})
</p>
</div>
)}
</CardContent> </CardContent>
</Card> </Card>
) )
+14 -6
View File
@@ -15,7 +15,8 @@ const translations = {
platform: { platform: {
select: "Select Your Platform", select: "Select Your Platform",
description: "Choose your operating system and package manager to browse available packages", description: "Choose your operating system and package manager to browse available packages",
selected: "Selected" selected: "Selected",
please_select: "Please select a platform first"
}, },
packages: { packages: {
title: "Available Packages", title: "Available Packages",
@@ -23,6 +24,7 @@ const translations = {
description: "Select packages to include in your installation script", description: "Select packages to include in your installation script",
search: "Search packages...", search: "Search packages...",
no_packages: "No packages found matching your criteria", no_packages: "No packages found matching your criteria",
count_label: "({current} of {total} packages for {platform})",
filters: { filters: {
category: "Category", category: "Category",
type: "Type", type: "Type",
@@ -116,7 +118,8 @@ const translations = {
platform: { platform: {
select: "Platformunuzu Seçin", select: "Platformunuzu Seçin",
description: "Mevcut paketlere göz atmak için işletim sisteminizi ve paket yöneticinizi seçin", description: "Mevcut paketlere göz atmak için işletim sisteminizi ve paket yöneticinizi seçin",
selected: "Seçildi" selected: "Seçildi",
please_select: "Lütfen önce bir platform seçin"
}, },
packages: { packages: {
title: "Mevcut Paketler", title: "Mevcut Paketler",
@@ -124,6 +127,7 @@ const translations = {
description: "Kurulum scriptinize dahil edilecek paketleri seçin", description: "Kurulum scriptinize dahil edilecek paketleri seçin",
search: "Paket ara...", search: "Paket ara...",
no_packages: "Kriterlerinize uyan paket bulunamadı", no_packages: "Kriterlerinize uyan paket bulunamadı",
count_label: "({platform} için {current} / {total} paket)",
filters: { filters: {
category: "Kategori", category: "Kategori",
type: "Tür", type: "Tür",
@@ -213,7 +217,7 @@ interface LocaleContextType {
locale: Locale locale: Locale
changeLocale: (locale: Locale) => void changeLocale: (locale: Locale) => void
toggleLocale: () => void toggleLocale: () => void
t: (key: string) => string t: (key: string, params?: Record<string, string | number>) => string
} }
const LocaleContext = createContext<LocaleContextType | undefined>(undefined) const LocaleContext = createContext<LocaleContextType | undefined>(undefined)
@@ -250,15 +254,19 @@ export function LocaleProvider({ children }: { children: ReactNode }) {
changeLocale(locale === 'en' ? 'tr' : 'en') changeLocale(locale === 'en' ? 'tr' : 'en')
} }
const t = (key: string) => { const t = (key: string, params?: Record<string, string | number>) => {
const keys = key.split('.') const keys = key.split('.')
let value: any = translations[locale] let value: any = translations[locale]
for (const k of keys) { for (const k of keys) {
value = value?.[k] value = value?.[k]
} }
if (typeof value === 'string' && params) {
return value || key return value.replace(/\{(\w+)\}/g, (_, k) =>
Object.prototype.hasOwnProperty.call(params, k) ? String(params[k]) : `{${k}}`
)
}
return (typeof value === 'string') ? value : key
} }
return ( return (