#!/bin/bash
exec > /var/log/varnish-bootstrap.log 2>&1
set -x

ARCH=$(dpkg --print-architecture)

# SSM (acceso, mismo patron que el resto del proyecto)
if ! dpkg -l amazon-ssm-agent 2>/dev/null | grep -q '^ii'; then
  curl -sSLo /tmp/amazon-ssm-agent.deb "https://s3.eu-central-1.amazonaws.com/amazon-ssm-eu-central-1/latest/debian_${ARCH}/amazon-ssm-agent.deb"
  dpkg -i /tmp/amazon-ssm-agent.deb
  rm -f /tmp/amazon-ssm-agent.deb
fi
systemctl enable amazon-ssm-agent
systemctl start amazon-ssm-agent

# Varnish
apt-get update -y
apt-get install -y varnish unzip

cat > /etc/varnish/default.vcl <<'VCLEOF'
# VCL version 5.0 is not supported so it should be 4.0 even though actually used Varnish version is 6
vcl 4.0;

import std;
import directors;
# The minimal Varnish version is 6.0
# For SSL offloading, pass the following header in your proxy server or load balancer: 'X-Forwarded-Proto: https'

# Backend = NLB interno "hyva-elganso-internal-nlb" (no ALB: un backend Varnish
# solo admite UNA IP, y un ALB resuelve a varias; vmod_dynamic no viene en el
# paquete varnish-modules de Ubuntu). El NLB da una IP privada ESTATICA por
# subred/AZ -- son las 3 de abajo. 2026-11-12, ver
# project_elganso_hyva_fase1_perf_varnish_opensearch.md.
probe backend_probe {
    .url = "/health_check.php";
    .timeout = 2s;
    .interval = 5s;
    .window = 10;
    .threshold = 5;
}

backend nlb_1a {
    .host = "10.50.10.91";
    .port = "80";
    .first_byte_timeout = 600s;
    .probe = backend_probe;
}
backend nlb_1b {
    .host = "10.50.11.49";
    .port = "80";
    .first_byte_timeout = 600s;
    .probe = backend_probe;
}
backend nlb_1c {
    .host = "10.50.12.83";
    .port = "80";
    .first_byte_timeout = 600s;
    .probe = backend_probe;
}

sub vcl_init {
    new web_backend = directors.round_robin();
    web_backend.add_backend(nlb_1a);
    web_backend.add_backend(nlb_1b);
    web_backend.add_backend(nlb_1c);
}

# Esta Varnish ya no es local al nodo que la purga (capa compartida delante
# del ALB interno) -- las purgas vienen por red desde cualquier nodo de la
# VPC (web o admin), no desde localhost. 2026-11-12, ver
# project_elganso_hyva_fase1_perf_varnish_opensearch.md.
acl purge {
    "10.50.0.0"/16;
}

sub vcl_recv {
    set req.backend_hint = web_backend.backend();

    if (req.restarts > 0) {
        set req.hash_always_miss = true;
    }

    if (req.method == "PURGE") {
        if (client.ip !~ purge) {
            return (synth(405, "Method not allowed"));
        }
        if (!req.http.X-Magento-Tags-Pattern && !req.http.X-Pool) {
            return (synth(400, "X-Magento-Tags-Pattern or X-Pool header required"));
        }
        if (req.http.X-Magento-Tags-Pattern) {
          ban("obj.http.X-Magento-Tags ~ " + req.http.X-Magento-Tags-Pattern);
        }
        if (req.http.X-Pool) {
          ban("obj.http.X-Pool ~ " + req.http.X-Pool);
        }
        return (synth(200, "Purged"));
    }

    if (req.method != "GET" &&
        req.method != "HEAD" &&
        req.method != "PUT" &&
        req.method != "POST" &&
        req.method != "TRACE" &&
        req.method != "OPTIONS" &&
        req.method != "DELETE") {
          return (pipe);
    }

    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    if (req.url ~ "/customer" || req.url ~ "/checkout") {
        return (pass);
    }

    if (req.url ~ "^/(pub/)?(health_check.php)$") {
        return (pass);
    }

    set req.http.grace = "none";

    set req.url = regsub(req.url, "^http[s]?://", "");

    std.collect(req.http.Cookie);

    if (req.url ~ "(\?|&)(gad_source|gbraid|wbraid|_gl|dclid|gclsrc|srsltid|msclkid|gclid|cx|_kx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=") {
        set req.url = regsuball(req.url, "(gad_source|gbraid|wbraid|_gl|dclid|gclsrc|srsltid|msclkid|gclid|cx|_kx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=[-_A-z0-9+()%.]+&?", "");
        set req.url = regsub(req.url, "[?|&]+$", "");
    }

    if (req.url ~ "^/(pub/)?(media|static)/") {
        return (pass);
    }

    if (req.url ~ "/graphql" && !req.http.X-Magento-Cache-Id && req.http.Authorization ~ "^Bearer") {
        return (pass);
    }

    return (hash);
}

sub vcl_hash {
    if ((req.url !~ "/graphql" || !req.http.X-Magento-Cache-Id) && req.http.cookie ~ "X-Magento-Vary=") {
        hash_data(regsub(req.http.cookie, "^.*?X-Magento-Vary=([^;]+);*.*$", "\1"));
    }

    if (req.http.X-Forwarded-Proto) {
        hash_data(req.http.X-Forwarded-Proto);
    }
    if (req.http.user-agent ~ "(?i)iPhone|iPod|BlackBerry|Palm|Googlebot-Mobile|Mobile|mobile|mobi|Windows Mobile|Safari Mobile|Android|Opera Mini") {
        hash_data("9");
    } elsif (req.http.user-agent ~ "(?i)app-elganso") {
        hash_data("9");
    } elsif (req.http.user-agent ~ "(?i)app-pwa") {
        hash_data("9");
    }

    if (req.url ~ "/graphql") {
        call process_graphql_headers;
    }
}

sub process_graphql_headers {
    if (req.http.X-Magento-Cache-Id) {
        hash_data(req.http.X-Magento-Cache-Id);
        if (req.http.Authorization ~ "^Bearer") {
            hash_data("Authorized");
        }
    }

    if (req.http.Store) {
        hash_data(req.http.Store);
    }

    if (req.http.Content-Currency) {
        hash_data(req.http.Content-Currency);
    }
}

sub vcl_backend_response {

    set beresp.grace = 3d;

    if (beresp.http.content-type ~ "text") {
        set beresp.do_esi = true;
    }

    if (bereq.url ~ "\.js$" || beresp.http.content-type ~ "text") {
        set beresp.do_gzip = true;
    }

    if (beresp.http.X-Magento-Debug) {
        set beresp.http.X-Magento-Cache-Control = beresp.http.Cache-Control;
    }

    if ((beresp.status != 200 && beresp.status != 404) || beresp.http.Cache-Control ~ "private") {
        set beresp.uncacheable = true;
        set beresp.ttl = 86400s;
        return (deliver);
    }

    if (beresp.ttl > 0s && (bereq.method == "GET" || bereq.method == "HEAD")) {
        std.collect(beresp.http.set-cookie);
        if ((bereq.url !~ "/graphql" || !bereq.http.X-Magento-Cache-Id)
         && bereq.http.cookie !~ "X-Magento-Vary="
         && beresp.http.set-cookie ~ "X-Magento-Vary=") {
           set beresp.ttl = 0s;
           set beresp.uncacheable = true;
        }
        unset beresp.http.set-cookie;
    }

    if (beresp.ttl <= 0s ||
        beresp.http.Surrogate-control ~ "no-store" ||
        (!beresp.http.Surrogate-Control &&
        beresp.http.Cache-Control ~ "no-cache|no-store") ||
        beresp.http.Vary == "*") {
        set beresp.ttl = 120s;
        set beresp.uncacheable = true;
    }

    if (bereq.url ~ "/graphql" && bereq.http.X-Magento-Cache-Id && bereq.http.X-Magento-Cache-Id != beresp.http.X-Magento-Cache-Id) {
        set beresp.ttl = 0s;
        set beresp.uncacheable = true;
    }

    return (deliver);
}

sub vcl_deliver {
    if (obj.uncacheable) {
        set resp.http.X-Magento-Cache-Debug = "UNCACHEABLE";
    } else if (obj.hits) {
        set resp.http.X-Magento-Cache-Debug = "HIT";
        set resp.http.Grace = req.http.grace;
    } else {
        set resp.http.X-Magento-Cache-Debug = "MISS";
    }

    if (resp.http.Cache-Control !~ "private" && req.url !~ "^/(pub/)?(media|static)/") {
        set resp.http.Pragma = "no-cache";
        set resp.http.Expires = "-1";
        set resp.http.Cache-Control = "no-store, no-cache, must-revalidate, max-age=0";
    }

    if (!resp.http.X-Magento-Debug) {
        unset resp.http.Age;
    }
    unset resp.http.X-Magento-Debug;
    unset resp.http.X-Magento-Tags;
    unset resp.http.X-Powered-By;
    unset resp.http.Server;
    unset resp.http.X-Varnish;
    unset resp.http.Via;
    unset resp.http.Link;
}

sub vcl_hit {
    if (obj.ttl >= 0s) {
        return (deliver);
    }
    if (std.healthy(req.backend_hint)) {
        if (obj.ttl + 300s > 0s) {
            set req.http.grace = "normal (healthy server)";
            return (deliver);
        } else {
            return (restart);
        }
    } else {
        set req.http.grace = "unlimited (unhealthy server)";
        return (deliver);
    }
}
VCLEOF

mkdir -p /etc/systemd/system/varnish.service.d
cat > /etc/systemd/system/varnish.service.d/override.conf <<'OVERRIDE'
[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,1024m -p http_resp_hdr_len=65536 -p http_resp_size=98304 -p http_max_hdr=256 -p workspace_backend=256k -p http_req_hdr_len=16384 -p workspace_client=64k
OVERRIDE

systemctl daemon-reload
systemctl enable varnish
systemctl restart varnish

# AWS CLI v2 (necesario para el push de metricas de varnishstat)
curl -sSL "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o /tmp/awscliv2.zip
cd /tmp && unzip -q -o awscliv2.zip && /tmp/aws/install
rm -rf /tmp/awscliv2.zip /tmp/aws

# CloudWatch Agent (CPU/mem/disco/proceso, mismo namespace HyvaElGanso que el resto)
curl -sSLo /tmp/amazon-cloudwatch-agent.deb "https://amazoncloudwatch-agent.s3.amazonaws.com/debian/${ARCH}/latest/amazon-cloudwatch-agent.deb"
dpkg -i /tmp/amazon-cloudwatch-agent.deb
rm -f /tmp/amazon-cloudwatch-agent.deb

mkdir -p /opt/aws/amazon-cloudwatch-agent/etc
cat > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json <<'CWCONFIG'
{
  "agent": { "metrics_collection_interval": 60, "run_as_user": "root" },
  "metrics": {
    "namespace": "HyvaElGanso",
    "append_dimensions": { "InstanceId": "${aws:InstanceId}" },
    "metrics_collected": {
      "cpu": { "measurement": ["cpu_usage_idle", "cpu_usage_user", "cpu_usage_system"], "totalcpu": true },
      "mem": { "measurement": ["mem_used_percent"] },
      "disk": { "measurement": ["used_percent"], "resources": ["/"] },
      "procstat": [
        { "pattern": "varnishd", "measurement": ["pid_count"] }
      ]
    }
  }
}
CWCONFIG
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json

# Metricas propias de Varnish (hit ratio) -> CloudWatch, cron cada minuto
mkdir -p /opt/hyva-elganso/bin
cat > /opt/hyva-elganso/bin/varnish_stats_to_cw.py <<'PYEOF'
#!/usr/bin/env python3
"""
Empuja metricas propias de Varnish (hit ratio, hits, misses, requests) a
CloudWatch cada minuto, namespace HyvaElGanso, mismo patron que el resto de
metricas del proyecto. varnishstat da contadores ACUMULADOS desde que arranco
el proceso -- este script guarda el ultimo valor visto y calcula el delta del
intervalo, asi el ratio refleja lo que ha pasado en el ULTIMO minuto, no la
media de toda la vida del proceso (que se iria aplanando con el tiempo).
"""
import json
import subprocess
import sys

STATE_PATH = "/var/lib/varnish-metrics/state.json"
REGION = "eu-central-1"
NAMESPACE = "HyvaElGanso"
AWS_BIN = "/usr/local/bin/aws"


def leer_contadores():
    out = subprocess.check_output(["varnishstat", "-1", "-j"])
    data = json.loads(out)
    c = data["counters"]
    return {
        "hit": c["MAIN.cache_hit"]["value"],
        "miss": c["MAIN.cache_miss"]["value"],
        "hitpass": c["MAIN.cache_hitpass"]["value"],
        "hitmiss": c["MAIN.cache_hitmiss"]["value"],
        "req": c["MAIN.client_req"]["value"],
    }


def leer_estado_previo():
    try:
        with open(STATE_PATH) as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return None


def guardar_estado(actual):
    import os
    os.makedirs("/var/lib/varnish-metrics", exist_ok=True)
    with open(STATE_PATH, "w") as f:
        json.dump(actual, f)


def token_imds():
    return subprocess.check_output([
        "curl", "-sX", "PUT", "http://169.254.169.254/latest/api/token",
        "-H", "X-aws-ec2-metadata-token-ttl-seconds: 60",
    ]).decode().strip()


def put_metric(instance_id, name, value, unit="Count"):
    subprocess.run([
        AWS_BIN, "cloudwatch", "put-metric-data",
        "--region", REGION,
        "--namespace", NAMESPACE,
        "--metric-name", name,
        "--dimensions", f"InstanceId={instance_id}",
        "--value", str(value),
        "--unit", unit,
    ], check=True)


def main():
    actual = leer_contadores()
    previo = leer_estado_previo()
    guardar_estado(actual)

    if previo is None:
        print("Primer arranque, sin estado previo, no se publica nada.")
        return 0

    d_hit = actual["hit"] - previo["hit"]
    d_miss = actual["miss"] - previo["miss"]
    d_hitpass = actual["hitpass"] - previo["hitpass"]
    d_hitmiss = actual["hitmiss"] - previo["hitmiss"]
    d_req = actual["req"] - previo["req"]

    if d_hit < 0 or d_miss < 0 or d_req < 0:
        print("Contadores reiniciados (reinicio de Varnish), se omite este intervalo.")
        return 0

    denom = d_hit + d_miss + d_hitpass + d_hitmiss
    ratio = round(100.0 * d_hit / denom, 2) if denom > 0 else 0.0

    instance_id = subprocess.check_output(
        ["curl", "-s", "-H", "X-aws-ec2-metadata-token: " + token_imds(),
         "http://169.254.169.254/latest/meta-data/instance-id"]
    ).decode().strip()

    put_metric(instance_id, "VarnishCacheHit", d_hit)
    put_metric(instance_id, "VarnishCacheMiss", d_miss)
    put_metric(instance_id, "VarnishClientReq", d_req)
    put_metric(instance_id, "VarnishHitRatioPct", ratio, unit="Percent")

    print(f"hit={d_hit} miss={d_miss} req={d_req} ratio={ratio}%")
    return 0


if __name__ == "__main__":
    sys.exit(main())
PYEOF
chmod 755 /opt/hyva-elganso/bin/varnish_stats_to_cw.py

(crontab -l 2>/dev/null; echo '* * * * * /usr/bin/python3 /opt/hyva-elganso/bin/varnish_stats_to_cw.py >> /var/log/varnish-stats-cw.log 2>&1') | crontab -

echo "VARNISH_BOOTSTRAP_DONE"
