#!/bin/bash
# Website Deployment Script
# Syncs files from git repository to /var/www/skyartshop/

set -e  # Exit on error

REPO_DIR="/media/pts/Website/SkyArtShop"
DEPLOY_DIR="/var/www/skyartshop"

echo "========================================="
echo "  SkyArtShop Website Deployment"
echo "========================================="
echo ""
echo "📁 Repository: $REPO_DIR"
echo "🌐 Deploy to:  $DEPLOY_DIR"
echo ""

# Check if we're in the repo directory
if [ ! -d "$REPO_DIR/.git" ]; then
    echo "❌ Error: Not in git repository"
    exit 1
fi

cd "$REPO_DIR"

# Show current branch
CURRENT_BRANCH=$(git branch --show-current)
echo "🔀 Current branch: $CURRENT_BRANCH"
echo ""

# Copy/sync website files
echo "📦 Deploying website files..."

# Create website directory structure in repo if it doesn't exist
mkdir -p website/public
mkdir -p website/admin
mkdir -p website/assets
mkdir -p website/uploads

# Copy current live files to repo for version control (first time setup)
if [ ! -f "website/public/shop.html" ]; then
    echo "📥 First time setup - copying live files to repository..."
    cp -r $DEPLOY_DIR/public/* website/public/ 2>/dev/null || true
    cp -r $DEPLOY_DIR/admin/* website/admin/ 2>/dev/null || true
    cp -r $DEPLOY_DIR/assets/* website/assets/ 2>/dev/null || true
    echo "✅ Files copied to repository"
    echo ""
    echo "⚠️  Please commit these files to git:"
    echo "   git add website/"
    echo "   git commit -m 'Add website files to repository'"
    echo ""
fi

# Deploy from repository to live site
echo "🚀 Deploying to live site..."

# Sync public files
rsync -av --delete website/public/ $DEPLOY_DIR/public/ 2>/dev/null || cp -r website/public/* $DEPLOY_DIR/public/

# Sync admin files
rsync -av --delete website/admin/ $DEPLOY_DIR/admin/ 2>/dev/null || cp -r website/admin/* $DEPLOY_DIR/admin/

# Sync assets (but don't delete to preserve any user uploads)
rsync -av website/assets/ $DEPLOY_DIR/assets/ 2>/dev/null || cp -r website/assets/* $DEPLOY_DIR/assets/

# Fix permissions
chown -R pts:pts $DEPLOY_DIR/public $DEPLOY_DIR/admin $DEPLOY_DIR/assets 2>/dev/null || true
chmod -R 644 $DEPLOY_DIR/public/*.html $DEPLOY_DIR/admin/*.html 2>/dev/null || true

echo ""
echo "========================================="
echo "✅ Deployment Complete!"
echo "========================================="
echo ""
echo "🌐 Website: https://skyarts.ddns.net"
echo "🔐 Admin:   https://skyarts.ddns.net/admin"
echo ""
echo "📝 Next steps:"
echo "   1. Edit files in: $REPO_DIR/website/"
echo "   2. Run this script to deploy"
echo "   3. Commit changes: git add . && git commit -m 'Update website'"
echo ""
