#!/bin/sh
set -e

# Configuration
# Note: Ensure the URL does not end with a trailing slash to avoid // in downloads
SERVER_URL="https://fuss.bz.it/utility/fuss-speechtotext/models/whisper-large-v3-turbo"
MODEL_DIR="/opt/fuss-speechtotext/models"
# List of required model files
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..."
        # Always fetch the latest checksum file from the server
        wget -q "$SERVER_URL/checksums.md5" -O "checksums.md5.new" || true

        for FILE in $FILES; do
            # Check if file exists and verify its MD5 hash
            # -Fw ensures exact filename matching (e.g., config.json vs preprocessor_config.json)
            if [ ! -f "$FILE" ] || ! grep -Fw "$FILE" checksums.md5.new | md5sum -c >/dev/null 2>&1; then
                echo "File $FILE missing or incomplete. Starting download..."                
                # -c allows resuming partial downloads
                wget -c "$SERVER_URL/$FILE" -O "$FILE" --show-progress
                
                # Immediate post-download verification
                if ! grep -Fw "$FILE" checksums.md5.new | md5sum -c >/dev/null 2>&1; then
                    echo "ERROR: Downloaded file $FILE is corrupt. Please try reinstalling."
                    exit 1
                fi
            else
                echo "✔ $FILE is already present and verified."
            fi
        done
        
        # Replace old checksum file with the verified one
        mv -f checksums.md5.new checksums.md5
        
        # Set system permissions (Root ownership and read-only for users)
        echo "Setting permissions..."
        chown -R root:root "$MODEL_DIR"
        chmod 644 "$MODEL_DIR"/*
        
        # Update system desktop and icon databases
        if command -v update-desktop-database >/dev/null 2>&1; then
            update-desktop-database -q
        fi
        if command -v gtk-update-icon-cache >/dev/null 2>&1; then
            gtk-update-icon-cache -f -t /usr/share/pixmaps >/dev/null 2>&1 || true
        fi
        
        echo "FUSS SpeechToText installation completed successfully."
    ;;
esac

exit 0
