#!/bin/bash
# HoofScan Swiss-Galoppers - Automatisches Server-Upload Script
# Für app1.fr.vps.apmin.ch

echo "🚀 HoofScan Swiss-Galoppers Server-Upload gestartet..."

# Server-Details
SERVER="app1.fr.vps.apmin.ch"
USER="root"
TARGET_DIR="/var/www/hoofscan"

# Dateien vorbereiten
echo "📦 Erstelle Upload-Paket..."

# Temporäres Upload-Verzeichnis erstellen
mkdir -p upload-package

# Notwendige Dateien kopieren
cp -r client upload-package/
cp -r server upload-package/
cp -r shared upload-package/
cp -r public upload-package/
cp -r scripts upload-package/

# Konfigurationsdateien
cp package.json upload-package/
cp package-lock.json upload-package/
cp tsconfig*.json upload-package/
cp ecosystem.config.js upload-package/
cp drizzle.config.ts upload-package/
cp vite.config.ts upload-package/
cp tailwind.config.ts upload-package/
cp postcss.config.js upload-package/
cp components.json upload-package/

# Deployment-Dokumentation
cp PERFEKTE-INSTALLATION.md upload-package/
cp APP1-DEPLOYMENT-GUIDE.md upload-package/
cp INSTALLATION-GUIDE.md upload-package/

# Swiss Galoppers Assets (falls vorhanden)
if [ -d "attached_assets" ]; then
    cp -r attached_assets upload-package/
fi

echo "📤 Upload zu $SERVER..."

# Upload mit rsync (empfohlen) oder scp
if command -v rsync &> /dev/null; then
    rsync -avz --delete upload-package/ $USER@$SERVER:$TARGET_DIR/
else
    scp -r upload-package/* $USER@$SERVER:$TARGET_DIR/
fi

echo "🔧 Automatische Installation auf Server..."

# SSH-Befehle für automatische Installation
ssh $USER@$SERVER << 'ENDSSH'
cd /var/www/hoofscan

echo "📋 Installing dependencies..."
npm install

echo "🏗️ Building application..."
npm run build

echo "🗄️ Setting up database..."
sudo -u postgres psql -c "CREATE DATABASE IF NOT EXISTS hoofscan;"
sudo -u postgres psql -c "CREATE USER IF NOT EXISTS hoofscan_user WITH PASSWORD 'HoofScan2025!';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE hoofscan TO hoofscan_user;"

echo "⚙️ Configuring environment..."
cat > .env << EOF
NODE_ENV=production
PORT=5000
DATABASE_URL=postgresql://hoofscan_user:HoofScan2025!@localhost/hoofscan
DOMAIN=app1.fr.vps.apmin.ch
PROTOCOL=https
SESSION_SECRET=$(openssl rand -base64 32)
EOF

echo "🗃️ Creating database schema..."
npm run db:push

echo "👤 Creating admin user..."
npm run create-admin

echo "🚀 Starting application with PM2..."
pm2 delete hoofscan-swiss-galoppers 2>/dev/null || true
pm2 start ecosystem.config.js
pm2 save

echo "✅ Installation completed successfully!"
echo "🌐 App available at: https://app1.fr.vps.apmin.ch/"

ENDSSH

# Aufräumen
rm -rf upload-package

echo "✅ HoofScan Swiss-Galoppers erfolgreich auf $SERVER installiert!"
echo "🌐 Verfügbar unter: https://$SERVER/"
echo "👤 Admin-Login: admin@swiss-galoppers.com / admin2025!"