<?php
/**
 * Serve /apple-touch-icon*.png from the site icon.
 *
 * iOS asks for these at the site root when a page is added to the home screen,
 * and it does so whether or not the page carries an <link rel="apple-touch-icon">
 * tag — the root probe is a fallback baked into Safari. WordPress only ever
 * emits the tag, so the probes 404. They were the largest source of genuine
 * (non-scanner) 404s in the log: roughly 1,350 hits across four filenames.
 *
 * Handled here rather than by dropping PNGs at the web root because only
 * wp-content is bind-mounted on this host — anything written beside index.php
 * lives in the container's own filesystem and disappears the next time the
 * container is recreated, which is exactly how wp-cli went missing.
 *
 * Runs on `init` so it costs a string comparison rather than a full query.
 *
 * @package Kadence-Child
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

add_action(
	'init',
	function () {
		if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) {
			return;
		}
		$path = isset( $_SERVER['REQUEST_URI'] ) ? wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
		if ( ! $path || 0 !== strpos( $path, '/apple-touch-icon' ) ) {
			return;
		}
		// /apple-touch-icon.png, -precomposed.png, and the -120x120 variants.
		if ( ! preg_match( '#^/apple-touch-icon(?:-(\d+)x\d+)?(?:-precomposed)?\.png$#', $path, $m ) ) {
			return;
		}

		// 180 is what current iOS actually renders; the sizes in the filename are
		// only what the device happened to ask for.
		$size = isset( $m[1] ) && $m[1] ? min( 512, max( 57, (int) $m[1] ) ) : 180;
		$url  = get_site_icon_url( $size );
		if ( ! $url ) {
			return; // No site icon set — let it 404 rather than invent one.
		}

		wp_redirect( $url, 301 );
		exit;
	},
	1
);
