#!/bin/sh

if [ "$UPDATE_CODE_FROM_GIT" = "true" ]; then
    apk add git nano rsync
    echo "Updating code from git.d-popov.com...(as '$GIT_USERNAME')"
    rm -rf /tmp/clone
    mkdir /tmp/clone
    
    git clone -b ${GIT_BRANCH:-master}  --depth 1 https://$GIT_USERNAME:${GIT_PASSWORD//@/%40}@git.d-popov.com/popov/next-cart-app.git /tmp/clone || exit 1
    GIT_COMMIT_ID=$(git -C /tmp/clone/next-cart-app rev-parse HEAD)
    LAST_COMMIT_MESSAGE=$(git log -1 --pretty=%B)
    echo "Current Git Commit: $LAST_COMMIT_MESSAGE: $GIT_COMMIT_ID"
    export GIT_COMMIT_ID

    # Use rsync for synchronizing files, ensuring deletion of files not in source
    rsync -av --delete /tmp/clone/next-cart-app/ /app/ || echo "Rsync failed: Issue synchronizing files"
    rsync -av /tmp/clone/next-cart-app/.env* /app/ || echo "Rsync failed: Issue copying .env files"
    rsync -av /tmp/clone/next-cart-app/_deploy/entrypoint.sh /app/entrypoint.sh || echo "Rsync failed: Issue copying entrypoint.sh"
    chmod +x /app/entrypoint.sh
    # Consider uncommenting the next line to clean up after successful copy
    rm -rf /tmp/clone 

    cd /app
    echo "Installing packages in /app"
    npm install --no-audit --no-fund --no-optional --omit=optional
    yes | npx prisma generate
    #npx prisma migrate deploy 
    echo "Done cloning. Current Git Commit ID: $GIT_COMMIT_ID"
    # prod script
    # npx next build
    # npx next start
fi

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