#!/bin/sh

if [ "$UPDATE_CODE_FROM_GIT" = "true" ]; then
    # Install necessary packages
    apk add git nano rsync
    echo "Updating code from git.d-popov.com...(as '$GIT_USERNAME')"

    # Create a temporary directory for the new clone
    rm -rf /tmp/clone
    mkdir /tmp/clone
    mkdir -p /app/logs

    # Clone the repository
    echo "\r\n\r\n Cloning repository..." | tee -a /app/logs/deploy.txt
    git clone -b ${GIT_BRANCH:-main} --depth 1 https://$GIT_USERNAME:${GIT_PASSWORD//@/%40}@git.d-popov.com/popov/mwitnessing.git /tmp/clone || exit 1

    # Synchronize all files except package.json, package-lock.json, and the contents of /public/content
    # rsync -av --filter='P /public/content/' --exclude 'package.json' --exclude 'package-lock.json' /tmp/clone/ /app/ || echo "Rsync failed: Issue synchronizing files"
    echo "\r\n\r\n Synchronizing files..."
    # rsync -av --exclude '/public/content' --exclude 'package.json' --exclude 'package-lock.json' /tmp/clone/ /app/ || echo "Rsync failed: Issue synchronizing files" | tee -a /app/logs/deploy.txt

    # Clear previous log
    echo "Starting sync process at $(date)" > /app/logs/deploy.txt

    # Run rsync with verbose output and itemize-changes
    rsync -av --itemize-changes --exclude 'public/content' --exclude 'package.json' --exclude 'package-lock.json' /tmp/clone/ /app/ >> /app/logs/deploy.txt 2>&1

    # Check rsync exit status
    if [ $? -ne 0 ]; then
        echo "Rsync failed: Issue synchronizing files" | tee -a /app/logs/deploy.txt
        cat /app/logs/deploy.txt  # Display the log contents
    else
        echo "Rsync completed successfully" | tee -a /app/logs/deploy.txt
        echo "Last few lines of rsync log:" | tee -a /app/logs/deploy.txt
        tail -n 20 /app/logs/deploy.txt  # Display the last 20 lines of the log
    fi



    echo "\r\n\r\n Checking for changes in package files..."
    # Determine if package.json or package-lock.json has changed
    PACKAGE_CHANGE=0
    if ! cmp -s /tmp/clone/package.json /app/package.json || ! cmp -s /tmp/clone/package-lock.json /app/package-lock.json; then
        PACKAGE_CHANGE=1
    fi

    # If package.json or package-lock.json has changed, copy them and reinstall node_modules
    if [ "$PACKAGE_CHANGE" -eq 1 ]; then
        echo "Package files have changed. Updating packages..."
        rsync -av /tmp/clone/package.json /app/package.json || echo "Rsync failed: Issue copying package.json"
        rsync -av /tmp/clone/package-lock.json /app/package-lock.json || echo "Rsync failed: Issue copying package-lock.json"
        rm -rf /app/node_modules
        yes | npx prisma generate
    else
        echo "Package files have not changed. Skipping package installation."
    fi

    cd /app
    npm install --no-audit --no-fund --no-optional --omit=optional
    npx next build 

    # Clean up
    rm -rf /tmp/clone
    echo "Update process completed."
fi



echo "Running the main process"
exec "$@"
