<?php
 if(php_sapi_name() != "cli")
  exit("This script is intended to be run from the CLI\n");

 $RSSURL = "https://abn.lol/Feed/Torrents?CategoryId=2&UserId=5779&TorrentKey=b0r1z49kr45eerxnsawobnwe39g4at3n";
 $CSVFILE = "rss.csv";

 echo "Fetching feed\n";
 $firsttimestart = microtime(true);

 $ch = curl_init($RSSURL);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 curl_setopt($ch, CURLOPT_USERAGENT, "curl/8.5.0"); // an empty user agent gets a 429 from the tracker WAF
 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
 $xml = curl_exec($ch);
 $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
 curl_close($ch);
 if($xml === false || $code != 200)
  exit("Fetch failed (HTTP $code), leaving CSV untouched\n");

 $rss = @simplexml_load_string($xml);
 if($rss === false)
  exit("XML parse failed, leaving CSV untouched\n");

 $exectime = round((microtime(true) - $firsttimestart) * 1000);
 echo "Execution time: $exectime ms\n\n";
 echo "Loading and merging\n";
 $timestart = microtime(true);

 // load the existing CSV into a release-name keyed map, dedup is O(1) on the key
 $data = [];
 if(file_exists($CSVFILE)) {
  $lines = file($CSVFILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  foreach($lines as $line) {
   $parts = explode(";", $line, 2);
   $data[$parts[0]] = isset($parts[1]) ? $parts[1] : "";
  }
 }
 $before = count($data);

 // add every feed item whose release name is not already present
 $added = 0;
 foreach($rss->channel->item as $item) {
  $title = trim((string)$item->title);
  if($title == "")
   continue;
  if(isset($data[$title]))
   continue;
  $data[$title] = trim((string)$item->link);
  $added++;
 }

 echo "Loaded: $before\n";
 echo "Added: $added\n";
 echo "Total: ".count($data)."\n";

 $exectime = round((microtime(true) - $timestart) * 1000);
 echo "Execution time: $exectime ms\n\n";
 echo "Writing CSV\n";
 $timestart = microtime(true);

 // rebuild the whole file and rename in place so a concurrent reader never sees a partial write
 $out = "";
 foreach($data as $title => $link)
  $out .= "$title;$link\n";
 file_put_contents("$CSVFILE.tmp", $out);
 rename("$CSVFILE.tmp", $CSVFILE);

 echo "Output size: ".round(filesize($CSVFILE) / 1000)." KB\n";

 $exectime = round((microtime(true) - $timestart) * 1000);
 echo "Execution time: $exectime ms\n";
 $exectime = round((microtime(true) - $firsttimestart) * 1000);
 echo "Total execution time: $exectime ms\n";
?>
