#!/bin/bash

CACHE_FILE=".build-cache"

needs_build() {
    # If cache file doesn't exist, require build
    if [ ! -f "$CACHE_FILE" ]; then
        echo "Build required: first run"
        return 0
    fi

    # Get all changed files from git
    changed_files=$(git status --porcelain | awk '{print $NF}')

    if [ -z "$changed_files" ]; then
        return 1
    fi

    # Check if any changed file is a build source file and newer than cache
    while IFS= read -r file; do
        if [[ "$file" =~ \.(js|vue|less|css)$ ]] && [ -f "$file" ] && [ "$file" -nt "$CACHE_FILE" ]; then
            echo "Build required: $file changed"
            return 0
        fi
    done <<< "$changed_files"

    return 1
}

upload() {
    if needs_build; then
        echo "Running build..."
        if npm run build; then
            # Update cache file timestamp
            touch "$CACHE_FILE"
            sh local-remote.sh
        else
            echo "Build failed, skipping upload"
            exit 1
        fi
    else
        echo "No build required - uploading directly..."
        sh local-remote.sh
    fi
}

if [ "$1" = "--upload" ]; then
	if [ -f $REMOTE_PROGRESS ]; then
		echo "Waiting for remote-local.sh to finish..."
		exit 0
	fi

    upload
    exit 0
fi

sh "remote-local.sh"

watchexec --debounce 1s -w . 'sh watch-build.sh --upload'
