pipeline {
    agent any

    triggers {
        // Runs at midnight on the 1st and 16th of every month ≈ every 15 days
        cron('0 0 1,16 * *')
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '10'))
        timestamps()
        timeout(time: 15, unit: 'MINUTES')
    }

    environment {
        TARGET_DIR = '/var/lib/jenkins/workspace/'
    }

    stages {

        stage('Preview Files to Delete') {
            steps {
                echo "🔍 Scanning for .png and .mp4 files in: ${TARGET_DIR}"
                sh '''
                    echo "---------------------------------------------------"
                    echo "Files found:"
                    find "$TARGET_DIR" -type f \\( -name "*.png" -o -name "*.mp4" \\) | while read -r file; do
                        echo "  [FOUND] $file"
                    done
                    echo "---------------------------------------------------"
                    TOTAL=$(find "$TARGET_DIR" -type f \\( -name "*.png" -o -name "*.mp4" \\) | wc -l)
                    echo "Total files to be deleted: $TOTAL"
                '''
            }
        }

        stage('Delete PNG and MP4 Files') {
            steps {
                echo "🗑️ Deleting .png and .mp4 files..."
                sh '''
                    find "$TARGET_DIR" -type f \\( -name "*.png" -o -name "*.mp4" \\) -delete
                    echo "✅ Deletion complete."
                '''
            }
        }

        stage('Verify Cleanup') {
            steps {
                echo "🔎 Verifying cleanup..."
                sh '''
                    REMAINING=$(find "$TARGET_DIR" -type f \\( -name "*.png" -o -name "*.mp4" \\) | wc -l)
                    echo "Remaining .png / .mp4 files: $REMAINING"
                    if [ "$REMAINING" -eq 0 ]; then
                        echo "✅ Workspace is clean. No media files remaining."
                    else
                        echo "⚠️ Warning: $REMAINING file(s) could not be deleted."
                        exit 1
                    fi
                '''
            }
        }
    }

    post {
        success {
            sh 'echo "🎉 Cleanup job completed successfully on $(date)."'
        }
        failure {
            echo "❌ Cleanup job failed. Please check the logs above."
        }
        always {
            echo "📋 Job: ${env.JOB_NAME} | Build: #${env.BUILD_NUMBER} | Status: ${currentBuild.currentResult}"
        }
    }
}