#!/bin/sh
set -e

SERVER_URL="https://fuss.bz.it/utility/fuss-speechtotext/models/whisper-large-v3-turbo"
MODEL_DIR="/opt/fuss-speechtotext/models"
FILES="model.bin config.json vocabulary.json tokenizer.json preprocessor_config.json"

case "$1" in
    configure)
        echo "Configuring FUSS SpeechToText..."
        mkdir -p "$MODEL_DIR"
        cd "$MODEL_DIR"

        echo "Verifying AI model integrity..."
        wget -q "$SERVER_URL/checksums.md5" -O "checksums.md5.new" || true

        for FILE in $FILES; do
            # Check if file exists and matches checksum
            if [ ! -f "$FILE" ] || ! grep -Fw "$FILE" checksums.md5.new | md5sum -c >/dev/null 2>&1; then
                echo "File $FILE missing, incomplete or incorrect. Attempting to fix..."
                
                # Try to resume/download. We allow wget to fail here to handle 416 errors manually
                wget -c "$SERVER_URL/$FILE" -O "$FILE" --show-progress || true
                
                # RE-VERIFY: if it's still wrong, the local file is likely larger than the server file
                # or totally corrupted. We must delete and download from scratch.
                if ! grep -Fw "$FILE" checksums.md5.new | md5sum -c >/dev/null 2>&1; then
                    echo "File $FILE still incorrect after resume. Deleting and downloading fresh..."
                    rm -f "$FILE"
                    wget "$SERVER_URL/$FILE" -O "$FILE" --show-progress
                fi

                # Final verification: if this fails, the installation MUST stop
                if ! grep -Fw "$FILE" checksums.md5.new | md5sum -c >/dev/null 2>&1; then
                    echo "ERROR: Permanent corruption for $FILE. Check server MD5 or network."
                    exit 1
                fi
            else
                echo "✔ $FILE is already present and verified."
            fi
        done
        
        mv -f checksums.md5.new checksums.md5
        chown -R root:root "$MODEL_DIR"
        chmod 644 "$MODEL_DIR"/*
        
        # Standard triggers
        update-desktop-database -q || true
        gtk-update-icon-cache -f -t /usr/share/pixmaps >/dev/null 2>&1 || true
        echo "Installation completed successfully."
    ;;
esac

exit 0
