<?php
//@2013-10-14 TODO nalezy uzyc jednorazowo hasla ADMIN_USERNAME_INITIAL_PASSWD po czym zmienic ja na haslo ADMIN_USERNAME_PASSWD i go uzywac dalej ? 
//@2013-09 SQIX:
//skrypt do instalacji SE na zdalnym serwerze APPLE na podstawie tabeli SES_PROCESY5_A
//wymaga po stronie zdalnej:
//1) Apple Mac mini
// - zainstalowane oprogramowanie Server z włączonym OpenDirectory i zalozonym uzytkownikiem z uprawnieniami administratora ( ADMIN_USERNAME_DIRECTORY ) 
// - ustawione konto administratora zgodne z parametrami w tabeli ( ADMIN_USERNAME / ADMIN_USERNAME_PASSWD  ) - do zalogowania się ssh
// NIE TRZEBA SKRYPT SCIAGA- zainstsalowane oprogramowanie XCODE z zainstalowanymi CONSOLE UTILS
// NIE TRZEBA SKRYPT SCIAGA - zainstalowane oprgoramowanie MACPORTS
// TRZEBA W SERVERADMIN RECZNIE ODPALIC OPEN_DIRECTORY!!! - trzeba dobrze ustawic hostname, bo jest uid=diradmin,cn=users,dc=193,dc=34,dc=3,dc=100

echo "<h2>Pamiętaj o konieczności udostępnienia dostępu do bazy SQL na port 3306 [administrator] dla instalowanego serwera dla serwera se.dev.webone.pl (stara sowa), bo inaczej nie zainstaluje się baza danych</h2>";


// powyższe instaluje się tak : 
//+ zakladamy konto w ITUNES na KLIENTA lub korzystamy z konta prezesa energo@me.com!!! TODO do wyjasnienia z zestawem pakietow
//+ Sciagamy xCODE z ITUNES (SKRYPT SAM SCIAGA LOKALNIE GO MAMY) 
//+ Aktualizujemy xCODE o ConsoleUtils! (SKRYPT SAM GO SCIAGA)

//Ściągnij MACPORTS (sciaga sie instalacja macowa i dziala prosto)
//#sciagnij z https://distfiles.macports.org/MacPorts/MacPorts-2.1.3-10.8-MountainLion.pkg

//Ustal konto systemowe firmowe podstawowe - nazwa server zawsze , haslo indywodualne - zapisz w kontatkach pod nazwa serwera (TODO)
//Ustal dostęp dla tego konta aby można było się logować SSH oraz VNC  , ustal haslo VNC - też zapisz



//PLAN:

//MAC OS 1.0 INSTALACJA SE - Najpierw isntalujemy pakiet SERVER z ITUNES (na poczatku opisane)

//MAC OS 1.01 Konsolowe drobne poprawki

//MAC OS 1.1 INSTALACJA SE - 
//MAC OS 1.3 FIREWALL konfiguracja serwera z SE i BAZA DANYCH
//MAC OS 2.   instalacja mysql 

//MAC OS 2.1 instalacja phpMyAdmin
//MAC OS 3.  instalacja webmaila roundcube



//#########!!!! POCZATEK INSTALACJI !!!!




function SSH_COMMAND_REMOTE_CREATE($username,$host,$password,$command) {

//return '/opt/local/bin/sshpass -p '.$password.' ssh -o StrictHostKeyChecking=no '.$username.'@'.$host.' <<EOF
return '/opt/local/bin/sshpass -p '.str_replace('!','\!',$password).' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=99999 '.$username.'@'.$host.' -t <<EOF	
sudo -n su -
declare PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin/:/Applications/Server.app/Contents/ServerRoot/usr/sbin/

'.$command.'

EOF';

/*return '/opt/local/bin/sshpass -p '.$password.' ssh -o StrictHostKeyChecking=no '.$username.'@'.$host.' 	

'.$command.'

"';
*/
}



function INSTALL_GETCOMMANDS($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD,$BACKUP_USB_DEVICE,$SERVER_VERSION) {
// $cmd[]['rsh']='echo "'.$ADMIN_USERNAME_PASSWD.'" | sudo -S su -';
// $cmd[]['rsh']='echo "'.$ADMIN_USERNAME_PASSWD.'" | sudo -S su -';
 //$cmd[]['rsh']='shopt -s dotglob'; //przenoszenie plikow z kropka



//! KONFIG POWERM MANAGEMENT i dostepu VNC
 $cmd[]['rsh']=' [ -e /Library/Server/Web ] || { '.tell_user_gui_error("Not installed OSX Server").'; exit 1; } '; //sprawdzenie czy ma OSX server - jak nie ma to die
 $cmd[]['rsh']=' serveradmin settings dirserv:LDAPSettings:LDAPSearchBase | grep  "'.$SERVER_ADDRESS_LDAP_DC.'" || { '.tell_user_gui_error('Not installed correctly Open Directory Service in OSX Server - should be set DC:'.$SERVER_ADDRESS_LDAP_DC).' ; exit 1 ;}'; //sprawdzenie czy ma OSX server - jak nie ma to die
 $cmd[]['rsh']=' pmset sleep 0'; //wylaczenie usypiania
 $cmd[]['rsh']=' pmset autorestart 1'; //automatyczny restart po awarii zasilania
 $cmd[]['rsh']='/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -clientopts -setvnclegacy -vnclegacy yes -clientopts -setvncpw -vncpw '.substr($ADMIN_USERNAME_PASSWD,0,6).' -restart -agent -privs -all'; //wlaczenie vnc z haslem 6 liter hasla glownego
 $cmd[]['rsh']='/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -configure -users '.$ADMIN_USERNAME.' -allowAccessFor -specifiedUsers  -configure -restart -agent -privs -all'; //dostep do remote desktop dla glownego admina

//! deinsalacja ewentualnie zainstalowanego systemu dla reinstalacji
// $cmd[]['rsh']='echo DEINSTALACJA_EWENTUALNIE_ZAINSTALOWANEG_SYSTEMU';
// $cmd[]['rsh']='ls /Library/Server/Web/Data/Sites/Default/ |grep -i OfflineIMAP  && rm -R /Library/Server/Web/Data/Sites/Default/OfflineIMAP* || echo PASSED';
// $cmd[]['rsh']='ls /Library/Server/Web/Data/Sites/Default/ |grep -i nconf  && rm -R /Library/Server/Web/Data/Sites/Default/nconf* || echo PASSED';
// $cmd[]['rsh']='ls /Library/Server/Web/Data/Sites/Default/ |grep -i icinga  && rm -R /Library/Server/Web/Data/Sites/Default/icinga* || echo PASSED';
// $cmd[]['rsh']='which mysqladmin && mysqladmin  -f -uroot -p'.$ADMIN_USERNAME_PASSWD.' drop nconf || echo PASSED ';
//! EOF deinsalacja ewentualnie zainstalowanego systemu dla reinstalacji




//$cmd[]['rsh']=INSTALL_GET_INIT_APPLE_XML($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY);

/*
//! instalowanie icigny @2014-03-15 sqix: nie supportujemy an ten moment icigny - trzeba ja dopasowac lepiej
  $cmd[]['rsh']=' mkdir -p /usr/src/';
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/icinga.tar.gz','/usr/src/');
  $cmd[]['rsh']=' cd /usr/src && tar -zxpvf icinga.tar.gz ';
  $cmd[]['rsh']=' port install rb-gd';
  $cmd[]['rsh']=' port install libdbi';
  $cmd[]['rsh']=' port install gd2';

  $cmd[]['rsh']='cd /usr/src/icinga-* && ./configure --with-command-group=_www --with-dbi-lib=/opt/local/lib --with-dbi-inc=/opt/local/include --with-web-user=_www --with-icinga-group=_www --with-web-group=_www --with-icinga-user=_www --with-gd-lib=/opt/local/lib  --with-gd-inc=/opt/local/include';
  $cmd[]['rsh']='cd /usr/src/icinga-* && make all';
  $cmd[]['rsh']='cd /usr/src/icinga-* && make install';
  $cmd[]['rsh']='cd /usr/src/icinga-* &&  make install-config';
  $cmd[]['rsh']='cd /usr/local/icinga && chown -R _www *';
  */
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_for_system_information=.*/authorized_for_system_information=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_for_configuration_information=.*/authorized_for_configuration_information=\*/ cgi.cfg';
 // $cmd[]['rsh']='cd /usr/local/icinga/etc && sed  -i.bak s/^authorized_for_full_command_resolution=.*/authorized_for_full_command_resolution=\*/ cgi.cfg';
 // $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_for_system_commands=.*/authorized_for_system_commands=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_contactgroup_for_all_services=.*/authorized_contactgroup_for_all_services=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_contactgroup_for_all_hosts=.*/authorized_contactgroup_for_all_hosts=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_contactgroup_for_all_service_commands=.*/authorized_contactgroup_for_all_service_commands=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_contactgroup_for_all_host_commands=.*/authorized_contactgroup_for_all_host_commands=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_for_all_service_commands=.*/authorized_for_all_service_commands=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_for_all_services=.*/authorized_for_all_services=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^authorized_for_all_hosts=.*/authorized_for_all_hosts=\*/ cgi.cfg';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^admin_email=.*/admin_email='.$ADMIN_USERNAME_L1.'@'.$SERVER_ADDRESS_SHORT.'/ icinga.cfg  ';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^admin_pager=.*/admin_pager='.$ADMIN_USERNAME_L1.'@'.$SERVER_ADDRESS_SHORT.'/ icinga.cfg ';
//  $cmd[]['rsh']='cd /usr/local/icinga/etc && sed -i.bak s/^cfg_file=/#cfg_file=/g icinga.cfg';

//! icinga pluginy-nagios @2014-03-15 sqix : icinga wywalona z instalatora do czasu przygotowania produktu
 // $cmd[]['rsh']=' port install mysql_select';
 
 /*
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/nagios-plugins-1.5.tar.gz','/usr/src/');
  $cmd[]['rsh']=' cd /usr/src && tar -zxpvf nagios-plugins-1.5.tar.gz';
  $cmd[]['rsh']=' cd /usr/src/nagios-plugins-1.5 && ./configure \
    --prefix=/usr/local/icinga --with-cgiurl=/icinga/cgi-bin \
    --with-nagios-user=_www --with-nagios-group=_www \
    --with-mysql=/opt/local/lib/mysql55/bin/mysql_config';
  $cmd[]['rsh']=' cd /usr/src/nagios-plugins-1.5 && make';
  $cmd[]['rsh']=' cd /usr/src/nagios-plugins-1.5 && make install ';

  $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/icinga && \
  cd /Library/Server/Web/Data/Sites/Default/icinga && \
  ln -s /usr/local/icinga/share/* ./ && \
  mkdir cgi-bin && cd cgi-bin && \
  ln -s /usr/local/icinga/sbin/* ./ && \
  chown -R _www /Library/Server/Web/Data/Sites/Default/icinga
 ';
 
 
$cmd[]['rsh']='echo \'<?xml version=1.0 encoding=UTF-8?>
<!DOCTYPE plist PUBLIC -//Apple//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd>
<plist version=1.0>
<dict>
    <key>Label</key>
    <string>org.icinga</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/icinga/bin/icinga</string>
        <string>/usr/local/icinga/etc/icinga.cfg</string>
    </array>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>\' > /Library/LaunchDaemons/org.icinga.plist';
$cmd[]['rsh']='mkdir /Library/Server/Web/Data/Sites/Default/icinga/rw';
*/
// $cmd[]['rsh']='sed -i.bak "s/command_file=.*/command_file=\/Library\/Server\/Web\/Data\/Sites\/Default\/icinga\/rw\/icinga.cmd/g" /usr/local/icinga/etc/icinga.cfg'; //zmieniam inita do launchctl aby sam z siebie sie odpalal
// $cmd[]['rsh']='cd /usr/local/icinga/libexec && chmod +s ./check_dhcp';
// $cmd[]['rsh']='cd /usr/local/icinga/libexec && chown root ./check_dhcp';
// $cmd[]['rsh']='cd /usr/local/icinga/libexec && chmod u+x ./check_dhcp ';
//
// $cmd[]['rsh']='mkdir -p /Library/Server/Web/Data/Sites/Default/icinga/rw';
// $cmd[]['rsh']='touch /Library/Server/Web/Data/Sites/Default/icinga/rw/icinga.cmd';
// $cmd[]['rsh']='chmod 0777 /Library/Server/Web/Data/Sites/Default/icinga/rw';
//
// $cmd[]['rsh']='chown -R _www /usr/local/icinga/';
// $cmd[]['rsh']='launchctl load /Library/LaunchDaemons/org.icinga.plist'  ;
// $cmd[]['rsh']='launchctl start org.icinga'  ;

 /*
//! instalowanie  nconfa
 	$cmd[]['rsh']=' port install p5.16-dbd-mysql';
  $cmd[]['rsh']=' port install p5-dbd-mysql';
  $cmd[]['rsh']=' mysqladmin -uroot -p'.$ADMIN_USERNAME_PASSWD.' create nconf ';
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/nconf.tar.gz','/Library/Server/Web/Data/Sites/Default');
  $cmd[]['rsh']=' cd /Library/Server/Web/Data/Sites/Default && tar -zxpvf nconf.tar.gz';
  $cmd[]['rsh']=' echo "<?php
/ *
#
# User/Password file for simple authentication
# To disable a user, rows can be commented out with "#"
#
# :: is the delimiter of the fields
# Do NOT use :: (2 colons) in a data field (as name or password etc.) !
#
#username::password::authorization(user|admin)::[user\'s full name (optional)]::
admin::nconf::admin::Administrator::
#user::1234::user::Normal User::
#dummy::9999::user::User Dummy::
#foo::bar::user::foo bar::
#
# using encrypted passwords
#user2::{CRYPT}s7FkIgzTWZia2::user::User with a CRYPT password::
#
* /
?>
" > /Library/Server/Web/Data/Sites/Default/nconf/config/.file_accounts.php';
 $cmd[]['rsh']=' echo "<?php
define(\'AUTH_ENABLED\', \'1\');
define(\'AUTH_TYPE\', \"ldap\");
define(\'AUTH_METHOD\', \'login\');
define(\'BASICAUTH_REALM\',  \"NConf Basic Auth\");
define(\'AUTH_FEEDBACK_AS_WELCOME_NAME\', \'1\');
define(\'GROUP_USER\',       \"user\");
define(\'GROUP_ADMIN\',      \"admin\");
define(\'GROUP_NOBODY\',     \"0\");
define(\'LDAP_SERVER\',      \"ldap://127.0.0.1\");
# The port to connect to. Not used when using URLs. Defaults to 389. (by PHP)
define(\'LDAP_PORT\',        \"389\");

define(\'BASE_DN\',          \"uid=<username>,cn=users,'.$SERVER_ADDRESS_LDAP_DC.'\");
define(\'USER_REPLACEMENT\', \"<username>\");
define(\'GROUP_DN\',         \"cn=groups,'.$SERVER_ADDRESS_LDAP_DC.'\");
define(\'ADMIN_GROUP\',      \"cn=workgroup\");
define(\'USER_GROUP\',       \"cn=workgroup\");
define(\'AUTH_SQLQUERY_USER\',null);
define(\'AUTH_SQLQUERY_ADMIN\',null);
?>" > /Library/Server/Web/Data/Sites/Default/nconf/config/authentication.php';
 
 $cmd[]['rsh']=' echo "
[extract config]
type        = local
source_file = \"/Library/Server/Web/Data/Sites/Default/nconf/output/NagiosConfig.tgz\"
target_file = \"/usr/local/icinga/etc/conf.d/\"
action      = extract
" > /Library/Server/Web/Data/Sites/Default/nconf/config/deployment.ini';
$cmd[]['rsh']=' echo "<?php
#
# Main MySQL connection parameters
#
define(\'DBHOST\', \'127.0.0.1\');
define(\'DBNAME\', \'nconf\');
define(\'DBUSER\', \'root\');
define(\'DBPASS\', \''.$ADMIN_USERNAME_PASSWD.'\');

?>" > /Library/Server/Web/Data/Sites/Default/nconf/config/mysql.php';
$cmd[]['rsh']=' echo "<?php
define(\'NCONFDIR\', \'/Library/Server/Web/Data/Sites/Default/nconf\');
define(\'OS_LOGO_PATH\', \"img/logos\");
define(\'NAGIOS_BIN\', \'/usr/local/icinga/bin/icinga\');
define(\'CHECK_UPDATE\', 0);
define(\'TEMPLATE_DIR\', \'nconf_fresh\');
define(\"DEBUG_MODE\",     0); # [0|1]
define(\"DEBUG_GENERATE\", 3); # [1=ERROR|2=WARN|3=INFO|4=DEBUG|5=TRACE]
define(\"DB_NO_WRITES\",   0); # [0|1] Experimental, use with CAUTION!
define(\'REDIRECTING_DELAY\', \"1\");
define(\'ALLOW_DEPLOYMENT\', 1);
\\\\\$STATIC_CONFIG = array(\"static_cfg\");
define(\'CHECK_STATIC_SYNTAX\', 1);
\\\\\$SUPERADMIN_GROUPS = array (\"+admins\");
\\\\\$ONCALL_GROUPS = array ();
define(\'CHECK_STATIC_SYNTAX\', 1);
\\\\\$SUPERADMIN_GROUPS = array (\"+admins\");
\\\\\$ONCALL_GROUPS = array ();
define(\'OVERVIEW_QUANTITY_STANDARD\', \"25\");
define(\'SELECT_VALUE_SEPARATOR\', \"::\");
define(\'PASSWD_ENC\', \"clear\");
define(\'PASSWD_DISPLAY\', 0);
define(\'PASSWD_DISPLAY\', 0);
define(\'PASSWD_HIDDEN_STRING\', \"********\");
?>" > /Library/Server/Web/Data/Sites/Default/nconf/config/nconf.php';
$cmd[]['rsh']=' cat  /Library/Server/Web/Data/Sites/Default/nconf/INSTALL/create_database.sql |mysql -uroot -h127.0.0.1 -Dnconf -p'.$ADMIN_USERNAME_PASSWD;
$cmd[]['rsh']=' rm -R  /Library/Server/Web/Data/Sites/Default/nconf/INSTALL*';
$cmd[]['rsh']=' rm -R  /Library/Server/Web/Data/Sites/Default/nconf/UPDATE*';
$cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/nconf/temp/test/ && touch /Library/Server/Web/Data/Sites/Default/nconf/temp/test/Default_collector.cfg'  ;
$cmd[]['rsh']=' chmod -R 0777 /Library/Server/Web/Data/Sites/Default/nconf/temp';
$cmd[]['rsh']=' chown -R _www  /Library/Server/Web/Data/Sites/Default/nconf';
$cmd[]['rsh']=' echo "
-- dodajemy Kolumne do powiazania numeru zasobu do monitorowania z bazy zasobow, bedzie trzeba miec jeszcze odznaczneie numeru Device
alter ignore table nconf.ConfigItems add A_RECORD_CREATE_AUTHOR char(25) ; 
alter ignore table nconf.ConfigAttrs add A_RECORD_CREATE_AUTHOR char(25) ; 
alter ignore table nconf.ConfigClasses add A_RECORD_CREATE_AUTHOR char(25) ; 
alter ignore table nconf.ConfigValues add A_RECORD_CREATE_AUTHOR char(25) ;
alter ignore table nconf.ItemLinks add A_RECORD_CREATE_AUTHOR char(25) ;
alter ignore table nconf.ConfigItems add CRM_LISTA_ZASOBOW_ID int(11) ; 
alter ignore table nconf.ConfigItems add DEVICES_ID int(11) ; " | mysql -D nconf -uroot -p'.$ADMIN_USERNAME_PASSWD ;
 $cmd[]['rsh']=' echo "
-- zapytanie do importu z SE zasobow oraz urzadzen do monitoringu do nconfa do icinga

-- w razie co mozna usunac dodane rekordy w taki sposob
 delete  FROM nconf.\\\\\`ConfigValues\\\\\` WHERE \\\\\`A_RECORD_CREATE_AUTHOR\\\\\` like \'SE_IMPORT\';
 delete  FROM nconf.\\\\\`ItemLinks\\\\\`  WHERE \\\\\`A_RECORD_CREATE_AUTHOR\\\\\` like \'SE_IMPORT\';
 delete  FROM nconf.\\\\\`ConfigItems\\\\\` WHERE \\\\\`A_RECORD_CREATE_AUTHOR\\\\\` like \'SE_IMPORT\';
 delete  FROM nconf.\\\\\`ConfigAttrs\\\\\` WHERE \\\\\`A_RECORD_CREATE_AUTHOR\\\\\` like \'SE_IMPORT\';
 delete  FROM nconf.\\\\\`ConfigClasses\\\\\` WHERE \\\\\`A_RECORD_CREATE_AUTHOR\\\\\` like \'SE_IMPORT\';

-- bierzemy z zasobow dane tylko takie, ktore nie maja powiazanych DEVICES (bierzemy tylko devices)
insert into nconf.ConfigItems ( id_item , fk_id_class , DEVICES_ID,A_RECORD_CREATE_AUTHOR) 
 select  \'\', 1, DEVICES.ID , \'SE_IMPORT\' from '.$REMOTE_FOLDER_ROOT.'.DEVICES 
   left join nconf.ConfigItems as ConfigItems_2 on ConfigItems_2.DEVICES_ID=DEVICES.ID
   where ConfigItems_2.DEVICES_ID is null ;

-- dodajemy zasoby do monitoringu w inteligentny sposob razem z waznymi parametrami - jak to widac w zapytaniu
insert ignore into nconf.ConfigValues ( attr_value, fk_id_attr, fk_id_item, A_RECORD_CREATE_AUTHOR ) 
  select 
  if( ConfigAttrs.Attr_name like \'%host_name%\'
   , left(replace(replace(replace(replace(replace(replace(concat(DEV.ID,\'-\',DEV.T_DEVICE_SERIAL,\'-\',DEV.S_HW,\'[\',\\\\\`CLZ\\\\\`.ID,\'] URZADZENIE \', DEV.T_DEVICE_TYPE,\'-\',CLZ.\\\\\`DESC\\\\\`,\' \'),\',\',\'\'),\'/\',\'\'),\'(\',\'\'),\')\',\'\'),\'%\',\'\'),\'?\',\'\'),50)
   , 
 if( ConfigAttrs.Attr_name like \'alias\', \\\\\`DEV\\\\\`.\\\\\`S_IP\\\\\`,
 if( ConfigAttrs.Attr_name like \'address\', \\\\\`DEV\\\\\`.\\\\\`S_IP\\\\\`,
 if( ConfigAttrs.Attr_name like \'host_is_collector\',\'no\',\'\')
)
)
 ) 
, ConfigAttrs.id_attr 
 , ConfigItems.id_item ,\'SE_IMPORT\'
    from  se_feromedia24_com.DEVICES as DEV
    left join '.$REMOTE_FOLDER_ROOT.'.CRM_LISTA_ZASOBOW as CLZ on CLZ.ID=DEV.CRM_LISTA_ZASOBOW_ID
      left join nconf.ConfigAttrs  on  ConfigAttrs.Attr_name
 in (\'host_name\',\'alias\',\'address\',\'notes\',\'notes_url\',\'host_is_collector\',\'action_url\',\'max_check_attempts\',\'check_interval\',\'retry_interval\',\'first_notification_delay\',\'notification_interval\',\'notification_options\',\'active_checks_enabled\',\'passive_checks_enabled\',\'notifications_enabled\',\'check_freshness\',\'freshness_threshold\')   and  ConfigAttrs.fk_id_class=\'1\'
   left join nconf.ConfigItems as ConfigItems on ConfigItems.DEVICES_ID=DEV.ID
--   left join '.$REMOTE_FOLDER_ROOT.'.DEVICES as DEVICES on DEVICES.CRM_LISTA_ZASOBOW_ID=CLZ.ID
 where  DEV.S_IP like \'%_\';
-- dodajemy potrzebne wpisy odnosnie klasy monitorowania
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr, A_RECORD_CREATE_AUTHOR ) 
 select ConfigItems.id_item , \'1\' , ConfigAttrs.id_attr , \'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'monitored_by\' and ConfigAttrs.fk_id_class=\'1\'
   where ConfigItems.DEVICES_ID>0 ;

-- kolejny istotny parametr
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR) 
 select ConfigItems.id_item , ConfigValues.fk_id_item , ConfigAttrs.id_attr , \'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'parents\' and ConfigAttrs.fk_id_class=\'1\'
      left join nconf.ConfigAttrs as ConfigAttrs2 on ConfigAttrs2.attr_name=\'host_name\' and ConfigAttrs.fk_id_class=\'1\'
      left join nconf.ConfigValues on  ConfigValues.attr_value=\'localhost\' and fk_id_attr=ConfigAttrs2.id_attr
   where ConfigItems.DEVICES_ID>0  and ConfigValues.fk_id_item is not null;

-- # OS domyslnie LINUX 18 , trzeba wziac z ConfigClasses config_class=\'os\' -> id_class, i poszukac ConfigItems.id_item;
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr, A_RECORD_CREATE_AUTHOR ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr , \'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'os\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=ConfigAttrs.attr_name
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.DEVICES_ID>0 
group by ConfigItems.id_item
;

-- #host-preset==75 , trzeba wziac z ConfigClasses config_class=\'os\' -> id_class, i poszukac ConfigItems.id_item;
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr, A_RECORD_CREATE_AUTHOR ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr ,\'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'host-preset\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=ConfigAttrs.attr_name
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.DEVICES_ID>0 
group by ConfigItems.id_item;

-- #check_period==19 , trzeba wziac kakis time_period z Classes;
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr ,\'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'check_period\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=\'timeperiod\'
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.DEVICES_ID>0 
group by ConfigItems.id_item;

-- #contact_groups==22 ,
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr, A_RECORD_CREATE_AUTHOR ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr,\'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'contact_groups\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=\'contactgroup\'
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.DEVICES_ID>0 
group by ConfigItems.id_item;

-- # use host template(s) to inherit properties from - szukamy ConfigValues.attr_value=\'linux-server\' z atrybutem 108(name)
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr, A_RECORD_CREATE_AUTHOR) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr,\'SE_IMPORT\'
 from nconf.ConfigItems  
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'use\' and ConfigAttrs.fk_id_class=\'1\'
    left join nconf.ConfigAttrs as ConfigAttrs_name on ConfigAttrs_name.attr_name=\'name\' and ConfigAttrs_name.fk_id_class=\'14\'
   left  join nconf.ConfigValues  on ConfigValues.attr_value=\'linux-server\' and ConfigValues.fk_id_attr=ConfigAttrs_name.id_attr
   left join nconf.ConfigClasses on ConfigClasses.config_class=\'host-template\'
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class and ConfigValues.fk_id_item=ConfigItems2.id_item
   where ConfigItems.DEVICES_ID>0 
group by ConfigItems.id_item;

-- bierzemy z zasobow dane tylko takie, ktore nie maja powiazanych DEVICES (TODO trzeba dorzucic obsluge tego)
insert into nconf.ConfigItems ( id_item , fk_id_class , CRM_LISTA_ZASOBOW_ID , A_RECORD_CREATE_AUTHOR) 
 select  \'\', 1, CRM_LISTA_ZASOBOW.ID ,\'SE_IMPORT\' from '.$REMOTE_FOLDER_ROOT.'.CRM_LISTA_ZASOBOW 
   left join nconf.ConfigItems as ConfigItems_2 on ConfigItems_2.CRM_LISTA_ZASOBOW_ID=CRM_LISTA_ZASOBOW.ID
   where CRM_LISTA_ZASOBOW.\\\\\`TYPE\\\\\`=\'SERWER\' and ConfigItems_2.CRM_LISTA_ZASOBOW_ID is null ;

-- dodajemy zasoby do monitoringu w inteligentny sposob razem z waznymi parametrami - jak to widac w zapytaniu
insert ignore into nconf.ConfigValues ( attr_value, fk_id_attr, fk_id_item , A_RECORD_CREATE_AUTHOR
 ) 
  select 
  if( ConfigAttrs.Attr_name like \'%host_name%\'
   , left(replace(replace(replace(replace(replace(replace(concat(\'[\',\\\\\`CLZ\\\\\`.ID,\'] SERWER \',CLZ.\\\\\`DESC\\\\\`,\' \',CLZ.\\\\\`OPIS\\\\\`),\',\',\'\'),\'/\',\'\'),\'(\',\'\'),\')\',\'\'),\'%\',\'\'),\'?\',\'\'),40)
   , 
 if( ConfigAttrs.Attr_name like \'alias\', \\\\\`CLZ\\\\\`.\\\\\`DESC\\\\\`,
 if( ConfigAttrs.Attr_name like \'address\', \\\\\`CLZ\\\\\`.\\\\\`DESC\\\\\`,
 if( ConfigAttrs.Attr_name like \'host_is_collector\',\'no\',\'\')
)
)
 ) 
, ConfigAttrs.id_attr 
 , ConfigItems.id_item , \'SE_IMPORT\'
    from  '.$REMOTE_FOLDER_ROOT.'.CRM_LISTA_ZASOBOW as CLZ
      left join nconf.ConfigAttrs  on  ConfigAttrs.Attr_name
 in (\'host_name\',\'alias\',\'address\',\'notes\',\'notes_url\',\'host_is_collector\',\'action_url\',\'max_check_attempts\',\'check_interval\',\'retry_interval\',\'first_notification_delay\',\'notification_interval\',\'notification_options\',\'active_checks_enabled\',\'passive_checks_enabled\',\'notifications_enabled\',\'check_freshness\',\'freshness_threshold\')   and  ConfigAttrs.fk_id_class=\'1\'
   left join nconf.ConfigItems as ConfigItems on ConfigItems.CRM_LISTA_ZASOBOW_ID=CLZ.ID
   left join '.$REMOTE_FOLDER_ROOT.'.DEVICES as DEVICES on DEVICES.CRM_LISTA_ZASOBOW_ID=CLZ.ID
 where CLZ.\\\\\`TYPE\\\\\`=\'SERWER\' and DEVICES.CRM_LISTA_ZASOBOW_ID is NULL;
-- dodajemy potrzebne wpisy odnosnie klasy monitorowania
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR
 ) 
 select ConfigItems.id_item , \'1\' , ConfigAttrs.id_attr , \'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'monitored_by\' and ConfigAttrs.fk_id_class=\'1\'
   where ConfigItems.CRM_LISTA_ZASOBOW_ID>0 ;

-- kolejny istotny parametr
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR
) 
 select ConfigItems.id_item , ConfigValues.fk_id_item , ConfigAttrs.id_attr , \'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'parents\' and ConfigAttrs.fk_id_class=\'1\'
      left join nconf.ConfigAttrs as ConfigAttrs2 on ConfigAttrs2.attr_name=\'host_name\' and ConfigAttrs.fk_id_class=\'1\'
      left join nconf.ConfigValues on  ConfigValues.attr_value=\'localhost\' and fk_id_attr=ConfigAttrs2.id_attr
   where ConfigItems.CRM_LISTA_ZASOBOW_ID>0  and ConfigValues.fk_id_item is not null;

-- # OS domyslnie LINUX 18 , trzeba wziac z ConfigClasses config_class=\'os\' -> id_class, i poszukac ConfigItems.id_item;
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR
 ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr ,\'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'os\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=ConfigAttrs.attr_name
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.CRM_LISTA_ZASOBOW_ID>0 
group by ConfigItems.id_item
;


-- #host-preset==75 , trzeba wziac z ConfigClasses config_class=\'os\' -> id_class, i poszukac ConfigItems.id_item;
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR
 ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr ,\'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'host-preset\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=ConfigAttrs.attr_name
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.CRM_LISTA_ZASOBOW_ID>0 
group by ConfigItems.id_item;


-- #check_period==19 , trzeba wziac kakis time_period z Classes;
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR
 ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr ,\'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'check_period\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=\'timeperiod\'
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.CRM_LISTA_ZASOBOW_ID>0 
group by ConfigItems.id_item;

-- #contact_groups==22 ,
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR
 ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr ,\'SE_IMPORT\' from nconf.ConfigItems 
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'contact_groups\' and ConfigAttrs.fk_id_class=\'1\'
     left join nconf.ConfigClasses on ConfigClasses.config_class=\'contactgroup\'
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class
   where ConfigItems.CRM_LISTA_ZASOBOW_ID>0 
group by ConfigItems.id_item;

-- # use host template(s) to inherit properties from - szukamy ConfigValues.attr_value=\'linux-server\' z atrybutem 108(name)
insert ignore into nconf.ItemLinks ( fk_id_item,fk_item_linked2,fk_id_attr , A_RECORD_CREATE_AUTHOR
 ) 
 select ConfigItems.id_item , ConfigItems2.id_item , ConfigAttrs.id_attr  ,\'SE_IMPORT\'
 from nconf.ConfigItems  
    left join nconf.ConfigAttrs on ConfigAttrs.attr_name=\'use\' and ConfigAttrs.fk_id_class=\'1\'
    left join nconf.ConfigAttrs as ConfigAttrs_name on ConfigAttrs_name.attr_name=\'name\' and ConfigAttrs_name.fk_id_class=\'14\'
   left  join nconf.ConfigValues  on ConfigValues.attr_value=\'linux-server\' and ConfigValues.fk_id_attr=ConfigAttrs_name.id_attr
   left join nconf.ConfigClasses on ConfigClasses.config_class=\'host-template\'
     left join nconf.ConfigItems as ConfigItems2 on ConfigItems2.fk_id_class=ConfigClasses.id_class and ConfigValues.fk_id_item=ConfigItems2.id_item
   where ConfigItems.CRM_LISTA_ZASOBOW_ID>0 
group by ConfigItems.id_item;
 
 " >  /Library/Server/Web/Data/Sites/Default/nconf/ADD-ONS/import_from_se_to_nconf.sql '   ;
 
 
//! nconf import do incingi z SE/devices urzadzen do monitoringu

*/

//@2014-03-14 sqix: funkcja zglasza errory do poprawy TODO
//! uruchomienie backupu USB jezeli wybrana opcja $BACKUP_USB_DEVICE
//$cmd[]['rsh']='for a in `mount |grep \'/Volumes\' |awk \'{ print $1 }\'`;  do
//	[ \''.$BACKUP_USB_DEVICE.'\' = \'YES\' ] && diskutil info $a |grep USB >/dev/null && {
//	 mountpath=`diskutil info /dev/disk1s3 |grep \'Mount Point\' |sed s/.*Mount\ Point:\ *//g`
//	 tmutil setdestination $mountpath
//	 tmutil enable
//	} || echo "Not used backup device"
//	done
//';

 return $cmd; 

}
 
 
function INSTALL_GETCOMMANDS_COMP_PORT($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD,$BACKUP_USB_DEVICE,$SERVER_VERSION) {
//komendy do stworzenia komponentu dot MYSQL
 $cmd[]['rsh']='cat /etc/sudoers |grep "'.$ADMIN_USERNAME.' ALL = NOPASSWD: /usr/bin/su" || echo "'.$ADMIN_USERNAME.' ALL = NOPASSWD: /usr/bin/su
 " >> /etc/sudoers;
 cat /etc/sudoers |grep "'.$ADMIN_USERNAME.' ALL = NOPASSWD: /usr/bin/su"';
$cmd[]['rsh']='cat /etc/sudoers |grep "_www ALL = NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals" || echo "_www ALL = NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals
 " >> /etc/sudoers;
 cat /etc/sudoers |grep "_www ALL = NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals"';

$cmd[]['rsh']='cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/dscl" || echo "_www ALL = NOPASSWD: /usr/bin/dscl
 " >> /etc/sudoers;
 cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/dscl"';


$cmd[]['rsh']='cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/pwpolicy" || echo "_www ALL = NOPASSWD: /usr/bin/pwpolicy
 " >> /etc/sudoers;
 cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/pwpolicy"';


$cmd[]['rsh']='cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/sbin/createhomedir" || echo "_www ALL = NOPASSWD: /usr/sbin/createhomedir
 " >> /etc/sudoers;
 cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/sbin/createhomedir"';

// $cmd[]['rsh']='echo \\\\\$UID';
// $cmd[]['rsh']='echo "Uruchamiam zdalna procedure instalacji SE " |wall ';
 $cmd[]['rsh']='launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist'; //wyszukowanie plikow


//TO MOVE TO INSTALL_GETCOMMANDS_COMP_PORT_MYSQL
if($SERVER_VERSION=='10.9Maverick') $cmd[]['rsh']="gcc 2>&1 |grep 'no input files' || echo 'You should install console-tools manually in server  - type in console gcc'";
if($SERVER_VERSION=='10.8MountainLion') $cmd[]['scp']=array('/Library/Server/Web/Data/Sites/Default/SE/se-dev/stuff/xcode462_cltools_10_86938259a.dmg','/tmp/xcode462_cltools_10_86938259a.dmg');
if($SERVER_VERSION=='10.8MountainLion') $cmd[]['rsh']='hdiutil mount /tmp/xcode462_cltools_10_86938259a.dmg -mountpoint /Volumes/xcodetools';
if($SERVER_VERSION=='10.8MountainLion') $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "/" -verbose';//  $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';
if($SERVER_VERSION=='10.8MountainLion')  $cmd[]['scp']=array('/Library/Server/Web/Data/Sites/Default/SE/se-dev/stuff/MacPorts-2.2.0-10.8-MountainLion.pkg','/tmp/MacPorts-2.2.0-10.8-MountainLion.pkg');
if($SERVER_VERSION=='10.9Maverick')  $cmd[]['rsh']=' gcc -v || { '.tell_user_gui_error("You should run installer again after successfully finished Console Utils / Uruchom ponownie instalacje po pozytywnym zainstalowaniu Console Utils").'
 exit 1
 } ';

if($SERVER_VERSION=='10.9Maverick')  $cmd[]['scp']=array('/Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/stuff/MacPorts-2.2.1-10.9-Mavericks.pkg','/tmp/MacPorts-2.2.1-10.9-Mavericks.pkg');
if($SERVER_VERSION=='10.8MountainLion') $cmd[]['rsh']='installer -package /tmp/MacPorts-2.2.0-10.8-MountainLion.pkg -target "/" -verbose';//  $cmd[]['rsh']='installer -package /tmp/MacPorts-2.2.0-10.8-MountainLion.pkg -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';
if($SERVER_VERSION=='10.9Maverick') $cmd[]['rsh']='installer -package /tmp/MacPorts-2.2.1-10.9-Mavericks.pkg -target "/" -verbose

';//  $cmd[]['rsh']='installer -package /tmp/MacPorts-2.2.0-10.8-MountainLion.pkg -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';


if($SERVER_VERSION=='10.9Maverick') $cmd[]['scp']=array('/Applications/SourceGuardian.app/Contents/Loaders/Mac\ OS\ X/ixed.5.4.dar','/usr/lib/php/extensions/no-debug-non-zts-20100525/');//  $cmd[]['rsh']='installer -package /tmp/MacPorts-2.2.0-10.8-MountainLion.pkg -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';
if($SERVER_VERSION=='10.9Maverick') $cmd[]['rsh']='cat /etc/php.ini |grep "extension=ixed.5.4.dar" || echo "\nextension=ixed.5.4.dar\n" >> /etc/php.ini';
//EOF TO MOVE TO INSTALL_GETCOMMANDS_COMP_PORT_MYSQL
 $cmd[]['rsh']='cat /etc/paths |grep "/opt/local/bin" || echo "/opt/local/bin" >>/etc/paths';
 $cmd[]['rsh']=' grep "/opt/local/bin" /etc/paths || echo "/opt/local/bin" >>/etc/paths'; //dodanie do sciezek
 $cmd[]['rsh']=" sed  -i.bak  \"s/PS1='\\\h:/PS1='\\\H:/g\" /etc/bashrc"; //zmiana wyswietlania kurosra hosta
 $cmd[]['rsh']='which wget || port install wget';
 $cmd[]['rsh']='which joe || port install joe';

 return $cmd; 


}
 
 
 
function INSTALL_GETCOMMANDS_POSTGIS($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD,$BACKUP_USB_DEVICE,$SERVER_VERSION) {

// ! instalacja mapservera oraz komponentow sluzacych do obslugi spatialnej
//stuff/GDAL_Complete-1.11.dmg
//stuff/cairo_Framework-1.12.2-1-2.dmg
//stuff/FreeType_Framework-2.4.12-1-2.dmg
//stuff/MapServer-6.0.3-1.dmg
//stuff/mapserver-6.4.1.tar
//  $cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/*','/Library/Server/Web/Data/Sites/Default/SE/');
/*
$cmd[]['rsh']='hdiutil mount /Library/Server/Web/Data/Sites/Default/SE/stuff/GDAL_Complete-1.11.dmg -mountpoint /Volumes/GDAL_Complete-1.11';
$cmd[]['rsh']='installer -package /Volumes/GDAL_Complete-1.11/GDAL*.pkg -target "/" -verbose';//  $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';

$cmd[]['rsh']='hdiutil mount /Library/Server/Web/Data/Sites/Default/SE/stuff/cairo_Framework-1.12.2-1-2.dmg -mountpoint /Volumes/cairo_Framework-1.12.2-1-2';
$cmd[]['rsh']='installer -package /Volumes/cairo_Framework-1.12.2-1-2/*.pkg -target "/" -verbose';//  $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';

$cmd[]['rsh']='hdiutil mount /Library/Server/Web/Data/Sites/Default/SE/stuff/FreeType_Framework-2.4.12-1-2.dmg -mountpoint /Volumes/FreeType_Framework-2.4.12-1-2';
$cmd[]['rsh']='installer -package /Volumes/FreeType_Framework-2.4.12-1-2/*.pkg -target "/" -verbose';//  $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';

$cmd[]['rsh']='hdiutil mount /Library/Server/Web/Data/Sites/Default/SE/stuff/MapServer-6.0.3-1.dmg -mountpoint /Volumes/MapServer-6.0.3-1';
$cmd[]['rsh']='installer -package /Volumes/MapServer-6.0.3-1/*.pkg -target "/" -verbose';//  $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';
*/

/* 
$cmd[]['rsh']='hdiutil mount /Library/Server/Web/Data/Sites/Default/SE/stuff/JavaForOSX2014-001.dmg -mountpoint /Volumes/JavaForOSX2014-001';
$cmd[]['rsh']='installer -package /Volumes/JavaForOSX2014-001/*.pkg -target "/" -verbose';//  $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';

$cmd[]['rsh']='hdiutil mount /Library/Server/Web/Data/Sites/Default/SE/stuff/jdk-8u5-macosx-x64.dmg -mountpoint /Volumes/jdk-8u5-macosx-x64'; //TODO czy licencja na to pozwala??
$cmd[]['rsh']='installer -package /Volumes/jdk-8u5-macosx-x64/*.pkg -target "/" -verbose';//  $cmd[]['rsh']='installer -package /Volumes/xcodetools/Com* -target "'.$SERVER_MOUNT_POINT_ROOT.'" -verbose';
$cmd[]['rsh']='port install libpng';

$cmd[]['rsh']='cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs ; jdk=`ls | sort | tail -n 1`;
               mkdir -p /System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers ; 
			   ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/$jdk/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/jni.h /System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/jni.h
               port install mapserver';
//$cmd[]['rsh']='port install mapserver';

*/


// postgis by BZYK
$cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/postgis/PostgreSQL-9.3.4-1.dmg','/tmp/PostgreSQL-9.3.4-1.dmg');

$cmd[]['rsh']='hdiutil mount /tmp/PostgreSQL-9.3.4-1.dmg -mountpoint /Volumes/PostgreSQL';
$cmd[]['rsh']='installer -package /Volumes/PostgreSQL/PostgreSQL.pkg -target "/" -verbose';
$cmd[]['rsh']='hdiutil unmount /Volumes/PostgreSQL';
$cmd[]['rsh']='cd /usr/local/pgsql/data';
$cmd[]['rsh']='sudo -u _postgres /usr/local/pgsql/bin/initdb -U postgres -D /usr/local/pgsql/data --encoding=UTF8 --locale=C || echo PASSED';
$cmd[]['rsh']='sed -i ".bak" "s/.*listen_address.*#/listen_addresses = \'0.0.0.0\'            #/g" /usr/local/pgsql/data/pg_hba.conf';
$cmd[]['rsh']='grep "host    all             all             0.0.0.0/0            md5"  /usr/local/pgsql/data/pg_hba.conf  || echo \'host    all             all             0.0.0.0/0            md5\' >> /usr/local/pgsql/data/pg_hba.conf';
$cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/postgis/org.postgresql.postgres.plist','/Library/LaunchDaemons/org.postgresql.postgres.plist');
$cmd[]['rsh']='launchctl load /Library/LaunchDaemons/org.postgresql.postgres.plist';
$cmd[]['rsh']='launchctl start org.postgresql.postgres';

$cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/postgis/GDAL_Complete-1.11.dmg','/tmp/GDAL_Complete-1.11.dmg');
$cmd[]['rsh']='hdiutil mount /tmp/GDAL_Complete-1.11.dmg -mountpoint /Volumes/GDAL_Complete';
$cmd[]['rsh']='installer -package "/Volumes/GDAL_Complete/GDAL Complete.pkg" -target "/" -verbose';
$cmd[]['rsh']='hdiutil unmount /Volumes/GDAL_Complete';

$cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/postgis/PostGIS-2.1.3-2.dmg','/tmp/PostGIS-2.1.3-2.dmg');
$cmd[]['rsh']='hdiutil mount /tmp/PostGIS-2.1.3-2.dmg -mountpoint /Volumes/PostGIS';
$cmd[]['rsh']='installer -package "/Volumes/PostGIS/PostGIS.pkg" -target "/" -verbose';
$cmd[]['rsh']='hdiutil unmount /Volumes/PostGIS';


$cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/postgis/JavaForOSX2014-001.dmg','/tmp/JavaForOSX2014-001.dmg');
$cmd[]['rsh']='hdiutil mount /tmp/JavaForOSX2014-001.dmg -mountpoint /Volumes/JavaForOSX';
$cmd[]['rsh']='installer -package "/Volumes/JavaForOSX/JavaForOSX.pkg" -target "/" -verbose';
$cmd[]['rsh']='hdiutil unmount /Volumes/JavaForOSX';

$cmd[]['rsh']='sudo -u _postgres /usr/local/pgsql/bin/createdb -U postgres -O "'.$ADMIN_USERNAME.'" "'.$REMOTE_FOLDER_ROOT.'" || echo PASSED'; 
$cmd[]['rsh']='/usr/local/pgsql/bin/psql -U postgres -c "create user root with password \''.$ADMIN_USERNAME_PASSWD.'\'" || echo PASSED';
$cmd[]['rsh']='/usr/local/pgsql/bin/psql -U postgres -d "'.$REMOTE_FOLDER_ROOT.'" -c "CREATE EXTENSION postgis;" || echo PASSED';
$cmd[]['rsh']='/usr/local/pgsql/bin/psql -U postgres -d "'.$REMOTE_FOLDER_ROOT.'" -c "CREATE EXTENSION postgis_topology;" || echo PASSED';
$cmd[]['rsh']='/usr/local/pgsql/bin/psql -U postgres -d "'.$REMOTE_FOLDER_ROOT.'" -c "CREATE EXTENSION fuzzystrmatch;" || echo PASSED';
$cmd[]['rsh']='/usr/local/pgsql/bin/psql -U postgres -d "'.$REMOTE_FOLDER_ROOT.'" -c "CREATE EXTENSION postgis_tiger_geocoder;" || echo PASSED';
//TODO jakis test dodania bazy danych i czy dziala?

$cmd[]['rsh']='rm -Rf /Library/Server/Web/Data/Sites/Default/pg || echo PASSED';
$cmd[]['rsh']='mkdir -p /Library/Server/Web/Data/Sites/Default/pg';
$cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/postgis/phpPgAdmin-5.1.zip','/Library/Server/Web/Data/Sites/Default/pg/phpPgAdmin-5.1.zip');
$cmd[]['rsh']='unzip -o /Library/Server/Web/Data/Sites/Default/pg/phpPgAdmin-5.1.zip -d /Library/Server/Web/Data/Sites/Default/pg';
$cmd[]['rsh']='mv /Library/Server/Web/Data/Sites/Default/pg/phpPgAdmin-5.1/* /Library/Server/Web/Data/Sites/Default/pg';
$cmd[]['rsh']='sed -i.bak "s/\\\'extra_login_security\\\'\]\.*=.*true/\\\'extra_login_security\\\'\]\ =\ false/" /Library/Server/Web/Data/Sites/Default/pg/conf/config.inc.php';


//PGADMIN - to nie pg phpmyadmin!
//$cmd[]['rsh']='port install wxWidgets-3.0';
//$cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/postgis/pgadmin3-1.18.1.tar.gz','/usr/src/pgadmin3-1.18.1.tar.gz');
//$cmd[]['rsh']='cd /usr/src/ && tar -zxpvf pgadmin3-1.18.1.tar.gz';
//$cmd[]['rsh']='cd /usr/src/pgadmin3-1.18.1 &&  --with-wx=/opt/local/Library/Frameworks/wxWidgets.framework/Versions/wxWidgets/3.0/ --with-wx-version=3.0';

//$cmd[]['rsh']='port install phppgadmin';



return $cmd;
}

 

function INSTALL_GETCOMMANDS_MYSQL55($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD,$BACKUP_USB_DEVICE,$SERVER_VERSION) {

//! MYSQL SERVER INSTALACJA
 $cmd[]['rsh']='port install mysql55-server';
 $cmd[]['rsh']='sudo -u _mysql /opt/local/lib/mysql55/bin/mysql_install_db';
 $cmd[]['rsh']='sed -i.bak "s/<key>Disabled<\/key>/<key>Enabled<\/key>/"  /Library/LaunchDaemons/org.macports.mysql55-server.plist'; //zmieniam inita do launchctl aby sam z siebie sie odpalal
 $cmd[]['rsh']='echo "[client]
default-character-set = latin2

[mysql]
#default-character-set = latin2

[mysqld]
log-error=/var/log/mysql.log
#default-character-set = utf8  
collation-server = latin2_general_ci
init-connect=\'SET NAMES  latin2\'
character-set-server =  latin2
" > /etc/my.cnf';
 $cmd[]['rsh']='sed -i.bak "s/skip-networking/#skip-networking/"  /opt/local/etc/mysql55/macports-default.cnf';
 $cmd[]['rsh']='mkdir -p /opt/local/var/run/mysql5/';
 $cmd[]['rsh']='launchctl load -w /Library/LaunchDaemons/org.macports.mysql55-server.plist';
 $cmd[]['rsh']='echo "/opt/local/lib/mysql55/bin" >>/etc/paths';
 //@2013-10-03 tu jest bug : - recznie wyzwolona ta sama komenda ruszyła, a skrypt zwrócił error  - sprawdzam z zamiana wykrzyknikow w hasle!
 $cmd[]['rsh']='sleep 10 && mysql -uroot -p\''.$ADMIN_USERNAME_PASSWD.'\' -e \'select 1+1;\' || /opt/local/lib/mysql55/bin/mysqladmin password \''.$ADMIN_USERNAME_PASSWD.'\' '; 
 $cmd[]['rsh']='mkdir -p /var/mysql && [ -e /var/mysql/mysql.sock ] || ln -s /opt/local/var/run/mysql55/mysqld.sock /var/mysql/mysql.sock';
 
  
 $cmd[]['rsh']='/opt/local/lib/mysql55/bin/mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.' -e "SET PASSWORD FOR \'root\'@\'localhost\' = PASSWORD(\''.$ADMIN_USERNAME_PASSWD.'\')" ';  //@2015-02-28 problem dlugosci hasla - musi byc tak ustawione
//! MYSQL SERVER INSTALACJA EOF

 $cmd[]['rsh']='which mysqladmin && mysqladmin  -f -uroot -p'.$ADMIN_USERNAME_PASSWD.' drop '.$REMOTE_FOLDER_ROOT.' || echo PASSED ';


return $cmd;
}

function INSTALL_GETCOMMANDS_WEBMAIL($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD,$BACKUP_USB_DEVICE,$SERVER_VERSION) {


 $cmd[]['rsh']='which mysqladmin && mysqladmin  -f -uroot -p'.$ADMIN_USERNAME_PASSWD.' drop webmail || echo PASSED ';

 $cmd[]['rsh']='test -d /Library/Server/Web/Data/Sites/Default/webmail && rm -R /Library/Server/Web/Data/Sites/Default/webmail || echo PASSED';
 $cmd[]['rsh']='test -d /Library/Server/Web/Data/Sites/Default/roundcube.tar.gz && rm -R /Library/Server/Web/Data/Sites/Default/roundcube.tar.gz || echo PASSED';

 //!!!!!!!!! WEBMAIL !!!!!!!
 $cmd[]['rsh']='echo INSTALUJE WEBMAILA';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/ || exit 1
 wget http://sourceforge.net/projects/roundcubemail/files/roundcubemail/0.9.1/roundcubemail-0.9.1.tar.gz/download -O roundcube.tar.gz || exit 1';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/ || exit 1
 tar -zxpvf roundcube.tar.gz || exit 1';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/ || exit 1
mv roundcubemail* webmail  || exit 1 ';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/webmail || exit 1 
chown _www temp/ || exit 1 
chown _www logs/ || exit 1 
';
 $cmd[]['scp_root']=array('/Library/Server/Web/Data/Sites/Default/webmail/loginFromSE.php',' /Library/Server/Web/Data/Sites/Default/webmail/');
 //ustalenie domyslnych identities na webmailu po zalogowaniu wlasciwych dla domeny
 $cmd[]['rsh']='test -n "'.$SERVER_ADDRESS_SHORT.'" && sed -i.bak "s/@DOMAIN_TO_EDIT/@'.$SERVER_ADDRESS_SHORT.'/"  /Library/Server/Web/Data/Sites/Default/webmail/loginFromSE.php'; 
 $cmd[]['rsh']='test -n "'.$SERVER_ADDRESS.'" && sed -i.bak "s/@DOMAIN_TO_EDIT/@'.$SERVER_ADDRESS.'/"  /Library/Server/Web/Data/Sites/Default/webmail/loginFromSE.php'; 
 $cmd[]['rsh']='sed -i.bak "s/\/\/\\\\\$RCMAIL->db->query(/\\\\\$RCMAIL->db->query(/"  /Library/Server/Web/Data/Sites/Default/webmail/loginFromSE.php'; 
// $cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff/OfflineIMAP-offlineimap-v6.5.5-0-g8bc2f35.tar',' /Library/Server/Web/Data/Sites/Default/');
// $cmd[]['rsh']='tar -zxpvf /Library/Server/Web/Data/Sites/Default/OfflineIMAP-offlineimap-v6.5.5-0-g8bc2f35.tar* -C /Library/Server/Web/Data/Sites/Default/'; 
 $cmd[]['rsh']='chmod +a "_www allow writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,add_file,add_subdirectory,delete_child,list,search,file_inherit,directory_inherit" /Library/WebServer/';
// $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/OfflineIMAP-offlineimap-8bc2f35/'; 
// $cmd[]['rsh']='touch /var/root/.offlineimaprc'; 
// $cmd[]['rsh']='port install db44'; //do icingi/nconfa
// $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/isync-1.0.6 && ./configure'; 


 $cmd[]['rsh']='mysqladmin  -uroot -p'.$ADMIN_USERNAME_PASSWD.' create webmail';
 $cmd[]['rsh']='echo "GRANT ALL PRIVILEGES ON webmail.* to \'webmail\'@\'127.0.0.1\' IDENTIFIED BY \'webmail666\'  WITH GRANT OPTION; flush privileges;" |mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.'';
 $cmd[]['rsh']='echo "GRANT ALL PRIVILEGES ON webmail.* to \'webmail\'@\'localhost\' IDENTIFIED BY \'webmail666\'  WITH GRANT OPTION; flush privileges;" |mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.'';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/webmail || exit 1
  cat ./SQL/mysql.initial.sql | mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.' -h 127.0.0.1 -Dwebmail || exit 1 ';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/webmail || exit 1
  rm  -r installer/ || exit 1';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/webmail || exit 1
  chown -R _www ../webmail || exit 1';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/webmail || exit 1
  chown -R _www ../webmail || exit 1';

 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/webmail || exit 1
 
 echo "<?
\\\\\$rcmail_config = array();
\\\\\$rcmail_config[\'debug_level\'] = 1;
\\\\\$rcmail_config[\'log_driver\'] = \'file\';
\\\\\$rcmail_config[\'log_date_format\'] = \'d-M-Y H:i:s O\';
\\\\\$rcmail_config[\'syslog_id\'] = \'roundcube\';
\\\\\$rcmail_config[\'syslog_facility\'] = LOG_USER;
\\\\\$rcmail_config[\'smtp_log\'] = true;
\\\\\$rcmail_config[\'log_logins\'] = false;
\\\\\$rcmail_config[\'log_session\'] = false;
\\\\\$rcmail_config[\'sql_debug\'] = false;
\\\\\$rcmail_config[\'imap_debug\'] = false;
\\\\\$rcmail_config[\'ldap_debug\'] = false;
\\\\\$rcmail_config[\'smtp_debug\'] = false;
\\\\\$rcmail_config[\'default_host\'] = \'127.0.0.1\';
\\\\\$rcmail_config[\'default_port\'] = 143;
\\\\\$rcmail_config[\'imap_auth_type\'] = PLAIN;
\\\\\$rcmail_config[\'imap_delimiter\'] = null;
\\\\\$rcmail_config[\'imap_ns_personal\'] = null;
\\\\\$rcmail_config[\'imap_ns_shared\']   = null;
\\\\\$rcmail_config[\'imap_force_caps\'] = false;
\\\\\$rcmail_config[\'imap_force_lsub\'] = false;
\\\\\$rcmail_config[\'imap_force_ns\'] = false;
\\\\\$rcmail_config[\'imap_timeout\'] = 0;
\\\\\$rcmail_config[\'imap_auth_cid\'] = null;
\\\\\$rcmail_config[\'imap_auth_pw\'] = null;
\\\\\$rcmail_config[\'imap_cache\'] = null;
\\\\\$rcmail_config[\'messages_cache\'] = false;
\\\\\$rcmail_config[\'smtp_server\'] = \'127.0.0.1\';
\\\\\$rcmail_config[\'smtp_port\'] = 25;
\\\\\$rcmail_config[\'smtp_user\'] = \'\';
\\\\\$rcmail_config[\'smtp_pass\'] = \'\';
\\\\\$rcmail_config[\'smtp_auth_type\'] = \'\';
\\\\\$rcmail_config[\'smtp_auth_cid\'] = null;
\\\\\$rcmail_config[\'smtp_auth_pw\'] = null;
\\\\\$rcmail_config[\'smtp_helo_host\'] = \'\';
\\\\\$rcmail_config[\'smtp_timeout\'] = 0;
\\\\\$rcmail_config[\'enable_installer\'] = false;
\\\\\$rcmail_config[\'dont_override\'] = array();
\\\\\$rcmail_config[\'support_url\'] = \'\';
\\\\\$rcmail_config[\'skin_logo\'] = null;
\\\\\$rcmail_config[\'auto_create_user\'] = true;
\\\\\$rcmail_config[\'user_aliases\'] = false;
\\\\\$rcmail_config[\'log_dir\'] = \'logs/\';
\\\\\$rcmail_config[\'temp_dir\'] = \'temp/\';
\\\\\$rcmail_config[\'message_cache_lifetime\'] = \'10d\';
\\\\\$rcmail_config[\'force_https\'] = false;
\\\\\$rcmail_config[\'use_https\'] = false;
\\\\\$rcmail_config[\'login_autocomplete\'] = 0;
\\\\\$rcmail_config[\'login_lc\'] = 2;
\\\\\$rcmail_config[\'skin_include_php\'] = false;
\\\\\$rcmail_config[\'display_version\'] = false;
\\\\\$rcmail_config[\'session_lifetime\'] = 10;
\\\\\$rcmail_config[\'session_domain\'] = \'\';
\\\\\$rcmail_config[\'session_name\'] = null;
\\\\\$rcmail_config[\'session_path\'] = null;
\\\\\$rcmail_config[\'session_storage\'] = \'db\';
\\\\\$rcmail_config[\'ip_check\'] = false;
\\\\\$rcmail_config[\'referer_check\'] = false;
\\\\\$rcmail_config[\'x_frame_options\'] = \'sameorigin\';
\\\\\$rcmail_config[\'des_key\'] = \'+oEkJSMxbrsl%C!J1f3AjJK-\';
\\\\\$rcmail_config[\'username_domain\'] = \'\';
\\\\\$rcmail_config[\'mail_domain\'] = \'\';
\\\\\$rcmail_config[\'password_charset\'] = \'ISO-8859-1\';
\\\\\$rcmail_config[\'sendmail_delay\'] = 0;
\\\\\$rcmail_config[\'max_recipients\'] = 0; 
\\\\\$rcmail_config[\'max_group_members\'] = 0; 
\\\\\$rcmail_config[\'useragent\'] = \'Roundcube Webmail/\'.RCMAIL_VERSION;
\\\\\$rcmail_config[\'product_name\'] = \'webmail\';
\\\\\$rcmail_config[\'include_host_config\'] = false;
\\\\\$rcmail_config[\'generic_message_footer\'] = \'\';
\\\\\$rcmail_config[\'generic_message_footer_html\'] = \'\';
\\\\\$rcmail_config[\'http_received_header\'] = false;
\\\\\$rcmail_config[\'http_received_header_encrypt\'] = false;
\\\\\$rcmail_config[\'mail_header_delimiter\'] = NULL;
\\\\\$rcmail_config[\'line_length\'] = 72;
\\\\\$rcmail_config[\'send_format_flowed\'] = true;
\\\\\$rcmail_config[\'mdn_use_from\'] = false;
\\\\\$rcmail_config[\'identities_level\'] = 0;
\\\\\$rcmail_config[\'client_mimetypes\'] = null;  # null == default
\\\\\$rcmail_config[\'mime_magic\'] = null;
\\\\\$rcmail_config[\'mime_types\'] = null;
\\\\\$rcmail_config[\'im_identify_path\'] = null;
\\\\\$rcmail_config[\'im_convert_path\'] = null;
\\\\\$rcmail_config[\'image_thumbnail_size\'] = 240;
\\\\\$rcmail_config[\'contact_photo_size\'] = 160;
\\\\\$rcmail_config[\'email_dns_check\'] = false;
\\\\\$rcmail_config[\'no_save_sent_messages\'] = false;
\\\\\$rcmail_config[\'plugins\'] = array();
\\\\\$rcmail_config[\'message_sort_col\'] = \'\';
\\\\\$rcmail_config[\'message_sort_order\'] = \'DESC\';
\\\\\$rcmail_config[\'list_cols\'] = array(\'subject\', \'status\', \'fromto\', \'date\', \'size\', \'flag\', \'attachment\');
\\\\\$rcmail_config[\'language\'] = null;
\\\\\$rcmail_config[\'date_format\'] = \'Y-m-d\';
\\\\\$rcmail_config[\'date_formats\'] = array(\'Y-m-d\', \'d-m-Y\', \'Y/m/d\', \'m/d/Y\', \'d/m/Y\', \'d.m.Y\', \'j.n.Y\');
\\\\\$rcmail_config[\'time_format\'] = \'H:i\';
\\\\\$rcmail_config[\'time_formats\'] = array(\'G:i\', \'H:i\', \'g:i a\', \'h:i A\');
\\\\\$rcmail_config[\'date_short\'] = \'D H:i\';
\\\\\$rcmail_config[\'date_long\'] = \'Y-m-d H:i\';
\\\\\$rcmail_config[\'drafts_mbox\'] = \'Drafts\';
\\\\\$rcmail_config[\'junk_mbox\'] = \'Junk\';
\\\\\$rcmail_config[\'sent_mbox\'] = \'Sent\';
\\\\\$rcmail_config[\'trash_mbox\'] = \'Trash\';
\\\\\$rcmail_config[\'default_folders\'] = array(\'INBOX\', \'Drafts\', \'Sent\', \'Junk\', \'Trash\');
\\\\\$rcmail_config[\'create_default_folders\'] = false;
\\\\\$rcmail_config[\'protect_default_folders\'] = true;
\\\\\$rcmail_config[\'quota_zero_as_unlimited\'] = false;
\\\\\$rcmail_config[\'enable_spellcheck\'] = true;
\\\\\$rcmail_config[\'spellcheck_dictionary\'] = false;
\\\\\$rcmail_config[\'spellcheck_engine\'] = \'googie\';
\\\\\$rcmail_config[\'spellcheck_uri\'] = \'\';
\\\\\$rcmail_config[\'spellcheck_languages\'] = NULL;
\\\\\$rcmail_config[\'spellcheck_ignore_caps\'] = false;
\\\\\$rcmail_config[\'spellcheck_ignore_nums\'] = false;
\\\\\$rcmail_config[\'spellcheck_ignore_syms\'] = false;
\\\\\$rcmail_config[\'recipients_separator\'] = \',\';
\\\\\$rcmail_config[\'max_pagesize\'] = 200;
\\\\\$rcmail_config[\'min_refresh_interval\'] = 60;
\\\\\$rcmail_config[\'upload_progress\'] = false;
\\\\\$rcmail_config[\'undo_timeout\'] = 0;
\\\\\$rcmail_config[\'address_book_type\'] = \'sql\';
\\\\\$rcmail_config[\'ldap_public\'] = array();

\\\\\$rcmail_config[\'ldap_public\'][\'localhost\'] = array(
  \'name\' => \'localhost\',
  \'hosts\' => array(\'127.0.0.1\'),
  \'port\' => 389,
  \'base_dn\' => \''.$SERVER_ADDRESS_LDAP_DC.'\',
  \'search_base_dn\' => \'\',
  \'required_fields\' => array(\'cn\', \'sn\', \'mail\'),
  \'filter\' => \'(&(!(uid=_*))(mail=*@*))\',
  \'search_dn_default\' => \'\',
  \'LDAP_Object_Classes\' => array(\'top\', \'inetOrgPerson\'),
  \'search_fields\' => array(\'givenName\',\'cn\',\'sn\',\'mail\'),
  \'fieldmap\' => array(
   \'name\'        => \'cn\',
   \'surname\'     => \'sn\',
   \'firstname\'   => \'givenName\',
   \'email\'       => \'mail\'
  ),
  \'LDAP_rdn\' => \'mail\',
  \'ldap_version\' => 3,
  \'scope\' => \'sub\',
  \'fuzzy_search\' => true
);

\\\\\$rcmail_config[\'autocomplete_addressbooks\'] = array(\'sql\',\'localhost\');
\\\\\$rcmail_config[\'autocomplete_min_length\'] = 1;
\\\\\$rcmail_config[\'autocomplete_threads\'] = 0;
\\\\\$rcmail_config[\'autocomplete_max\'] = 15;
\\\\\$rcmail_config[\'address_template\'] = \'{street}<br/>{locality} {zipcode}<br/>{country} {region}\';
\\\\\$rcmail_config[\'addressbook_search_mode\'] = 0;
\\\\\$rcmail_config[\'default_charset\'] = \'ISO-8859-1\';
\\\\\$rcmail_config[\'skin\'] = \'larry\';
\\\\\$rcmail_config[\'mail_pagesize\'] = 50;
\\\\\$rcmail_config[\'addressbook_pagesize\'] = 50;
\\\\\$rcmail_config[\'addressbook_sort_col\'] = \'surname\';
\\\\\$rcmail_config[\'addressbook_name_listing\'] = 0;
\\\\\$rcmail_config[\'timezone\'] = \'auto\';
\\\\\$rcmail_config[\'prefer_html\'] = true;
\\\\\$rcmail_config[\'show_images\'] = 0;
\\\\\$rcmail_config[\'message_extwin\'] = false;
\\\\\$rcmail_config[\'compose_extwin\'] = false;
\\\\\$rcmail_config[\'htmleditor\'] = 0;
\\\\\$rcmail_config[\'prettydate\'] = true;
\\\\\$rcmail_config[\'draft_autosave\'] = 300;
\\\\\$rcmail_config[\'preview_pane\'] = false;
\\\\\$rcmail_config[\'preview_pane_mark_read\'] = 0;
\\\\\$rcmail_config[\'logout_purge\'] = false;
\\\\\$rcmail_config[\'logout_expunge\'] = false;
\\\\\$rcmail_config[\'inline_images\'] = true;
\\\\\$rcmail_config[\'mime_param_folding\'] = 0;
\\\\\$rcmail_config[\'skip_deleted\'] = false;
\\\\\$rcmail_config[\'read_when_deleted\'] = true;
\\\\\$rcmail_config[\'flag_for_deletion\'] = false;
\\\\\$rcmail_config[\'refresh_interval\'] = 60;
\\\\\$rcmail_config[\'check_all_folders\'] = false;
\\\\\$rcmail_config[\'display_next\'] = true;
\\\\\$rcmail_config[\'autoexpand_threads\'] = 0;
\\\\\$rcmail_config[\'reply_mode\'] = 0;
\\\\\$rcmail_config[\'strip_existing_sig\'] = true;
\\\\\$rcmail_config[\'show_sig\'] = 1;
\\\\\$rcmail_config[\'force_7bit\'] = false;
\\\\\$rcmail_config[\'delete_always\'] = false;
\\\\\$rcmail_config[\'delete_junk\'] = false;
\\\\\$rcmail_config[\'mdn_requests\'] = 0;
\\\\\$rcmail_config[\'mdn_default\'] = 0;
\\\\\$rcmail_config[\'dsn_default\'] = 0;
\\\\\$rcmail_config[\'reply_same_folder\'] = false;
\\\\\$rcmail_config[\'forward_attachment\'] = false;
\\\\\$rcmail_config[\'default_addressbook\'] = null;
\\\\\$rcmail_config[\'spellcheck_before_send\'] = false;
\\\\\$rcmail_config[\'autocomplete_single\'] = false;
\\\\\$rcmail_config[\'default_font\'] = \'\'; 
" > config/main.inc.php 
 ';

$cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/webmail || exit 1
echo "<?
\\\\\$rcmail_config = array();
\\\\\$rcmail_config[\'db_dsnw\'] = \'mysql://webmail:webmail666@127.0.0.1/webmail\';
\\\\\$rcmail_config[\'db_dsnr\'] = \'\';
\\\\\$rcmail_config[\'db_persistent\'] = false;

// you can define specific table names used to store webmail data
\\\\\$rcmail_config[\'db_table_users\'] = \'users\';
\\\\\$rcmail_config[\'db_table_identities\'] = \'identities\';
\\\\\$rcmail_config[\'db_table_contacts\'] = \'contacts\';
\\\\\$rcmail_config[\'db_table_contactgroups\'] = \'contactgroups\';
\\\\\$rcmail_config[\'db_table_contactgroupmembers\'] = \'contactgroupmembers\';
\\\\\$rcmail_config[\'db_table_session\'] = \'session\';
\\\\\$rcmail_config[\'db_table_cache\'] = \'cache\';
\\\\\$rcmail_config[\'db_table_cache_index\'] = \'cache_index\';
\\\\\$rcmail_config[\'db_table_cache_thread\'] = \'cache_thread\';
\\\\\$rcmail_config[\'db_table_cache_messages\'] = \'cache_messages\';
\\\\\$rcmail_config[\'db_table_dictionary\'] = \'dictionary\';
\\\\\$rcmail_config[\'db_table_searches\'] = \'searches\';
\\\\\$rcmail_config[\'db_table_system\'] = \'system\';

// you can define specific sequence names used in PostgreSQL
\\\\\$rcmail_config[\'db_sequence_users\'] = \'user_ids\';
\\\\\$rcmail_config[\'db_sequence_identities\'] = \'identity_ids\';
\\\\\$rcmail_config[\'db_sequence_contacts\'] = \'contact_ids\';
\\\\\$rcmail_config[\'db_sequence_contactgroups\'] = \'contactgroups_ids\';
\\\\\$rcmail_config[\'db_sequence_searches\'] = \'search_ids\';
// end db config file
" > config/db.inc.php';

//!!!!!!!!! EOF WEBMAIL !!!!!!!



return $cmd;
}
 

function INSTALL_GETCOMMANDS_SE($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD,$BACKUP_USB_DEVICE,$SERVER_VERSION) {
 $cmd[]['rsh']='test -d /Library/Server/Web/Data/Sites/Default/SE/ && rm -R /Library/Server/Web/Data/Sites/Default/SE || echo PASSED';
 //!!! Instalacja i generowanie konfiga - kopiowanie
  $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/SE'; //zalozenie katalogow


  $cmd[]['scp_root']=array($INSTALL_ROOT.'/budynki*','/Library/Server/Web/Data/Sites/Default/SE/');
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/favicon.ico','/Library/Server/Web/Data/Sites/Default/SE/');
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/icon','/Library/Server/Web/Data/Sites/Default/SE/');
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/index*','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/odt2xhtml*','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/procesy5*','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/przypomnij.php','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/se-lib','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/session-expire.php','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/stuff','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/superedit*','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/webdav','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['rsh']='mkdir /Library/Server/Web/Data/Sites/Default/SE/config';
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/config/.cnf--column_init*','/Library/Server/Web/Data/Sites/Default/SE/config/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/config/.cnf--external_ids.ini.php*','/Library/Server/Web/Data/Sites/Default/SE/config/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/config/.cnf--external_ids.ini.php*','/Library/Server/Web/Data/Sites/Default/SE/config/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/.config.php','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/procesy','/Library/Server/Web/Data/Sites/Default/SE/');  
  $cmd[]['scp_root']=array($INSTALL_ROOT.'/bash_sync_perms.php','/Library/Server/Web/Data/Sites/Default/SE/');

  //! .cnf--default_db
  $cmd[]['rsh']=' echo ";<?php
;die(); // For further security
;// default DB

type=\"mysql\"
host=\"127.0.0.1\"
port=\"3306\"
user=\"root\"
pass=\"'.$ADMIN_USERNAME_PASSWD.'\"
database=\"'.$REMOTE_FOLDER_ROOT.'\"

" > /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_db-'.$SERVER_ADDRESS.'.ini.php
';
 //! .cnf--folders
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT;
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/PISMA';
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/DEVICES'; 
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/PROJEKTY';
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/SES_PROCESY5_A';
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/CRM_PROCES';
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/DRUKI';
 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/ADMIN_USERS';

 $cmd[]['rsh']=' mkdir -p /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'/SKANY'; //@2014-01-18 - should be added
 $cmd[]['rsh']=' chmod 0755 /Library/Server/Web/Data/Sites/Default/PLIKI/';
 $cmd[]['rsh']=' chmod -R +a "_www allow writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,add_file,add_subdirectory,delete_child,list,search,file_inherit,directory_inherit" /Library/Server/Web/Data/Sites/Default/PLIKI';
//! TODO te komendy nie działają @2013-10-15 - trzeba ruszyc recznie z GUI
 $cmd[]['rsh']=' sharing -l |grep '.$REMOTE_FOLDER_ROOT.' || sharing -a /Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.' -A '.$REMOTE_FOLDER_ROOT.' -s 101' ; //uruchomienie sharingu smb/afp dla udzialu
 $cmd[]['rsh']=' serveradmin start afp' ; //uruchomienie sharingu smb/afp dla udzialu
 $cmd[]['rsh']=' serveradmin start smb' ; //uruchomienie sharingu smb/afp dla udzialu
 $cmd[]['rsh']=' serveradmin start sharing' ; //uruchomienie sharingu smb/afp dla udzialu
//EOF TODO te komendy nie dzialaja
//@2014-01-18 bindera: aktualizacja konfigu do plikow zgodna z zalozeniami korespondencji w podfolderach
 $cmd[]['rsh']=' echo ";<?php
;die(); // For further security

[root_points]
mount_point=\"/Library/Server/Web/Data/Sites/Default/PLIKI/'.$REMOTE_FOLDER_ROOT.'\"
share_point=\"//'.$SERVER_ADDRESS.'/'.$REMOTE_FOLDER_ROOT.'\"
www_share_point=\"https://'.$SERVER_ADDRESS.'/PLIKI/'.$REMOTE_FOLDER_ROOT.'\"

[m_dist_files_types]
ARTYKUL=\"ARTYKUL\"   
CERT_CE=\"CERT_CE\"
CERTYFIKAT=\"CERTYFIKAT\"
DEKLARACJA=\"DEKLARACJA\"
DOK_POWYK=\"DOK_POWYK\"
DRUK=\"DRUK\"
;//ETYKIETA=\"ETYKIETA\"
FAKTURA=\"FAKTURA\"
FIRMWARE=\"FIRMWARE\"
;//INSTRUKCJA=\"INSTRUKCJA\"
;//INSTRUKCJA_PL=\"INSTRUKCJA_PL\"
;//INSTRUKCJA_PL_DRUK=\"INSTRUKCJA_PL_DRUK\"
;//KARTA=\"KARTA\"
INNE=\"INNE\"
KARTA_GWARANCYJNA=\"KARTA_GWARANCYJNA\"
;//KOMPLETACJA=\"KOMPLETACJA\"
LIST_PRZEWOZ=\"LIST_PRZEWOZ\"
NOTATKA=\"NOTATKA\"
OFERTA=\"OFERTA\"
;//OVERLAY=\"OVERLAY\"
PISMO=\"PISMO\"
POLISA=\"POLISA\"
PREZENTACJA=\"PREZENTACJA\"
PROJEKT=\"PROJEKT\"
PROJEKT_BUD=\"PROJEKT_BUD\"
PROJEKT_GRAF=\"PROJEKT_GRAF\"
PROTOKOL=\"PROTOKOL\"
PROTOK_ODB_TOWAR=\"PROTOK_ODB_TOWAR\"
REKLAMACJA=\"REKLAMACJA\"
RYS_TECHNICZNY=\"RYS_TECHNICZNY\"
SPEC_WYROBU=\"SPEC_WYROBU\"
SOFT_CD=\"SOFT_CD\"
SWIAD_JAKOSCI=\"SWIAD_JAKOSCI\"
TODO=\"TODO\"
UMOWA=\"UMOWA\"
UCHWALA=\"UCHWALA\"
UCHWALA_WWW=\"UCHWALA_WWW\"
UZGODNIENIE=\"UZGODNIENIE\"
WEZW_DO_ZAPL=\"WEZW_DO_ZAPL\"
WWW_DOKUMENTY=\"WWW_DOKUMENTY\"
WWW_PRACA=\"WWW_PRACA\"
WZORZEC=\"WZORZEC\"
WNIOSEK=\"WNIOSEK\"
WNIOSEK_URLOP=\"WNIOSEK_URLOP\"
WYD_MAGAZYN=\"WYD_MAGAZYN\"
WYCENA=\"WYCENA\"
ZDJECIE=\"ZDJECIE\"
ZDJECIE_HI=\"ZDJECIE_HI\"
ZWOLNIENIE_LEK=\"ZWOLNIENIE_LEK\"
ZAMOWIENIE=\"ZAMOWIENIE\"

[default_COLUMN]
mount_point=\"default\";
share_point=\"default\"
www_share_point=\"default\"
LOOKAT_NEGFILE_LOOK_REGEX=\"/<VARNAME>./\"
LOOKAT_NEGFILE_VARNAME=\"ID\"
LOOKAT_FOLDER_LOOK_REGEX=\"/../\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_M_DIST_FILES_INDEXNAME=\"ID\"



[ADMIN_USERS_COLUMN]
mount_point=\"ADMIN_USERS\"
share_point=\"ADMIN_USERS\"
www_share_point=\"ADMIN_USERS\"
LOOKAT_FOLDER_LOOK_GLOB=\"<VARNAME>.*\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_FORMAT=\"<VARNAME1>.<VARNAME2>\"
DEST_FOLDER_VARNAME1=\"ID\"
DEST_FOLDER_VARNAME2=\"ADM_NAME\"


[CRM_LISTA_ZASOBOW_COLUMN]
mount_point=\"DRUKI\"
share_point=\"DRUKI\"
www_share_point=\"DRUKI\"
LOOKAT_FOLDER_LOOK_GLOB=\"<VARNAME>.*\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_FORMAT=\"<VARNAME1>.<VARNAME2>\"
DEST_FOLDER_VARNAME1=\"ID\"
DEST_FOLDER_VARNAME2=\"DESC\"


[CRM_PROCES_COLUMN]
mount_point=\"CRM_PROCES\"
share_point=\"CRM_PROCES\"
www_share_point=\"CRM_PROCES\"
LOOKAT_FOLDER_LOOK_GLOB=\"<VARNAME>.*\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_FORMAT=\"<VARNAME1>.<VARNAME2>\"
DEST_FOLDER_VARNAME1=\"ID\"
DEST_FOLDER_VARNAME2=\"DESC\"


[CRM_PROCES_COLUMN]
mount_point=\"PROCESY\"
share_point=\"PROCESY\"
www_share_point=\"PROCESY\"
LOOKAT_FOLDER_LOOK_GLOB=\"<VARNAME>.*\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_FORMAT=\"<VARNAME1>.<VARNAME2>\"
DEST_FOLDER_VARNAME1=\"ID\"
DEST_FOLDER_VARNAME2=\"DESC_PL\"

[IN7_MK_BAZA_DYSTRYBUCJI_COLUMN]
mount_point=\"PROJEKTY\"
share_point=\"PROJEKTY\"
www_share_point=\"PROJEKTY\"
LOOKAT_FOLDER_LOOK_GLOB=\"<VARNAME>.*\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_FORMAT=\"<VARNAME1>.<VARNAME2>\"
DEST_FOLDER_VARNAME1=\"ID\"
DEST_FOLDER_VARNAME2=\"M_DIST_DESC\"

[IN7_DZIENNIK_KORESP_COLUMN]
mount_point=\"PISMA\"
share_point=\"PISMA\"  
www_share_point=\"PISMA\"
LOOKAT_FOLDER_LOOK_GLOB=\"<VARNAME>.*\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_FORMAT=\"<VARNAME1>.<VARNAME2>-<VARNAME3>\"
DEST_FOLDER_VARNAME1=\"ID\"
DEST_FOLDER_VARNAME2=\"K_OD_KOGO\"
DEST_FOLDER_VARNAME3=\"K_ZAWARTOS\"

[DEVICES_COLUMN]
mount_point=\"DEVICES\"
share_point=\"DEVICES\"
www_share_point=\"DEVICES\"
LOOKAT_FOLDER_LOOK_GLOB=\"<VARNAME>.*\"
LOOKAT_FOLDER_VARNAME=\"ID\"
DEST_FOLDER_FORMAT=\"<VARNAME1>.<VARNAME2>_<VARNAME3>\"
DEST_FOLDER_VARNAME1=\"ID\"
DEST_FOLDER_VARNAME2=\"T_PRODUCER\"
DEST_FOLDER_VARNAME3=\"S_HW\"

[SCANS_COLUMN]
mount_point=\"SKANY\"
share_point=\"SKANY\"
www_share_point=\"SKANY\"


" > /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--folders-'.$SERVER_ADDRESS.'.ini.php';
//! .config_domena_.php
//LDAP 
$cmd[]['rsh']='echo ";<?php
;die(); // For further security
;// default LDAP

version=\"3\"
host=\"'.$SERVER_ADDRESS.'\"
;//port=\"\"
user=\"'.$ADMIN_USERNAME_DIRECTORY.'\"
pass=\"'.$ADMIN_USERNAME_PASSWD.'\"
base_dn=\"'.$SERVER_ADDRESS_LDAP_DC.'\"
" > /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_ldap-'.$SERVER_ADDRESS.'.ini.php
';

$cmd[]['rsh']='echo "<?php

//$DATABASE_ROOT_ZASOB_ID=36; //numer zasobu dla bazy SQL w zasobach, pod nim powinny byc bezposrednio tabele, potem komorki
 \\$CRM_IMPORT_TRANSLATE[\'CRM_LISTA_ZASOBOW\'][36]=2; //baza danych[36] na baze danych zainicjalizowana
 \\$CRM_IMPORT_TRANSLATE[\'CRM_LISTA_ZASOBOW\'][14]=1; //server[14]  na zainicjalizowany [1] tutaj definiujemy z zasob
   \\$CNF_ZASOB[\'biallnet_crm_profiles\'][\'INTERFACE_ADDR\'] = \'se.dev.webone.pl\';
   \\$CNF_ZASOB[\'biallnet_crm_profiles\'][\'SQL_USER\'] = \'crmexportprof\';
   \\$CNF_ZASOB[\'biallnet_crm_profiles\'][\'SQL_USER_PASS\'] = \'crmexportprof\';
   \\$CNF_ZASOB[\'biallnet_crm_profiles\'][\'SQL_DATABASE\'] = \'SES_USERS2\';

" > /Library/Server/Web/Data/Sites/Default/SE/config/.config-'.$SERVER_ADDRESS.'.php';

  $cmd[]['rsh']='echo "<?php header(\'Location: https://'.$SERVER_ADDRESS.'/SE\'); ?>" > /Library/Server/Web/Data/Sites/Default/index.php';  
   
//$cmd[]['rsh']='uruchomic na serwerze open directory i dodac tam konta roota';
//$cmd[]['rsh']='skonfigurowac poczte i wlaczyc';
//$cmd[]['rsh']='skonfigurowac pliki i wlaczyc - razem ze skanami';
//$cmd[]['rsh']='uruchomic i skonfiugorowac kalendarze (haslo do wysylki poczty musi dzialac i byc konto takie dodane)';
 $cmd[]['rsh']='sed -i.bak "s/short_open_tag = Off/short_open_tag = On/"  /etc/php.ini '; 
 $cmd[]['rsh']='sed -i.bak "s/memory_limit =.*/memory_limit = 428M/"  /etc/php.ini '; 
 $cmd[]['rsh']='sed -i.bak "s/session.gc_maxlifetime =.*/session.gc_maxlifetime = 3600/"  /etc/php.ini '; 
 $cmd[]['rsh']='sed -i.bak "s/upload_max_filesize =.*/upload_max_filesize = 120M/"  /etc/php.ini '; 
 $cmd[]['rsh']='sed -i.bak "s/allow_url_include = Off/allow_url_include = On/"  /etc/php.ini'; 

$cmd[]['rsh']='serveradmin settings web:defaultSite:enableServerSideIncludes = yes';
$cmd[]['rsh']='serveradmin settings web:defaultSite:allowAllOverrides = yes';

$cmd[]['rsh']='serveradmin start web';



  $cmd[]['rsh']=' echo ";<?php
;die(); // For further security
;// default DB

type=\"mysql\"
host=\"se.dev.webone.pl\"
port=\"3306\"
user=\"crmexportprof\"
pass=\"crmexportprof\"
database=\"SES_USERS2\"

" > /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--import_db-'.$SERVER_ADDRESS.'.ini.php
'; //todo zmienic to wczesniej


 $cmd[]['scp_root']=array(''.$INSTALL_ROOT.'/.config_base_structure.php','/Library/Server/Web/Data/Sites/Default/SE/');   //todo do przeniesienia wyzej - struktura musi byc wygenerowana
 $cmd[]['rsh']='mysqladmin  -uroot -p'.$ADMIN_USERNAME_PASSWD.' create '.$REMOTE_FOLDER_ROOT.' || echo passed' ; //todo przestawic wczesniej

 //! inicjalizacja bazy SQIX_STRUCTURE_DB_SYNC
  $cmd[]['scp_root']=array(''.$INSTALL_ROOT.'/.config_base_structure_dump.sql','/Library/Server/Web/Data/Sites/Default/SE/');   //todo do przeniesienia wyzej - struktura musi byc wygenerowana
  $cmd[]['rsh']='/opt/local/lib/mysql55/bin/mysql  -uroot -p'.$ADMIN_USERNAME_PASSWD.' '.$REMOTE_FOLDER_ROOT.' < /Library/Server/Web/Data/Sites/Default/SE/.config_base_structure_dump.sql'; //TODO powinno byc osobne miejsce do bazy i struktur bo kasuje to baze zamiast aktualizacji!


// TODO @2014-06-16 sprawdzic dodawanie struktur DB_STRUCTURES_CREATE - czy jest potrzebne - imho TAK
 $cmd[]['rsh']='php -r"include(\'/Library/Server/Web/Data/Sites/Default/SE/superedit-DB_PROCEDURES_CREATE.php\') ; DB_PROCEDURES_CREATE(); " '.$SERVER_ADDRESS.' '; 



 $cmd[]['rsh']=' echo " delete from ADMIN_USERS  where ADM_ACCOUNT=\''.$ADMIN_USERNAME_L1.'\'" |mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap
 $cmd[]['rsh']=' echo " delete from ADMIN_USERS  where ADM_ACCOUNT=\''.$ADMIN_USERNAME_DIRECTORY.'\'" |mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap

 $cmd[]['rsh']=' echo " insert into ADMIN_USERS (ADM_ACCOUNT,ADM_ADMIN_LEVEL,ADM_PASSWD) values (\''.$ADMIN_USERNAME_L1.'\',\'1\',\''.$ADMIN_USERNAME_L1_PASS.'\')" |mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap
 $cmd[]['rsh']=' echo " insert into ADMIN_USERS (ADM_ACCOUNT,ADM_ADMIN_LEVEL,ADM_PASSWD) values (\''.$ADMIN_USERNAME_DIRECTORY.'\',\'0\',\''.$ADMIN_USERNAME_PASSWD.'\')" |mysql -uroot -p'.$ADMIN_USERNAME_PASSWD.' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap

 
 /* @2014-03-10 these has been moved to create config_base_structure_dump.sql option - WYKONAJ_REFERENCYJNA_BAZE_DANYCH 
 $cmd[]['rsh']='php -r"include(\'/Library/Server/Web/Data/Sites/Default/SE/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'import_db\',\'default_db\',0,\'WYSLIJ_DO_BAZY\',\'SYNC_ZASOBY_STRUCTURES_FROM_CONFIG\'); " '.$SERVER_ADDRESS.' FILTR'; //todo pare razy trzaba powtarzac bo sa bledy
 $cmd[]['rsh']='php -r"include(\'/Library/Server/Web/Data/Sites/Default/SE/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'import_db\',\'default_db\',0,\'WYSLIJ_DO_BAZY\',\'CREATE_ZASOBY_DATABASE_DESC\'); " '.$SERVER_ADDRESS.' FILTR'; //@2013-10-15 staje recznie ? 
 $cmd[]['rsh']='php -r"include(\'/Library/Server/Web/Data/Sites/Default/SE/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'import_db\',\'default_db\',0,\'WYSLIJ_DO_BAZY\',\'FROM_ZASOBY_TO_ZASOBY\'); " '.$SERVER_ADDRESS.' %PISM%,%zasob%,%ADMINISTRACJA%wyposaz%'; //import procesow z tagami PISMO
 */ 
// $cmd[]['rsh']='php -r"include(\'/Library/Server/Web/Data/Sites/Default/SE/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'import_db\',\'default_db\',0,\'WYSLIJ_DO_BAZY\',\'FROM_ZASOBY_TO_ZASOBY\'); " '.$SERVER_ADDRESS.' %zasob%'; //import procesow z tagami PISMO
// $cmd[]['rsh']='php -r"include(\'/Library/Server/Web/Data/Sites/Default/SE/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'import_db\',\'default_db\',0,\'WYSLIJ_DO_BAZY\',\'FROM_ZASOBY_TO_ZASOBY\'); " '.$SERVER_ADDRESS.' %ADMINISTRACJA%'; //import procesow z tagami PISMO


//  $cmd[]='whoami';

//todo po zainstalowaniu bazy danych i zasobow trzeba zmienic nazwe zasobow naszych :
//[14]=biuro.biall-net.pl -> $SERVER_ADDRESS
//[4803]=vpn.biall-net.pl -> todo(adres IP lokalny w ramach vpn.$SERVER_ADDRESS)

 //! .cnf--default_db as id 2
  $cmd[]['rsh']=' echo ";<?php
;die(); // For further security
;// default DB

type=\"mysql\"
host=\"127.0.0.1\"
port=\"3306\"
user=\"root\"
pass=\"'.$ADMIN_USERNAME_PASSWD.'\"
database=\"'.$REMOTE_FOLDER_ROOT.'\"

" > /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--zasob_2-'.$SERVER_ADDRESS.'.ini.php
';
//! dodanie pierwszego usera ADMIN_USERNAME_L1 oraz diradmin

$cmd[]['rsh']=' php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php '.$SERVER_ADDRESS.' addToLaunchctl';
$cmd[]['rsh']=' launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist';



//odpalenie jabbera dla skroconej domeny servera:
$cmd[]['rsh']=' test -n "'.$SERVER_ADDRESS_SHORT.'" && serveradmin settings jabber:hostsCommaDelimitedString = "'.$SERVER_ADDRESS.','.$SERVER_ADDRESS_SHORT.'"';
//odpalenie jabbera::::
$cmd[]['rsh']=' serveradmin start jabber';
//odpalenie poczty  dla skroconej domeny servera:
$cmd[]['rsh']=' test -n "'.$SERVER_ADDRESS_SHORT.'" && serveradmin settings mail:postfix:virtual_domains:_array_index:0 = "'.$SERVER_ADDRESS_SHORT.'"';
//odpalenie poczty::::
//$cmd[]['rsh']=' serveradmin settings mail:postfix:message_size_limit_enabled = no'; //wylaczenie limitu poczty
$cmd[]['rsh']=' serveradmin settings mail:postfix:message_size_limit = 90485760 ' ; //limit 90 mega
$cmd[]['rsh']=' serveradmin start mail'; 
//TODO need to reedit MainConf for virtual domains in  /Library/Server/Mail/Config/postfix/main.cf (add hash:)
// virtual_alias_domains = $virtual_alias_maps hash:/Library/Server/Mail/Config/postfix/virtual_domains

$cmd[]['rsh']=' serveradmin start calendar';

return $cmd;
}


function INSTALL_GETCOMMANDS_MYADMIN($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD,$BACKUP_USB_DEVICE,$SERVER_VERSION) {
 $cmd[]['rsh']='test -d /Library/Server/Web/Data/Sites/Default/phpMyAdmin.tar.gz && rm -R /Library/Server/Web/Data/Sites/Default/phpMyAdmin.tar.gz || echo PASSED';
 $cmd[]['rsh']='test -d /Library/Server/Web/Data/Sites/Default/garbage && rm -R /Library/Server/Web/Data/Sites/Default/garbage || echo PASSED';
//! phpMyAdmin garbage
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/ || exit 1
 wget http://sourceforge.net/projects/phpmyadmin/files/phpMyAdmin/4.0.3/phpMyAdmin-4.0.3-all-languages.zip/download#\!md5\!4f71985c99e4e26e8b6b0b9165cafaad -O phpMyAdmin.tar.gz || exit 1 
 tar -zxpvf phpMyAdmin.tar.gz || exit 1 ';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/ || exit 1
 mv phpMyAdmin-* garbage || exit 1 ';
 $cmd[]['rsh']='cd /Library/Server/Web/Data/Sites/Default/garbage || exit 1 
echo "<?
\\\\\$i = 0;
\\\\\$i++;
\\\\\$cfg[\'Servers\'][\\\\\$i][\'verbose\'] = \''.$SERVER_ADDRESS.'\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'host\'] = \'127.0.0.1\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'port\'] = \'\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'socket\'] = \'\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'connect_type\'] = \'tcp\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'extension\'] = \'mysqli\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'auth_type\'] = \'cookie\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'user\'] = \'root\';
\\\\\$cfg[\'Servers\'][\\\\\$i][\'password\'] = \'\';
\\\\\$cfg[\'blowfish_secret\'] = \'51bc5c5b538ff0.23201365\';
\\\\\$cfg[\'DefaultLang\'] = \'en\';
\\\\\$cfg[\'ServerDefault\'] = 1;
\\\\\$cfg[\'UploadDir\'] = \'\';
\\\\\$cfg[\'SaveDir\'] = \'\';
?>
" > config.inc.php || exit 1 

 ';


return $cmd;
}

function INSTALL_GET_INIT_APPLE_XML($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$ADMIN_USERNAME_PASSWD,$SERVER_MOUNT_POINT_ROOT,$SERVER_ADDRESS,$SERVER_ADDRESS_LDAP_DC,$SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$ADMIN_USERNAME_L1,$ADMIN_USERNAME_L1_PASS,$ADMIN_USERNAME_DIRECTORY,$ADMIN_USERNAME_INITIAL_PASSWD)  {
return '"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\"
\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
<key>AdminUser</key>
<dict>
<key>exists</key>
<false/>
<key>name</key>
<string>'.$ADMIN_USERNAME.'</string>
<key>password</key>
<string>'.$ADMIN_USERNAME_INITIAL_PASSWD.'</string>
<key>realname</key>
<string>Administrator</string>
<key>uid</key>
<string>501</string>
</dict>
<key>ComputerName</key>
<string>'.$SERVER_ADDRESS.'</string>
Chapter 2 Installing Server Software and Finishing Basic Setup 23
<key>DS</key>
<dict>
<key>DSClientInfo</key>
<string>2 - NetInfo client - broadcast dhcp static -192.168.42.250
network</string>
<key>DSClientType</key>
<string>2</string>
<key>DSType</key>
<string>2 - directory client</string>
</dict>
<key>HostName</key>
<string>'.$SERVER_ADDRESS.'</string>
<key>InstallLanguage</key>
<string>Polish</string>
<key>Keyboard</key>
<dict>
<key>DefaultFormat</key>
<string>0</string>
<key>DefaultScript</key>
<string>0</string>
<key>ResID</key>
<integer>0</integer>
<key>ResName</key>
<string>U.S.</string>
<key>ScriptID</key>
<integer>0</integer>
</dict>
<key>ServicesAutoStart</key>
<dict>
<key>Apache</key>
<true/>
<key>File</key>
<true/>
<key>MacManager</key>
<true/>
<key>Mail</key>
<true/>
<key>Print</key>
<false/>
<key>QTSS</key>
<false/>
<key>WebDAV</key>
<false/>
</dict>
<key>TimeZone</key>
<string>Europe/Warsaw</string>
<key>VersionNumber</key>
<integer>1</integer>
</dict>
</plist>
"';

}

function tell_user_gui_error($msg) {
	return 'osascript -e "tell app \"System Events\" to display alert \"'.$msg.'\""';
}


function MakeCommand($command_id,$command,$installer_tmp,$installer_dir) {
	$file_sh="install.bash/".$command_id.".bash";
	$ins_sh="if [ -e ".$installer_tmp."/".$file_sh." ] ; then echo 'running:".$file_sh."'; ".$installer_tmp."/".$file_sh." && mv ".$installer_tmp."/".$file_sh." ".$installer_tmp."/install.executed_ok/ || {   osascript -e \"tell app \\\"System Events\\\" to display dialog \\\"`( echo 'Problem z komenda ".$installer_tmp."/".$file_sh."'  )`\\\"\" ; exit 1 ; } fi \n";
	$file=fopen($installer_dir."/".$file_sh, "w") or die('Cannot open file:  '.$installer_dir."/".$file_sh);
	fwrite($file,"#!/bin/sh\n".$command."\n");
	fclose($file);
	chmod($installer_dir."/".$file_sh, 0755); 
	//$ins_sh.=$command['rsh']."\n\r";
	DEBUG_S(-3,$command_id.':out of ',array($out,$exit));
	return $ins_sh;
}

function MAKE_PKG_COMPONENT($h,$installer_dir_tar,$installer_url,$installer_tmp,$cmd,$exit_file,$installer_dir_name,$pkg_id,$encrypt=false) {
		
	
		$UID=$h->ID;
		$installer_dir=$installer_dir_tar."/".$installer_dir_name; //pakowany katalog z instalatorem
	//	$installer_dir_tar="/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A"; //katalog CWD z ktorego budowana jest instalacja 
	//	$installer_url="http://biuro.biall-net.pl/PLIKI/SES_PROCESY5_A/"; //miejsce do sciagania instalatora przez WWW
	//	$installer_tmp="/tmp/pl.procesy5_".$UID.".".$h->SERVER_ADDRESS; //miejsce do ktorego installer odpakuje wszystko 
		exec('rm -Rf '.$installer_dir);
		mkdir($installer_dir,0777);
		mkdir($installer_dir."/install.bash",0777);
		mkdir($installer_dir."/install.executed_ok",0777);

		echo "<br> I mkdir ".$installer_dir;
		$ins_sh="#!/bin/sh \nshopt -s dotglob\n  echo 'instaluje i robie LS' >>/tmp/loginst \n ls >>/tmp/loginst \n declare PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin/:/Applications/Server.app/Contents/ServerRoot/usr/sbin/\n \n";
		foreach($cmd as $command_id=>$command) {	
		if(isset($command['rsh'])) {
	 		 	//$exec=SSH_COMMAND_REMOTE_CREATE($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,$command['rsh']);
	 		 	//DEBUG_S(-3,$command_id.':in '.htmlspecialchars(str_replace(array($h->ADMIN_USERNAME_PASSWD,str_replace('!','\!',$h->ADMIN_USERNAME_PASSWD)),'xxxxxx',$exec)),str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$exec));
				//flush();
	 			$out="";$exit="";
	 			//exec($exec,$out,$exit);
	 			$file_sh="install.bash/".$command_id.".bash";
	 			$ins_sh.="if [ -e ".$installer_tmp."/".$file_sh." ] ; then echo 'running:".$file_sh."'; ".$installer_tmp."/".$file_sh." && mv ".$installer_tmp."/".$file_sh." ".$installer_tmp."/install.executed_ok/ || {   osascript -e \"tell app \\\"System Events\\\" to display dialog \\\"`( echo 'Problem z komenda ".$installer_tmp."/".$file_sh."'  )`\\\"\" ; exit 1 ; } fi \n";
//	 			touch($file_sh);
	 			$file=fopen($installer_dir."/".$file_sh, "w") or die('Cannot open file:  '.$installer_dir."/".$file_sh);
	 			fwrite($file,"#!/bin/sh\n".$command['rsh']."\n");
	 			fclose($file);
	 			chmod($installer_dir."/".$file_sh, 0755); 
	 			//$ins_sh.=$command['rsh']."\n\r";
	 			DEBUG_S(-3,$command_id.':out of ',array($out,$exit));
	 			flush();
	 		} else if(isset($command['scp'])) {
	 			//$command_out='/opt/local/bin/sshpass -p '.$h->ADMIN_USERNAME_PASSWD.' /usr/bin/scp -v -3 -o StrictHostKeyChecking=no  '.$command['scp'][0].' '.$h->ADMIN_USERNAME.'@' . $h->SERVER_ADDRESS_IP . ':'.$command['scp'][1];
	 		 	//DEBUG_S(-3,$command_id.':in '.str_replace(array($h->ADMIN_USERNAME_PASSWD,str_replace('!','\!',$h->ADMIN_USERNAME_PASSWD)),'xxxxxx',$command_out),htmlspecialchars(str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$command_out)));
	 			//flush();
	 			mkdir($installer_dir."/".$command_id,0777);
	 			exec("cp ".$command['scp'][0]." ".$installer_dir."/".$command_id);
	 			$ins_sh.="mv ".$installer_tmp."/".$command_id."/* ".$command['scp'][1]." \n";
	 		
	 		} else if(isset($command['scp_root'])) {

				
				mkdir($installer_dir."/".$command_id,0777);
	 			exec("cp -r ".$command['scp_root'][0]." ".$installer_dir."/".$command_id);
	 			$ins_sh.="mv ".$installer_tmp."/".$command_id."/* ".$command['scp_root'][1]." \n";
				flush();
				//set_time_limit(36000);
	 		}
	 		$last_command_id=$command_id;
	 		
		}
		
			if(($encrypt)) {
	 			$exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b- --domain '.$h->SERVER_ADDRESS_SHORT.' -r *.php -x superedit-DB_PROCEDURES_CREATE.php';
	 			exec($exec,$out,$exit);$out="";$exit="";
	 			DEBUG_S(-3,'Zakodowanie kodu php/kompilacja z licencja i kluczem',array($exec,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
	 		}
	 			//usuniecie musi byc przed instalacja TODO
	 			//$last_command_id++;
	 			//
	 			//$ins_sh.=MakeCommand($command_id,"rm -Rf ".$installer_tmp,$installer_tmp,$installer_dir) ;
	 			
	 			/* klucz nie potrzebny do kodowania dla domeny
	 			$last_command_id++;
				mkdir($installer_dir."/".$last_command_id,0777);
				$exec='cd '.$installer_dir."/".$last_command_id.' &&  /Applications/SourceGuardian.app/Contents/MacOS/licgen --projid '.$h->ID.' --projkey '.$h->ID.' procesylicence_se';
	 			exec($exec,$out,$exit);$out="";$exit="";
	 			
	 			DEBUG_S(-3,'Wygenerowanie klucza dla klienta',array($exec,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
	 			$ins_sh.="mv ".$last_command_id."/* /Library/Server/Web/Data/Sites/Default/SE/ \n";
	 			*/

	 			mkdir($installer_dir."/scripts",0777);
	 			$file=fopen($installer_dir."/scripts/postinstall", "w") or die('Cannot open file:  '.$installer_dir."/scripts/postinstall");
	 			fwrite($file,$ins_sh."\n");
	 			fclose($file);
	 			
	 		//	die();
	 			chmod($installer_dir."/scripts/"."postinstall", 0755); $out="";$exit="";
	 		//	$exit_file=str_replace('.', '_', $UID.".".$h->SERVER_ADDRESS);
	 			
	 			//$exec="tar -C".$installer_dir_tar." -cz ".$UID.".".$h->SERVER_ADDRESS."  > ".$installer_dir_tar."/".$exit_file.".tar.gz";
	 			//exec($exec ,$out,$exit);
	 			//DEBUG_S(-3,'Tarowanie ',array($exec,$out,$exit),__FILE__,__FUNCTION__,__LINE__);

	 			$exec="cd ".$installer_dir_tar." && pkgbuild --scripts ".$installer_dir_name."/scripts/ --root ".$installer_dir_name." --identifier ".$pkg_id." --install-location ".$installer_tmp." ".$exit_file.".pkg" ;
	 			exec($exec ,$out,$exit);
	 			DEBUG_S(-3,'Robiebie pkg ',array($exec,$out,$exit),__FILE__,__FUNCTION__,__LINE__);


	 			echo "<hr><A href='{$installer_url}{$exit_file}.pkg'> ściągnij instalacje Procesy5 {$exit_file}.pkg</a>\n";
				//echo "<pre>Instalator skrypt TODO : \n".htmlspecialchars($ins_sh)."</pre>";

	//			return 0;

		
	}


function INSTALL_SES_PROCESY_A() {
  $INSTALL_ROOT='/Users/plabudda/se-dev-pl/SE'; //glowny katalog ze zrodlem SE
//DB::query('update SES_PROCESY5_A set INSTALL_COMPLETE_POINT=0 ');
//TODO@2013-10-05 - należy dorobić obsługę ADMIN_USERNAME_INITIAL_PASSWD aby jednorazowo się zalogowało i zmieniło na ADMIN_USERNAME_PASSWD (jakis hash) i jego juz potem wszedzie uzywalo - aby klient go nie znal

//	$cmd=INSTALL_GETCOMMANDS();
// $sql="select * from SES_PROCESY5_A where A_STATUS='NORMAL' and INSTALL_COMPLETE_POINT<'".count($cmd)."'";
 $sql="select * from SES_PROCESY5_A where A_STATUS='NORMAL' ";

 if(!empty($_REQUEST['ID'])) $sql.=" and ID='{$_REQUEST['ID']}'"; 
 else { $sql.=" and 1=2 "; echo "Musisz wyzwolic instalacje konkretnego serwera z parametrem"; } 

 
 DB::query('set global max_allowed_packet=1000000000;');
 $res=DB::query($sql);
 
 //if(DB::num_rows==0) echo "brak rekordow";
 
 while($h=DB::fetch($res)) {
   $REMOTE_FOLDER_ROOT=str_replace(array(".","-"),'_',$h->SERVER_ADDRESS); //also database name!



	$cmd=INSTALL_GETCOMMANDS($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,$h->SERVER_MOUNT_POINT_ROOT,$h->SERVER_ADDRESS,$h->SERVER_ADDRESS_LDAP_DC,$h->SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$h->ADMIN_USERNAME_L1,$h->ADMIN_USERNAME_L1_PASS,$h->ADMIN_USERNAME_DIRECTORY,$h->ADMIN_USERNAME_INITIAL_PASSWD,$h->BACKUP_USB_DEVICE,$h->SERVER_VERSION);


		//! FORMULARZ MENU
		echo "<hr><form method=GET><input type=hidden name=FUNCTION_INIT value=INSTALL_SES_PROCESY_A>
		    Ustal instalacje <select name=ID>";
		    $rlres=DB::query('select * from SES_PROCESY5_A where A_STATUS=\'NORMAL\'');
			while($rl=DB::fetch($rlres)) {
				echo "\n<option value='{$rl->ID}' ";
				if(!empty($_REQUEST['ID']) && ($_REQUEST['ID']==$rl->ID)) echo " selected ";
				echo ">{$rl->SERVER_ADDRESS} ({$rl->INSTALL_COMPLETE_POINT})</option>";
			
			}
			echo "</select><br>Ustal poczatek <select name=START>";
			foreach($cmd as $id=>$val) {
				echo "<option value='".$id."'"; if($_REQUEST['START']==$id) echo " selected ";
				echo " >".$id." ".str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$val['rsh'].$val['scp_root'][0].$val['scp'][0])."</option>";
			}
			echo "</select><br>
			Ustal koniec <select name=STOP>";
			foreach($cmd as $id=>$val) {
				echo "<option value='".$id."'"; if($_REQUEST['STOP']==$id) echo " selected ";
				if(empty($_REQUEST['STOP'])&&$id==count($cmd)-1) echo " selected "; 
				echo " >".$id." ".str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$val['rsh'].$val['scp_root'][0].$val['scp'][0])."</option>";
			}

			echo "</select>
			<br><input type=submit name='POBIERZ_XML_AUTOCONFIG_USB'  value='POBIERZ_XML_AUTOCONFIG_USB (TODO nie gotowe @2014-03-10)'> 
			<br>
			 <input type=submit name='WYKONAJ_REFERENCYJNA_BAZE_DANYCH'  value='1. WYKONAJ_REFERENCYJNA_BAZE_DANYCH (v@2014-03-15)'>			
			 <input type=submit name='POBIERZ_INSTALATOR_SH'  value='2. POBIERZ_INSTALATOR_SH (v@2014-03-15)'> <br>
			 <input type=submit value='INSTALUJ'>
			</form>
		
		";
		
		// 	$ldap_dc_generated=implode(',dc=',explode("",$h->SERVER_ADDRESS));
	$needed=array($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,$h->SERVER_ADDRESS,$h->SERVER_ADDRESS_LDAP_DC,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$h->ADMIN_USERNAME_L1,$h->ADMIN_USERNAME_L1_PASS,$h->ADMIN_USERNAME_DIRECTORY,$h->SERVER_VERSION);
	foreach($needed as $ind=>$need) {
		if(empty($need)) { echo 'Brak ustalonej jednej z wymaganych zmiennych w ustawieniach instalacyjnych serwera ('.$ind.')' ;
			die();
			};
	}
	//! POBIERZ_XML_AUTOCONFIG_USB
	if(!empty($_REQUEST['POBIERZ_XML_AUTOCONFIG_USB'])) {
		//if(empty($h->ADMIN_USERNAME_INITIAL_PASSWD)) die('Brak ADMIN_USERNAME_INITIAL_PASSWD');
		$xml=INSTALL_GET_INIT_APPLE_XML($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,$h->SERVER_MOUNT_POINT_ROOT,$h->SERVER_ADDRESS,$h->SERVER_ADDRESS_LDAP_DC,$h->SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$h->ADMIN_USERNAME_L1,$h->ADMIN_USERNAME_L1_PASS,$h->ADMIN_USERNAME_DIRECTORY,$h->ADMIN_USERNAME_INITIAL_PASSWD);
		echo "<pre>\n".htmlspecialchars($xml)."</pre>";
		
				return 0;
	}
	
	//! WYKONAJ_REFERENCYJNA_BAZE_DANYCH
	if(!empty($_REQUEST['WYKONAJ_REFERENCYJNA_BAZE_DANYCH'])) {
		set_time_limit(36000);
		$CONNTEST = DB::getDB('test_db');

		$CONNTEST->query('drop database test');
		$CONNTEST->query('create database test');
		$exec='php -r"include(\''.$INSTALL_ROOT.'/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'default_db\',\'default_db\',0,\'WYSLIJ_DO_BAZY\',\'CREATE_ZASOBY_STRUCTURES_CONFIG\'); " '.$_SERVER['SERVER_NAME'].' FILTR';	 //fresh create structures
	 	exec($exec,$out,$exit);
	 	DEBUG_S(-3,$command_id.':out of ',array($exec,$out,$exit));
 
	 	//zainstalowanie struktur w tabeli test etc
	 	$out="";$exit="";
	 	$exec='php -r"include(\''.$INSTALL_ROOT.'/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'test_db\',\'test_db\',0,\'WYSLIJ_DO_BAZY\',\'SYNC_ZASOBY_STRUCTURES_FROM_CONFIG\'); " '.$_SERVER['SERVER_NAME'].' FILTR'; //todo pare razy trzaba powtarzac bo sa bledy
	 	exec($exec,$out,$exit);	 	DEBUG_S(-3,$command_id.':out of1/4 ',array($exec,$out,$exit));flush(); $out="";$exit="";
	 	$exec='php -r"include(\''.$INSTALL_ROOT.'/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'test_db\',\'test_db\',0,\'WYSLIJ_DO_BAZY\',\'CREATE_ZASOBY_DATABASE_DESC\',\'3\'); " '.$_SERVER['SERVER_NAME'].' FILTR'; //@2013-10-15 staje recznie ? 
	 	exec($exec,$out,$exit);	 	DEBUG_S(-3,$command_id.':out of2/3 ',array($exec,$out,$exit));flush();$out="";$exit="";

	 	$exec='php -r"include(\''.$INSTALL_ROOT.'/superedit-SQIX_STRUCTURE_DB_SYNC.php\') ; SQIX_STRUCTURE_DB_SYNC(\'default_db\',\'test_db\',0,\'WYSLIJ_DO_BAZY\',\'FROM_ZASOBY_TO_ZASOBY\',\'3\'); " '.$_SERVER['SERVER_NAME'].' %PISM%,%zasob%,%ADMINISTRACJA%'; //import procesow z tagami PISMO
	 	exec($exec,$out,$exit);	 	DEBUG_S(-3,$command_id.':out of3/4 ',array($exec,$out,$exit));flush();$out="";$exit="";
	 	//tutaj bedzie TODO mysqldump do katalogu installera i komendy z tym zwiazane musza byc jakies - przekopiuj dumpa, odpal go w bazie glownej 
	 	$exec="/opt/local/bin/mysqldump5 -utest test >{$INSTALL_ROOT}/.config_base_structure_dump.sql"; //TODO piotr - moze jakies lepsze miejsce na tego dumpa
	 	exec($exec,$out,$exit);	 	DEBUG_S(-3,$command_id.':out of4/4 ',array($exec,$out,$exit));$out="";$exit="";


	
	} 
	//! POBIERZ_INSTALATOR_SH
	else if(!empty($_REQUEST['POBIERZ_INSTALATOR_SH'])) 
	{

		$installer_url="http://biuro.biall-net.pl/PLIKI/SES_PROCESY5_A/"; //miejsce do sciagania instalatora przez WWW
		$installer_dir_tar="/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A"; //katalog CWD z ktorego budowana jest instalacja 

		$packages['pl.procesy5']['exit_file']=str_replace('.', '_', $h->ID.".".$h->SERVER_ADDRESS); //czesc nazwy wynikowego pliku .pkg
		$packages['pl.procesy5']['installer_dir_name']=$h->ID.".".$h->SERVER_ADDRESS; //nazwa katalogu w jakim jest przygotowywany pkg
		$packages['pl.procesy5']['installer_tmp']="/tmp/pl.procesy5_".$h->ID.".".$h->SERVER_ADDRESS; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5']['CMD_FUNCTION']="INSTALL_GETCOMMANDS"; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5']['xml_choice']['visible']='true';
		$packages['pl.procesy5']['xml_choice']['title']='Procesy5';	
		$packages['pl.procesy5']['xml_choice']['description']='Main Procesy5 install components and scripts';	
		$packages['pl.procesy5']['xml_choice']['start_selected']='true';	

		$packages['pl.procesy5.COMP_PORT']['exit_file']=str_replace('.', '_', $h->ID.".COMP_PORT_".$h->SERVER_ADDRESS); //czesc nazwy wynikowego pliku .pkg
		$packages['pl.procesy5.COMP_PORT']['installer_dir_name']=$h->ID.".COMP_PORT_".$h->SERVER_ADDRESS; //nazwa katalogu w jakim jest przygotowywany pkg
		$packages['pl.procesy5.COMP_PORT']['installer_tmp']="/tmp/pl.procesy5_COMP_PORT_".$h->ID.".".$h->SERVER_ADDRESS;  //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.COMP_PORT']['CMD_FUNCTION']="INSTALL_GETCOMMANDS_COMP_PORT"; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.COMP_PORT']['xml_choice']['visible']='true';
		$packages['pl.procesy5.COMP_PORT']['xml_choice']['title']='MacPorts,Xcode,Licence';	
		$packages['pl.procesy5.COMP_PORT']['xml_choice']['description']='Needed utilities and libraries to install Procesy5 and Database';			
		$packages['pl.procesy5.COMP_PORT']['xml_choice']['start_selected']='true';	

		$packages['pl.procesy5.MYSQL55']['exit_file']=str_replace('.', '_', $h->ID.".MYSQL55_".$h->SERVER_ADDRESS); //czesc nazwy wynikowego pliku .pkg
		$packages['pl.procesy5.MYSQL55']['installer_dir_name']=$h->ID.".MYSQL55_".$h->SERVER_ADDRESS; //nazwa katalogu w jakim jest przygotowywany pkg
		$packages['pl.procesy5.MYSQL55']['installer_tmp']="/tmp/pl.procesy5_MYSQL55_".$h->ID.".".$h->SERVER_ADDRESS;  //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.MYSQL55']['CMD_FUNCTION']="INSTALL_GETCOMMANDS_MYSQL55"; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.MYSQL55']['xml_choice']['visible']='true';
		$packages['pl.procesy5.MYSQL55']['xml_choice']['title']='Mysql-55';	
		$packages['pl.procesy5.MYSQL55']['xml_choice']['description']='Required Mysql55 database from MacPorts';			
		$packages['pl.procesy5.MYSQL55']['xml_choice']['start_selected']='true';	

//POSTGIS
		$packages['pl.procesy5.POSTGIS']['exit_file']=str_replace('.', '_', $h->ID.".POSTGIS_".$h->SERVER_ADDRESS); //czesc nazwy wynikowego pliku .pkg
		$packages['pl.procesy5.POSTGIS']['installer_dir_name']=$h->ID.".POSTGIS_".$h->SERVER_ADDRESS; //nazwa katalogu w jakim jest przygotowywany pkg
		$packages['pl.procesy5.POSTGIS']['installer_tmp']="/tmp/pl.procesy5_POSTGIS_".$h->ID.".".$h->SERVER_ADDRESS;  //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.POSTGIS']['CMD_FUNCTION']="INSTALL_GETCOMMANDS_POSTGIS"; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.POSTGIS']['xml_choice']['visible']='true';
		$packages['pl.procesy5.POSTGIS']['xml_choice']['title']='Postgres-postgis';	
		$packages['pl.procesy5.POSTGIS']['xml_choice']['description']='Required Postgis database for qGIS ';			
		$packages['pl.procesy5.POSTGIS']['xml_choice']['start_selected']='true';	



		$packages['pl.procesy5.WEBMAIL']['exit_file']=str_replace('.', '_', $h->ID.".WEBMAIL_".$h->SERVER_ADDRESS); //czesc nazwy wynikowego pliku .pkg
		$packages['pl.procesy5.WEBMAIL']['installer_dir_name']=$h->ID.".WEBMAIL_".$h->SERVER_ADDRESS; //nazwa katalogu w jakim jest przygotowywany pkg
		$packages['pl.procesy5.WEBMAIL']['installer_tmp']="/tmp/pl.procesy5_WEBMAIL_".$h->ID.".".$h->SERVER_ADDRESS;  //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.WEBMAIL']['CMD_FUNCTION']="INSTALL_GETCOMMANDS_WEBMAIL"; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.WEBMAIL']['xml_choice']['visible']='true';
		$packages['pl.procesy5.WEBMAIL']['xml_choice']['title']='Webmail RoundCube';	
		$packages['pl.procesy5.WEBMAIL']['xml_choice']['description']='Additional webmail from roundcube';			
		$packages['pl.procesy5.WEBMAIL']['xml_choice']['start_selected']='true';	

		$packages['pl.procesy5.SE']['exit_file']=str_replace('.', '_', $h->ID.".SE_".$h->SERVER_ADDRESS); //czesc nazwy wynikowego pliku .pkg
		$packages['pl.procesy5.SE']['installer_dir_name']=$h->ID.".SE_".$h->SERVER_ADDRESS; //nazwa katalogu w jakim jest przygotowywany pkg
		$packages['pl.procesy5.SE']['installer_tmp']="/tmp/pl.procesy5_SE_".$h->ID.".".$h->SERVER_ADDRESS;  //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.SE']['CMD_FUNCTION']="INSTALL_GETCOMMANDS_SE"; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.SE']['xml_choice']['visible']='true';
		$packages['pl.procesy5.SE']['xml_choice']['title']='Procesy5 main application';	
		$packages['pl.procesy5.SE']['xml_choice']['description']='Main application and install scripts for Procesy5';			
		$packages['pl.procesy5.SE']['xml_choice']['start_selected']='true';	
		$packages['pl.procesy5.SE']['encrypt']=true;	


		$packages['pl.procesy5.MYADMIN']['exit_file']=str_replace('.', '_', $h->ID.".MYADMIN_".$h->SERVER_ADDRESS); //czesc nazwy wynikowego pliku .pkg
		$packages['pl.procesy5.MYADMIN']['installer_dir_name']=$h->ID.".MYADMIN_".$h->SERVER_ADDRESS; //nazwa katalogu w jakim jest przygotowywany pkg
		$packages['pl.procesy5.MYADMIN']['installer_tmp']="/tmp/pl.procesy5_MYADMIN_".$h->ID.".".$h->SERVER_ADDRESS;  //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.MYADMIN']['CMD_FUNCTION']="INSTALL_GETCOMMANDS_MYADMIN"; //miejsce do ktorego installer odpakuje wszystko instalator
		$packages['pl.procesy5.MYADMIN']['xml_choice']['visible']='true';
		$packages['pl.procesy5.MYADMIN']['xml_choice']['title']='php MyAdmin';	
		$packages['pl.procesy5.MYADMIN']['xml_choice']['description']='Component located at /garbage URL, to manage database';			
		$packages['pl.procesy5.MYADMIN']['xml_choice']['start_selected']='true';	





					DEBUG_S(-3,'Dane komponentow instalacji',$packages,__FILE__,__FUNCTION__,__LINE__);

		
		foreach($packages as $pkg_id=>$pkg_info) {
			$cmd=$pkg_info['CMD_FUNCTION']($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,$h->SERVER_MOUNT_POINT_ROOT,$h->SERVER_ADDRESS,$h->SERVER_ADDRESS_LDAP_DC,$h->SERVER_ADDRESS_SHORT,$INSTALL_ROOT,$REMOTE_FOLDER_ROOT,$h->ADMIN_USERNAME_L1,$h->ADMIN_USERNAME_L1_PASS,$h->ADMIN_USERNAME_DIRECTORY,$h->ADMIN_USERNAME_INITIAL_PASSWD,$h->BACKUP_USB_DEVICE,$h->SERVER_VERSION);
			MAKE_PKG_COMPONENT($h,$installer_dir_tar,$installer_url,$pkg_info['installer_tmp'],$cmd,$pkg_info['exit_file'],$pkg_info['installer_dir_name'],$pkg_id,$pkg_info['encrypt']);
			$package_xml['pkg-ref'].='<pkg-ref id="'.$pkg_id.'"/>';
            $package_xml['choices-outline'].='<line choice="'.$pkg_id.'"/>
            ';
             $package_xml['choice'].='<choice id="'.$pkg_id.'" visible="'.$pkg_info['xml_choice']['visible'].'" title="'.$pkg_info['xml_choice']['title'].'"
			 description="'.$pkg_info['xml_choice']['description'].'" start_selected="'.$pkg_info['xml_choice']['start_selected'].'">
			 <pkg-ref id="'.$pkg_id.'"/>
			 </choice>
			 <pkg-ref id="'.$pkg_id.'" version="0" onConclusion="none">'.$pkg_info['exit_file'].'.pkg</pkg-ref>';
		}
	
		DEBUG_S(-3,'Dane xml package',$package_xml,__FILE__,__FUNCTION__,__LINE__);

		$product['xml']='<?xml version="1.0" encoding="utf-8" standalone="no"?>
		<installer-gui-script minSpecVersion="1">
		
	<title>Procesy5 system installer</title>
    <organization>pl.procesy5</organization>
	<background file="installerImage.png" mime-type="image/png" alignment="right" scaling="proportional" />
    <domains enable_localSystem="true"/>
    <os-version min="10.8"/>
	'.$package_xml['pkg-ref'].'
    <options customize="always" require-scripts="true" rootVolumeOnly="true" />
      <choices-outline>
         <line choice="default" >
         '.$package_xml['choices-outline'].'
         </line>
    </choices-outline> 
    <choice id="default" visible="true" title="Procesy5 Bundle"  description="Please select carefully components" start_selected="true" />
    ';
	//$product['xml'].=$package_xml['pkg-ref'];
	$product['xml'].=$package_xml['choice'];
	$product['xml'].='</installer-gui-script>';
	echo "<br>Product XML<br>".$product['xml'];
	mkdir($installer_dir_tar."/".$h->ID.".resources",0777);
	$file=fopen($installer_dir_tar."/".$h->ID.".distribution.xml", "w") or die('Cannot open file:  '.$installer_dir_tar.'.'.$h->ID.".distribution.xml");
	 			fwrite($file,$product['xml']."\n");
	 			fclose($file);
	 			
	//copy logo
	exec("cp ".$INSTALL_ROOT."/icon/procesy5.png ".$installer_dir_tar."/".$h->ID.".resources/installerImage.png");
	 
	$exec="cd ".$installer_dir_tar." && productbuild --distribution ".$h->ID.".distribution.xml  --resources ".$h->ID.".resources ".$h->ID."_Procesy5_".str_replace('.','_',$h->SERVER_ADDRESS).".pkg" ;
	exec($exec ,$out,$exit);
	 DEBUG_S(-3,'Robie glownego instalatora pkg',array($exec,$out,$exit),__FILE__,__FUNCTION__,__LINE__);

	 		
	echo "<hr><A href='{$installer_url}".$h->ID."_Procesy5_".str_replace('.','_',$h->SERVER_ADDRESS).".pkg'> ściągnij glownego instalacje Procesy5 ".$h->ID."_Procesy5_".str_replace('.','_',$h->SERVER_ADDRESS).".pkg</a>\n";

	
				
	} else {
			
		
		if(!isset($_REQUEST['START'])||!isset($_REQUEST['STOP'])||empty($_REQUEST['ID'])) 
		return 0;
		
	
	

	 	if(!empty($_REQUEST['TEST'])) {
	 	    DEBUG_S(-3,'Komendy',$cmd); 
	
		 } else {
		   foreach($cmd as $command_id=>$command) {
		//if ($command_id==48) die("przerywam na $command_id");
			    	 if(!empty($_REQUEST['START']))  {
						if($command_id<$_REQUEST['START'])
					    continue;
					 }
					 if(!empty($_REQUEST['STOP']))  {
						if($command_id>$_REQUEST['STOP'])
					    die('Wymuszony stop na '.$_REQUEST['STOP']);
					 }
				  
					if($h->INSTALL_COMPLETE_POINT>$command_id-1) { 
					  echo ",{$command_id}";
					  continue; //ignorujemy wykonane z powodzeniem dzialania
					 }
				//! command['rsh']
				if(isset($command['rsh'])) {
		 		 	$exec=SSH_COMMAND_REMOTE_CREATE($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,$command['rsh']);
		 		 	DEBUG_S(-3,$command_id.':in '.htmlspecialchars(str_replace(array($h->ADMIN_USERNAME_PASSWD,str_replace('!','\!',$h->ADMIN_USERNAME_PASSWD)),'xxxxxx',$exec)),str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$exec));
					flush();
		 			$out="";$exit="";
		 			exec($exec,$out,$exit);
		 			DEBUG_S(-3,$command_id.':out of ',array($out,$exit));
		 			flush();
		 		} else if(isset($command['scp'])) {
		 			$command_out='/opt/local/bin/sshpass -p '.$h->ADMIN_USERNAME_PASSWD.' /usr/bin/scp -v -3 -o StrictHostKeyChecking=no  '.$command['scp'][0].' '.$h->ADMIN_USERNAME.'@' . $h->SERVER_ADDRESS_IP . ':'.$command['scp'][1];
		 		 	DEBUG_S(-3,$command_id.':in '.str_replace(array($h->ADMIN_USERNAME_PASSWD,str_replace('!','\!',$h->ADMIN_USERNAME_PASSWD)),'xxxxxx',$command_out),htmlspecialchars(str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$command_out)));
		 			flush();
		 			exec($command_out,$out,$exit); 
		 		 	DEBUG_S(-3,$command_id.':out ',array($out,$exit));
					flush();
		 		} else if(isset($command['scp_root'])) {
	
					$exec=SSH_COMMAND_REMOTE_CREATE($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,' test -d /tmp/scp_root && rm -R /tmp/scp_root ; mkdir -p /tmp/scp_root ; chown '.$h->ADMIN_USERNAME.' /tmp/scp_root ');
		 			exec($exec,$out,$exit);
		 			$command_out='/opt/local/bin/sshpass -p '.$h->ADMIN_USERNAME_PASSWD.' /usr/bin/scp -r -v -3 -o StrictHostKeyChecking=no  '.$command['scp_root'][0].' '.$h->ADMIN_USERNAME.'@' . $h->SERVER_ADDRESS_IP . ':/tmp/scp_root/';
		 			exec($command_out,$out,$exit);
		 		 	DEBUG_S(-3,$command_id.':out of '.str_replace(array($h->ADMIN_USERNAME_PASSWD,str_replace('!','\!',$h->ADMIN_USERNAME_PASSWD)),'xxxxxx',$command_out),array(htmlspecialchars(str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$command_out)),$out,$exit));
			 		if($exit==0) { flush();
			 		$out="";$exit="";
		 		 	$exec=SSH_COMMAND_REMOTE_CREATE($h->ADMIN_USERNAME,$h->SERVER_ADDRESS_IP,$h->ADMIN_USERNAME_PASSWD,' cd /tmp/scp_root/ && find . -name . -o -exec sh -c \'mv "\$@" "\$0"\' '.$command['scp_root'][1].' {} + -type d -prune ');
		 		 		exec($exec,$out,$exit);
		 		 		DEBUG_S(-3,$command_id.':out of '.str_replace(array($h->ADMIN_USERNAME_PASSWD,str_replace('!','\!',$h->ADMIN_USERNAME_PASSWD)),'xxxxxx',$command['rsh']),array(htmlspecialchars(str_replace($h->ADMIN_USERNAME_PASSWD,'xxxxxx',$exec)),$out,$exit));
					}
					flush();
					set_time_limit(36000);
		 		}
		 		
		 		
		 			if($exit==0) {
		 			    array_slice($out, 0, 1000); 
		 				$sql="update SES_PROCESY5_A set A_RECORD_UPDATE_DATE=now(), A_RECORD_UPDATE_AUTHOR='".$_SESSION['ADM_ACCOUNT']."',INSTALL_COMPLETE_POINT='".$command_id."' , INSTALL_COMPLETE_POINT_INFO='".DB::_(implode('\n<br>',$out) )."' where ID='".$h->ID."' ";
		 				DB::query($sql);
		 				$sql="insert into SES_PROCESY5_A_HIST (ID_USERS2,A_RECORD_UPDATE_DATE,A_RECORD_UPDATE_AUTHOR,INSTALL_COMPLETE_POINT,INSTALL_COMPLETE_POINT_INFO) select '".$h->ID."',now(),A_RECORD_UPDATE_AUTHOR,INSTALL_COMPLETE_POINT,INSTALL_COMPLETE_POINT_INFO from SES_PROCESY5_A where ID='".$h->ID."'  ";
		 				DB::query($sql);
		 				$command_id++;
		 			} else {
		 				$sql="update SES_PROCESY5_A set A_RECORD_UPDATE_DATE=now(), A_RECORD_UPDATE_AUTHOR='".$_SESSION['ADM_ACCOUNT']."', INSTALL_COMPLETE_POINT_INFO='ERROR!!!: ".DB::_(implode('\n<br>',$out) )."' where ID='".$h->ID."' ";
		 				DB::query($sql);
		 				$sql="insert into SES_PROCESY5_A_HIST (ID_USERS2,A_RECORD_UPDATE_DATE,A_RECORD_UPDATE_AUTHOR,INSTALL_COMPLETE_POINT,INSTALL_COMPLETE_POINT_INFO) select '".$h->ID."',now(),A_RECORD_UPDATE_AUTHOR,INSTALL_COMPLETE_POINT,INSTALL_COMPLETE_POINT_INFO from SES_PROCESY5_A where ID='".$h->ID."'  ";
		 				DB::query($sql);
		 				die('error at '.$command_id);
		 			}
		 	   }
		  }
	}
 
 }










}








/*

error_reporting(E_ALL & ~E_NOTICE);

define('DS', DIRECTORY_SEPARATOR);
define('APP_PATH_ROOT', dirname(__FILE__));
define('APP_PATH_WWW', dirname(__FILE__));
define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');

//session_save_path("../session") ;
session_start();

date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions

if (file_exists(".config.php")) include(".config.php");

SEF('DEBUG_S');
SEF('ZAP_SQL');
SEF('ZAP_SQL_UPDATE');
SEF('USERS_COLUMN_INIT');
SEF('AUTHORIZE_USER');
SEF('AUTHORIZE_USER_LOGIN');
//SEF("AUTHORIZE_USER_BY_AUTH_MODULE");
//SEF("AUTHORIZE_USER_LOGIN_BY_AUTH_MODULE");
SEF('GETFORMITEM');
SEF('T_WORKPOINTS_USER_SELECT');
require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('User');
Lib::loadClass('Config');
Lib::loadClass('App');
Lib::loadClass('DB');
Lib::loadClass('S');
*/


