#!/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'). Branch: ${GIT_BRANCH:main}"  > /app/logs/deploy.txt

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

    # Clear previous log
    echo "Starting sync process at $(date)" > /app/logs/deploy.txt
    # Clone the repository
    echo "\r\n\r\n Cloning repository..." | tee -a 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 /tmp/clone/_deploy/entrypoint.sh /app/entrypoint.sh || echo "Rsync failed: Issue copying entrypoint.sh"
    


    # rsync -av --update --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


    ########################################################################################
    # Backup permits folder if it exists
    mkdir -p /tmp/content
    if [ -d "/app/public/content/permits" ]; then
        echo "Backing up server permits folder..." | tee -a /app/logs/deploy.txt
        cp -r /app/public/content/permits /tmp/content/
        echo "Server permits folder backed up successfully." | tee -a /app/logs/deploy.txt
        ls -la /tmp/content/permits >> /app/logs/deploy.txt 2>&1
    else
        echo "Server permits folder not found, will create it after deployment." | tee -a /app/logs/deploy.txt
        mkdir -p /tmp/content/permits
    fi

    # Run rsync with verbose output and itemize-changes, excluding the permits folder
    echo "Running rsync for main codebase..." | tee -a /app/logs/deploy.txt
    rsync -av --itemize-changes \
        --exclude='package.json' \
        --exclude='package-lock.json' \
        --exclude='/public/content/permits' \
        --exclude='/public/content/uploads' \
        /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

    # Check if the Git project contains a permits folder
    if [ -d "/tmp/clone/public/content/permits" ] && [ "$(ls -A /tmp/clone/public/content/permits)" ]; then
        echo "Found permits files in Git project, preparing to merge..." | tee -a /app/logs/deploy.txt
        # Create a temporary directory for Git project permits files
        mkdir -p /tmp/git_permits
        cp -r /tmp/clone/public/content/permits/* /tmp/git_permits/ 2>/dev/null || true
        ls -la /tmp/git_permits >> /app/logs/deploy.txt 2>&1
    else
        echo "No permits files found in Git project." | tee -a /app/logs/deploy.txt
    fi

    # Restore/merge permits folder
    echo "Restoring and merging permits folders..." | tee -a /app/logs/deploy.txt
    # Ensure the destination directory exists
    mkdir -p /app/public/content/permits
    
    # First restore the server permits
    if [ -d "/tmp/content/permits" ]; then
        cp -r /tmp/content/permits/* /app/public/content/permits/ 2>/dev/null || true
        echo "Server permits restored." | tee -a /app/logs/deploy.txt
    fi
    
    # Then merge in the Git project permits (will overwrite if same filename)
    if [ -d "/tmp/git_permits" ] && [ "$(ls -A /tmp/git_permits)" ]; then
        cp -r /tmp/git_permits/* /app/public/content/permits/ 2>/dev/null || true
        echo "Git project permits merged." | tee -a /app/logs/deploy.txt
    fi

    # Check contents after restoration and merge
    echo "Contents of merged permits folder:" >> /app/logs/deploy.txt
    ls -la /app/public/content/permits >> /app/logs/deploy.txt 2>&1
    ########################################################################################


    echo "\r\n\r\n Fixing problematic npm packages..." | tee -a /app/logs/deploy.txt
    cd /app
    
    # Remove problematic node_modules if they exist
    if [ -d "node_modules/abbrev" ]; then
        echo "Removing problematic abbrev package..." | tee -a /app/logs/deploy.txt
        rm -rf node_modules/abbrev
    fi
    
    if [ -d "node_modules/bcrypt" ]; then
        echo "Removing problematic bcrypt package..." | tee -a /app/logs/deploy.txt
        rm -rf node_modules/bcrypt
    fi
    
    # Ensure clean node_modules state
    if [ -d "node_modules" ]; then
        echo "Cleaning up node_modules..." | tee -a /app/logs/deploy.txt
        find node_modules -type d -name "node_modules" -not -path "node_modules" -exec rm -rf {} + 2>/dev/null || true
        find node_modules -name "*.node" -type f -delete 2>/dev/null || true
    fi
    
    # Install problematic packages individually
    echo "Installing abbrev package separately..." | tee -a /app/logs/deploy.txt
    npm install abbrev@latest --no-save --no-audit --no-fund || echo "Failed to install abbrev, continuing anyway"
    
    echo "Installing bcrypt package separately with build from source..." | tee -a /app/logs/deploy.txt
    npm install bcrypt@latest --build-from-source --no-save --no-audit --no-fund || echo "Failed to install bcrypt, continuing anyway"

    # Fix Prisma-specific issues
    echo "Fixing Prisma-specific dependencies..." | tee -a /app/logs/deploy.txt
    
    # Remove problematic Prisma nested dependencies
    if [ -d "node_modules/@prisma" ]; then
        echo "Cleaning up Prisma dependencies..." | tee -a /app/logs/deploy.txt
        rm -rf node_modules/@prisma/internals/node_modules/@prisma/engines
        rm -rf node_modules/@prisma/internals/node_modules/@prisma/engines-version
        rm -rf node_modules/@prisma/client/node_modules/@prisma/engines-version
        rm -rf node_modules/.prisma
    fi
    
    # Install specific Prisma versions known to work
    echo "Installing specific Prisma versions..." | tee -a /app/logs/deploy.txt
    npm uninstall prisma @prisma/client --no-save || true
    npm install prisma@5.12.0 @prisma/client@5.12.0 --save-exact --no-audit --no-fund || echo "Failed to install Prisma, continuing anyway"
    
    # Ensure Prisma engines are downloaded
    echo "Generating Prisma client..." | tee -a /app/logs/deploy.txt
    npx prisma generate --schema=./prisma/schema.prisma || echo "Failed to generate Prisma client, continuing anyway"

    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..." | tee -a /app/logs/deploy.txt
        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"
        
        echo "Cleaning node_modules directory..." | tee -a /app/logs/deploy.txt
        rm -rf /app/node_modules
        
        # Clean npm cache
        echo "Cleaning npm cache..." | tee -a /app/logs/deploy.txt
        npm cache clean --force
        
        echo "Installing dependencies with safer options..." | tee -a /app/logs/deploy.txt
        # Try different installation strategies in case of failure
        npm install --production --no-optional --legacy-peer-deps || \
        npm install --production --no-optional --force || \
        npm install --production --no-optional --no-package-lock || \
        echo "WARNING: All npm install attempts failed, continuing with deployment" | tee -a /app/logs/deploy.txt
        
        # Generate Prisma client
        echo "Generating Prisma client..." | tee -a /app/logs/deploy.txt
        npx prisma generate || echo "WARNING: Prisma generate failed" | tee -a /app/logs/deploy.txt
    else
        echo "Package files have not changed. Skipping package installation." | tee -a /app/logs/deploy.txt
    fi

    cd /app
    
    # Build the Next.js application
    echo "Building Next.js application..." | tee -a /app/logs/deploy.txt
    npx next build || echo "WARNING: Next.js build failed" | tee -a /app/logs/deploy.txt

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



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