#!/usr/bin/env php
<?php
define("SMF", true);
$boarddir = getenv("FORUMS_SOURCE");
$sourcedir = "$boarddir/Sources";
$forum_version = "SMF " . getenv("SMF_VERSION");

$temp_dir = "$boarddir/Packages/temp";

require_once("$sourcedir/Errors.php");
require_once("$sourcedir/QueryString.php");
require_once("$sourcedir/Subs.php");
require_once("$sourcedir/Subs-Package.php");

function loadLanguage($language) {}

function download($uri) {
    $entries = scandir(".");
    passthru("wget --content-disposition \"$uri\"");
    return array_values(array_diff(scandir("."), $entries))[0];
}

function downloadPackage($packageUrl) {
    global $boarddir;
    $packageFile = download($packageUrl);
    $fullPackageName = "$boarddir/Packages/$packageFile";
    rename($packageFile, $fullPackageName);
    return $packageFile;
}

function unpackPackage($packageFile) {
    global $boarddir, $temp_dir;
    $fullPackageName = "$boarddir/Packages/$packageFile";
    mktree($temp_dir, 0777);
    read_tgz_file($fullPackageName, $temp_dir);
}

function installPackage($packageFile) {
    $packageInfo = getPackageInfo($packageFile);
    return parsePackageInfo($packageInfo['xml'], false);
}

function cleanup() {
    global $temp_dir;
    deltree($temp_dir);
}

$packageUrl = $argv[1];
$packageFile = downloadPackage($packageUrl);
unpackPackage($packageFile);
installPackage($packageFile);
cleanup();
