image: node:20

pipelines:
  branches:
    main:
      - step:
          name: Deploy Node App
          deployment: Development

          script:
            # Install required packages
            - apt-get update && apt-get install -y openssh-client rsync

            # Setup SSH
            - mkdir -p ~/.ssh

            # Decode PEM key
            - echo "$SSH_PRIVATE_KEY_BASE64" | base64 -d > ~/.ssh/id_rsa

            # Correct permissions
            - chmod 700 ~/.ssh
            - chmod 600 ~/.ssh/id_rsa

            # Add server to known hosts
            - ssh-keyscan -H $SERVER_IP >> ~/.ssh/known_hosts

            # Sync files to server
            - |
              rsync -avz \
                --delete \
                --exclude='.git' \
                --exclude='node_modules' \
                --exclude='dist' \
                --exclude='.next' \
                --exclude='bin/www' \
                --exclude='public-assets/uploads/' \
                -e "ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no" \
                ./ $SERVER_USER@$SERVER_IP:/var/www/html/green_rubies_llc/backend/

            # Run deployment script
            - |
              ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no \
              $SERVER_USER@$SERVER_IP '
                cd /var/www/html/green_rubies_llc/backend &&
                bash deploy.sh
              '