#!/bin/bash

# Flutter Tank Web App - Update Script
# Erstellt ein neues Web Build und kopiert es auf den Server

set -e

# Configuration
SERVER_USER="root"
SERVER_IP="192.168.1.19"
SERVER_PATH="/root/weightserver"

echo "🚀 Starting Flutter Web App Update..."
echo "================================================"

# Step 1: Build Flutter Web
echo "📦 Building Flutter web release..."
flutter build web --release --no-wasm-dry-run

if [ $? -ne 0 ]; then
    echo "❌ Build failed!"
    exit 1
fi

echo "✅ Build successful!"

# Step 2: Clean and copy to local webserver folder (preserve installDocker)
echo "🧹 Cleaning webserver folder (keeping installDocker)..."
rm -rf webserver/assets webserver/canvaskit webserver/icons
rm -f webserver/*.js webserver/*.json webserver/*.html webserver/*.png

echo "📋 Copying new build to webserver folder..."
cp -r build/web/* webserver/

echo "✅ Local webserver folder updated!"

# Step 3: Copy to server
echo "📤 Copying to server $SERVER_IP..."
sudo scp -r webserver/* $SERVER_USER@$SERVER_IP:$SERVER_PATH/

if [ $? -ne 0 ]; then
    echo "❌ Server copy failed!"
    exit 1
fi

echo "✅ Files copied to server!"

# Step 4: Restart webserver
echo "🔄 Restarting webserver container..."
ssh $SERVER_USER@$SERVER_IP "cd $SERVER_PATH/installDocker && ./deploy.sh"

if [ $? -ne 0 ]; then
    echo "⚠️  Warning: Server restart failed or deploy.sh not found"
    echo "   You may need to manually restart the webserver"
else
    echo "✅ Webserver restarted!"
fi

echo ""
echo "✅ Update complete!"
echo "================================================"
echo "Your app should now be updated at:"
echo "  http://weight.joshihomeserver.ipv64.net"
echo "================================================"
