#!/bin/php
<?php
/*
Description:
This tool analyzes the local world-file with only the local repositires
So it is reproducable on every computer (without impacts of currently installed programs and binhost)
Right after that zzz-dynamic files for package.use/package.unmask/package.accept_keywords are created

No longer the need of pw-cfg-portage-use ebuilds in petersweeze needed
No longer the need of -wrapper ebuilds in petersweeete needed
update_preinstall_useflags.php is now obsolet - keeps until every petersweeze pw-cfg* / *-wrappers are removed!


*/

echo "\r\nSTART [update_maintain_deps.php]\r\n";

// Pre filesystem checks:
if(!file_exists("/etc/portage/package.use")){
    echo "mkdir package.use...\r\n";
    mkdir("/etc/portage/package.use");
}
if(!file_exists("/etc/portage/package.unmask")){
    echo "mkdir package.unmask...\r\n";
    mkdir("/etc/portage/package.unmask");
}
if(!file_exists("/etc/portage/package.accept_keywords")){
    echo "mkdir package.accept_keywords...\r\n";
    mkdir("/etc/portage/package.accept_keywords");
}
if(!file_exists("/etc/portage/package.use/zzz-dynamic")){
    echo "touch package.use/zzz-dynamic...\r\n";
    touch("/etc/portage/package.use/zzz-dynamic");
}
if(!file_exists("/etc/portage/package.unmask/zzz-dynamic")){
    echo "touch package.unmask/zzz-dynamic...\r\n";
    touch("/etc/portage/package.unmask/zzz-dynamic");
}
if(!file_exists("/etc/portage/package.accept_keywords/zzz-dynamic")){
    echo "touch package.accept_keywords/zzz-dynamic...\r\n";
    touch("/etc/portage/package.accept_keywords/zzz-dynamic");
}

echo "Claim flock... ";
$fp_lock = fopen("/var/run/update_maintain_deps.lock","w+");
flock($fp_lock,LOCK_EX);
echo "done\r\n";
echo "First calling update_preinstall_useflags.php...\r\n";
passthru("update_preinstall_useflags.php");
echo "done update_preinstall_useflags.php!\r\n";
echo "This program creates USE-Flag/unmask/accept_keywords files for complete deptree of world\r\n";
echo "Cleanup files...";
cleanup_file("/etc/portage/package.use/zzz-dynamic");
cleanup_file("/etc/portage/package.unmask/zzz-dynamic");
cleanup_file("/etc/portage/package.accept_keywords/zzz-dynamic");
echo "done!\r\n";
sleep(1); // Sometimes the next emerge-command think the files are not emptied and dont produce the full list
echo "Recreate complete dependency graphs...\r\n";
passthru("FEATURES=-getbinpkg emerge --backtrack=100 --autounmask-backtrack=y --autounmask-only --autounmask --autounmask-write --emptytree world");
fclose($fp_lock);
echo "EXIT [update_maintain_deps.php]\r\n\r\n";


function cleanup_file($filename){
	$fp = fopen($filename,"r");
	$firstline=fgets($fp,1024);
	fclose($fp);
	
	$fp = fopen($filename,"w");
	fwrite($fp,trim($firstline)."\n");
	fclose($fp);
}
