image: node:18

pipelines:
  branches:
    "main":  # Adjust to your main branch
      - step:
          name: Build and push
          caches:
            - node
          script:
            - echo "Installing dependencies..."
            - npm install
            - echo "Building Next.js application..."
            - npm run build
            - echo "Compressing build files..."
            - tar -czf build.tar.gz .next package.json package-lock.json public
            - echo "Deploying to server..."
            - pipe: atlassian/rsync-deploy:0.6.0
              variables:
                USER: $SSH_USER
                SERVER: $SSH_HOST
                REMOTE_PATH: $BUILD_PATH
                LOCAL_PATH: ${BITBUCKET_CLONE_DIR}
                DEBUG: "true"
      - step:
          name: Install Dependencies and Run App
          script:
            - pipe: atlassian/ssh-run:0.8.1
              variables:
                SSH_USER: $SSH_USER
                SERVER: $SSH_HOST
                COMMAND: |
                  cd $REMOTE_PATH &&
                  echo "Extracting build files..." &&
                  tar -xzf build.tar.gz &&
                  rm build.tar.gz &&
                  echo "Ensuring Node.js is installed..." &&
                  if ! command -v node &> /dev/null; then
                    curl -fsSL https://deb.nodesource.com/setup_18.x | bash - &&
                    apt-get install -y nodejs
                  fi &&
                  echo "Installing dependencies..." &&
                  npm install &&
                  echo "Starting the application..." &&
                  pm2 delete tracking-app || true &&
                  pm2 start npm --name tracking-app -- start &&
                  echo "Checking PM2 status..." &&
                  pm2 list
definitions:
  caches:
    node: ~/.npm
