<?php

$destination = "/home/tfe/Nextcloud/Musika/Badok";
if(!is_dir($destination))
{
    mkdir($destination, 0755, true);
}

$url = "https://www.badok.eus/azken-kantuak";

$content = file_get_contents($url);
preg_match_all("/<a.*?data-mp3=\"mp3\".*?><\/a>/", $content, $matches);
foreach($matches[0] as $link)
{
    $tid = preg_replace("/.*data-tid=\"(.*?)\".*/", "$1", $link);

    $image = preg_replace("/.*data-uimg=\"(.*?)\".*/", "$1", $link);
    trim($image);

    $artist = preg_replace("/.*data-artist=\"(.*?)\".*/", "$1", $link);
    trim($artist);
    $artist = preg_replace("/[^a-zA-Z0-9]/", "_", $artist);

    $album = "";
    $izena = preg_replace("/.*data-izena=\"(.*?)\".*/", "$1", $link);
    trim($izena);
    $izena = preg_replace("/[^a-zA-Z0-9]/", "_", $izena);
    if(preg_match("/(.*) - (.*)/", $izena, $matches))
    {
        $album = $matches[1];
        $izena = $matches[2];
    }

    $artist_folder = "$destination/$artist";
    if(!is_dir($artist_folder))
    {
        mkdir($artist_folder, 0755, true);
    }

    $destination_file = "$destination/$artist/$album/$izena.mp3";
    if(!file_exists($destination_file))
    {
        $destination_image = "$destination/$artist/$album/$izena.jpg";
        file_put_contents($destination_image, file_get_contents($image));

        echo "[$artist] $izena ($tid)\n";
        $dl_url = json_decode(file_get_contents("https://www.badok.eus/wp-content/plugins/badok/server_processing.php?play_mp3=" . $tid),true);
        echo "Deskargatzen [$artist] $izena ($tid) - $destination_file\n";
        file_put_contents($destination_file, file_get_contents($dl_url["url"]));
        echo "OK\n";

        exec("eyeD3 --artist \"$artist\" --album \"$album\" --title \"$izena\" --add-image $destination_image:FRONT_COVER $destination_file");
    }
    else {
        echo "[$artist] $izena ($tid) Dagoeneko egina dago.\n";
    }
}


