<?php

echo "Downloading...\n";
file_put_contents(__DIR__ . "/GeoLite2-City.tar.gz", file_get_contents("https://dl.netsyms.net/dbs/geolite2/GeoLite2-City.tar.gz"));

echo "Extracting...\n";
// decompress from gz
$p = new PharData(__DIR__ . "/GeoLite2-City.tar.gz");
$p->decompress();

// unarchive from the tar
$phar = new PharData(__DIR__ . "/GeoLite2-City.tar");
mkdir(__DIR__ . "/tmp");
$phar->extractTo(__DIR__ . "/tmp");

echo "Installing...\n";
$files = glob(__DIR__ . "/tmp/GeoLite2-City_*/GeoLite2-City.mmdb");
if (count($files) == 1) {
    rename($files[0], __DIR__ . "/GeoLite2-City.mmdb");
}

echo "Cleaning up...\n";
unlink(__DIR__ . "/GeoLite2-City.tar.gz");
unlink(__DIR__ . "/GeoLite2-City.tar");
$dir = __DIR__ . "/tmp";
$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it,
             RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
    if ($file->isDir()){
        rmdir($file->getRealPath());
    } else {
        unlink($file->getRealPath());
    }
}
rmdir($dir);