#!/usr/local/bin/php
<?php

define("BOT","1698987817:AAEp3Lk5EK4iXKJuVZiiW5IeFvuRs1QHl9E");

# Busco los hosts disponibles
exec("ls /usr/local/etc/letsencrypt/live/", $live);
$hosts = array_values(array_filter($live, function($e){
  return strpos($e, ".com") !== false;
}));

# Busco las fechas de expiracion de los cert
$cert = [];
foreach($hosts as $h){
  exec("openssl s_client -connect $h:443 -servername $h < /dev/null | openssl x509 -noout -enddate", $ret);
  $cert[] = ["host" => $h, "exp" => array_pop($ret)];
}

$cert = array_filter($cert, function($e){
  return !empty($e['exp']);
});

# Convertir a objetos DateTime
$datetimes = array_map(function($line) {
  # Extraer la fecha eliminando "notAfter="
  $dateString = str_replace("notAfter=", "", $line['exp']);
  # Crear un objeto DateTime
  return DateTime::createFromFormat("M d H:i:s Y T", $dateString);
}, $cert);

$datetimes = array_filter($datetimes, function($e){
  return is_object($e);
});

# Determino que hosts renovar
foreach($datetimes as $i => $d){
  $cert[$i]['exp'] = $d;
  $now = new DateTime();
  $interval = $now -> diff($cert[$i]['exp']);
  $cert[$i]['dias'] = $interval->days;
  if($cert[$i]['dias'] < 10){
    $renovar[] = $cert[$i];
  }
}

if(empty($renovar)){
#  telegram("msg", "✅✅🔄 No hay hosts que renovar hoy\n🖧Instancia: TEST", "-487527567");
  exit();
}

# Mando alerta telegram
$msg = "🖥️🔄 Hosts que se renovaran hoy\n🖧Instancia: TEST\n\n";
foreach($renovar as $r){
  $msg .= $r['host'].": ".$r['dias']." ".($r['dias'] == 1 ? "dia restante" : "dias restantes")."\n";
}

telegram("msg", $msg, "-487527567");

# Renuevo los hosts
echo "APAGANDO APACHE\n";
exec("apachectl stop");
sleep(5);

echo "RENOVANDO HOSTS\n";
foreach($renovar as $r){
  exec("certbot certonly -c /usr/local/etc/letsencrypt/letsencrypt.ini -d ".$r['host']);
}

echo "ENCENDIENDO APACHE\n";
exec("apachectl start");


function telegram($tipo,$msg,$chat = "-583367312") {
  # -487527567 GRUPO IT
  # -669140484 TEMAS SISTEMAS
  # -583367312 EMRO ALERTAS
  # 1487387714 Alejandro Sistemas
  # 1880818174 Alejandro Gomez
  #Enviador de mensajes
  if($tipo == "msg"){
    $ret = @file_get_contents("https://api.telegram.org/bot".BOT."/sendMessage",false,stream_context_create(
      array(
        'http'=>array(
          'method'=>'POST',
          'header'=>"Content-Type:application/x-www-form-urlencoded\r\n",
          'content'=>http_build_query(
            array(
              'chat_id'=>$chat,
              'text'=>$msg
            )
          )
        )
      )
    ));
    return (strpos($ret,"\"ok\":true,") === false ? false : true);
  }

  #Enviador de adjuntos
  if($tipo == "file"){
    exec("curl -v -F \"chat_id=$chat\" -F document=@$msg https://api.telegram.org/bot".BOT."/sendDocument 2>&1",$ret);
    return (!is_array($ret) || strpos(implode("\n",$ret),"\"ok\":true,") === false ? false : true);
  }
}









#openssl s_client -connect <hostname>:443 -servername <hostname> </dev/null 2>/dev/null | openssl x509 -noout -enddate
