#!/bin/bash
# SummitWave deployment with proper cache-busting for CSS/JS

SERVER="www269.your-server.de"
USER="summitb"
REMOTE_DIR="public_html"
LOCAL_DIR="$(dirname "$0")/src"

# === PASSWORD FROM ENVIRONMENT VARIABLE ===
# export SFTP_PASS='DeinSFTPPasswort'
if [ -z "$SFTP_PASS" ]; then
    echo "Error: Please set the SFTP_PASS environment variable with your password."
    exit 1
fi

# === CHECK sshpass INSTALLATION ===
if ! command -v sshpass &> /dev/null; then
    echo "Error: sshpass is not installed. Install with: sudo apt install sshpass"
    exit 1
fi

# === CREATE TEMPORARY WORKING COPY OF index_noSIG_AIopt.html WITH CACHE-BUSTING ===
CACHE_PARAM=$(date +%s)  # Timestamp als Cache-Buster
TEMP_INDEX=$(mktemp)

# Nur CSS und JS Links in <link> und <script> anpassen
sed -E 's/(href="[^"]+\.css")/\1?v='"$CACHE_PARAM"'/g;
        s/(src="[^"]+\.js")/\1?v='"$CACHE_PARAM"'/g' \
        "$LOCAL_DIR/index_noSIG_AIopt.html" > "$TEMP_INDEX"

# === CREATE TEMPORARY SFTP BATCH FILE ===
BATCH_FILE=$(mktemp)
cat > "$BATCH_FILE" <<EOF
cd $REMOTE_DIR

# Upload modified index.html as index.html
put "$TEMP_INDEX" index.html

# Upload other static files
put "$LOCAL_DIR/impressum.html"
put "$LOCAL_DIR/robots.txt"
put "$LOCAL_DIR/sitemap.xml"
put "$LOCAL_DIR/.htaccess"

# Ensure img folder exists and upload images
mkdir img
cd img
put "$LOCAL_DIR/img/"*

bye
EOF

# === UPLOAD ALL FILES IN ONE SFTP SESSION ===
echo "Uploading website files to $USER@$SERVER:$REMOTE_DIR ..."
sshpass -p "$SFTP_PASS" sftp -oBatchMode=no -b "$BATCH_FILE" $USER@$SERVER

# === CLEANUP ===
rm "$BATCH_FILE" "$TEMP_INDEX"

echo "Deployment complete! Visit your website: http://www.summitwave.eu/?v=$CACHE_PARAM"
