#!/usr/bin/perl
## nappit add-on ampo
## Okt. 2013, based on script from effemmess

############
## setup ampo (Apache, MySQL + PHPMyadmin, PHP, Owncloud)
##
####################################################################################
#
#
####################################################################################

####################
# not on Solaris  11
####################
     $ant=`uname -a`;
     @par=split(/ /,$ant);
     if ($par[3]=~/^11\./i) {
       print "\n"x20;
       print "This ampo installer is running on Illumos based systems only.\nOn Solaris 11 install the default AMP stack via: \npkg install amp\n\n";
       exit;
     }

###############
### root only !
###############
     $ant=`whoami`; chomp $ant;
     if ($ant ne "root") {
         print "user $ant not allowed\nlogin as root or su and run setup again!";
	 exit;
     }
	
#run from $HOME ie /root
###############
               $t=`pwd`;
               $ant=`echo \$HOME`;
               if ($t ne $ant){
                      print "\n\n#####################\nYou must call wget as from your \$HOME-directory.\n Please do a cd /\$HOME and try again.\n\n";
                      exit;
               }


if (-f "$ant/amp.log") {
  `rm $ant/amp.log`;
}

##date
#######
 ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime(time);
 $mon++;
 if ($min < 10)  { $min  = "0$min";  }
 if ($hour < 10) { $hour = "0$hour"; }
 if ($mday < 10) { $mday = "0$mday"; }
 if ($mon < 10)  { $mon  = "0$mon";  }
 $year=1900+$year;



##############
# Startmessage
##############
$t=`echo \$HOME`;
chomp($t);        # remove newline

      print "\n"x20;
      print "***************************************************************************\n\n";
      print "**    Setup napp-it AMPO ZFS Server addon Ver. 0.2 beta - Okt 2013       **\n";
      print "**    intended for OmniOS and OpenIndiana - not working on Solaris 11    **\n\n";
      print "***************************************************************************\n\n";
      print "** Actions (logfile $t/ampo.log):                            \n";
      print "**     Install Apache 2.4.6, MySQL 5.6.12, PHPMyadmin,  PHP 5.4.19       **\n";
      print "**     via pkgin (provided by SmartOS) and OwnCloud 5.0.10               **\n\n";
      print "***************************************************************************\n\n\n";
      print "*  \n";
      sleep(3);
      print " 3 \n"; sleep(2);
      print " 2 \n"; sleep(2);
      print " 1 \n"; sleep(2);

print "\n"x40;


#########################################################
## step 1. create BE, optionally add path to all commands
#########################################################

    # create BE pre setup
    $t=time();
    `beadm create pre_amp_setup_$t`;
    
    
    # required path for pkgin
    # export PATH=/opt/local/sbin:/opt/local/bin:$PATH
    
    $r=`echo \$PATH`;
    if (!($r=~/opt\/local/)) {
      $path="export PATH=/opt/local/sbin:/opt/local/bin:\$PATH;";
      $r=`$path echo \$PATH`;
      chomp ($r);
      &log1("step 1. add Path: \nexport PATH=/opt/local/sbin:/opt/local/bin:\$PATH;");
    } else {
      $path="";
      &log1("step 1. Path: $r");
    }



###################
# step 2: bootstrap
###################

    &log1("step 2. Load bootstrap\ncurl http://pkgsrc.joyent.com/packages/SmartOS/bootstrap/bootstrap-2013Q2-x86_64.tar.gz | gtar -zxpf - -C /");
    $r=`curl http://pkgsrc.joyent.com/packages/SmartOS/bootstrap/bootstrap-2013Q2-x86_64.tar.gz | gtar -zxpf - -C / `;
    &log2($r);
    
    
    #Update repo-database
    $r.=`$path pkgin -y update`;
    &log2($r);


################
# step 3: Apache
################

    &log1('step 3. Install Apache: pkgin -y install apache-2.4');                       # okt 2013: 2.4.6
    $r=`$path pkgin -y install apache-2.4`;
    &log2($r);

# 3.1 backup httpd.conf once
############################
    if (!(-f "/opt/local/etc/httpd/httpd.conf.orig")) {
       `cp /opt/local/etc/httpd/httpd.conf /opt/local/etc/httpd/httpd.conf.orig`;       # original Apache
    }
    # backup httpd.conf once to /opt/local/etc/httpd/httpd.conf.default                 # default is last valid after owncloud setup
    sleep(2);
    
    #exit;


#####################
# step 4: Install PHP
##################### Include php specific settings to httpd_php.conf

    &log1('step 4. Install PHP: pkgin -y install php-5.4');                             # okt 2013: 5.4.19
    $r=`$path pkgin -y install php-5.4`;
    &log2($r);
    
    &log2('Install PHP module: pkgin -y install ap24-php54');                           # okt 2013: 5.4.1
    $r=`$path pkgin -y install ap24-php54`;
    &log2($r);


# 4.1 install php extensions (also needed for owncloud)
############################

    &log2('Install PHP extensions: pkgin -y install php54-ftp');                        # okt 2013: 5.4.19
    $r=`$path pkgin -y install php54-ftp`;
    &log2($r);
    
    &log2('Install PHP extensions: pkgin -y install php54-curl');                       # okt 2013: 5.4.19
    $r=`$path pkgin -y install php54-curl`;
    &log2($r);
    
    &log2('Install PHP extensions: pkgin -y install php54-intl');                       # okt 2013: 5.4.19
    $r=`$path pkgin -y install php54-intl`;
    &log2($r);
    
    &log2('Install PHP extensions: pkgin -y install php54-owncloud');                   # okt 2013: 5.0.7
    $r=`$path pkgin -y install php54-owncloud`;
    &log2($r);

    &log2('Install PHP extensions: pkgin -y install php54-soap');                        # okt 2013: 5.4.19
    $r=`$path pkgin -y install php54-soap`;
    &log2($r);	

# 4.2 backup php.ini once
#########################
    if (!(-f "/opt/local/etc/php.ini.orig")) {
       `cp /opt/local/etc/php.ini /opt/local/etc/php.ini.orig`;
    }

## 4.3 add index.php to: DirectoryIndex index.html index.php in httpf.conf
#######################################
    $r=`cat /opt/local/etc/httpd/httpd.conf`;
    if (!($r=~/DirectoryIndex index.html index.php/s)) {
       $r=~s/DirectoryIndex index.html/DirectoryIndex index.html index.php/s;
    }

## 4.4 add Include httpd_php.conf to httpf.conf
#######################################
    if (!($r=~/\nInclude \/opt\/local\/etc\/httpd\/httpd_php.conf/s))  {
       $r.="\n# add php specific settings\n";
       $r.="Include /opt/local/etc/httpd/httpd_php.conf\n";
       &log2('add: Include /opt/local/etc/httpd/httpd_php.conf to httpd.conf');
    }

    `touch /opt/local/etc/httpd/httpd_php.conf`;
    open (M, ">/opt/local/etc/httpd/httpd.conf");
       print M "$r";
    close (M);



## 4.5 create httpd_php.conf
############################
    $r=`cat /opt/local/etc/httpd/httpd_php.conf`;

    #  add: LoadModule php5_module lib/httpd/mod_php5.so
    if (!($r=~/mod_php5.so/s)) {
        $r.="\n# add php specific settings\n#LoadModules\n";
        $r.="LoadModule php5_module lib/httpd/mod_php5.so\n\n";
        &log2('add: LoadModule php5_module lib/httpd/mod_php5.so to httpd_php.conf');
    }

    # add: AddHandler application/x-httpd-php .php
    if (!($r=~/\nAddHandler application\/x-httpd-php .php/s)) {
       $r.="\n#AddHandler\n";
       $r.="AddHandler application\/x-httpd-php .php\n\n";
    }

    # write updated httpd_php.conf
    open (M, ">/opt/local/etc/httpd/httpd_php.conf");
        print M "$r";
    close (M);


#


# 4.4 backup httpd.conf once
############################
    if (!(-f "/opt/local/etc/httpd/httpd.conf.orig.php")) {
       `cp /opt/local/etc/httpd/httpd.conf /opt/local/etc/httpd/httpd.conf.orig.php`;
    }


# 4.5 edit/add needed entries to php.ini
########################################
    $r=`cat /opt/local/etc/php.ini`;
    
    ## edit php.ini
    if (!($r=~/IAMPO Extensions/s)) {
    $t=<<EoF;


;;;;;;;;;;;;;;;;;;;;
; IAMPO Extensions ;
;;;;;;;;;;;;;;;;;;;;

extension=bz2.so
extension=curl.so
extension=dom.so
extension=gd.so
extension=gettext.so
extension=iconv.so
extension=intl.so
extension=json.so
extension=mbstring.so
extension=mcrypt.so
extension=mysqli.so
extension=mysql.so
extension=pdo.so
extension=pdo_sqlite.so
extension=zip.so
extension=zlib.so
extension=ftp.so
extension=soap.so
EoF
    # write new php.ini
    $r=~s/extension=php_zip.dll/extension=php_zip.dll$t/s;
    open (M, ">/opt/local/etc/php.ini");
        print M "$r";
    close (M);
    
    # save once as default
    if (!(-f "/opt/local/etc/php.ini.default"))  {
      `cp /opt/local/etc/php.ini /opt/local/etc/php.ini.default`;
    }
    &log2('backup default: /opt/local/etc/php.ini.default');

} ##/ edit php.ini



###############
# step 5: MySQL
###############

    &log1('step 5. Install MySQL: pkgin -y install mysql-server-5.6');           # okt 2013: 5.6.12
    $r=`$path pkgin -y install mysql-server-5.6`;
    &log2($r);


# 5.1 patch mysql manifest
##########################
    $r=`svcs mysql`;
    if ($r=~/maintenance/) { `svcadm disable mysql`; }
    if (!($r=~/online/)) {

      &log1('5a: Modify MySQL SMF manifest (to fix maintenance problem)');
      # there seems a bug: service -> maintenance: see http://csylvester.blogspot.de/
      # <method_context project='mysql' working_directory='/var/mysql'> must be
      # <method_context working_directory='/var/mysql'>

          $r=`cat /opt/local/share/smf/mysql-server/manifest.xml`;
          @r=split(/\n/,$r);
          foreach $t (@r) {
                if ($t=~/method\_context/)  {
                    $t=~s/ project=\'mysql\'//;
                }
          }
          $r=join("\n",@r);
          open (M, ">/opt/local/share/smf/mysql-server/manifest.xml");
              print M "$r";
          close (M);

          #reload manifest
          &log1("modify and reload manifest /opt/local/share/smf/mysql-server/manifest.xml");
          $r=`svccfg -v import /opt/local/share/smf/mysql-server/manifest.xml`;
          &log2($r);
      }

####################
# step 6: PHPMyadmin
####################

    &log1('step 6: install phpmyadmin');
    $r=`$path pkgin -y install phpmyadmin`;                         ## okt 2013: 3.5.8.2
    &log2($r);
    
    # 6.1 add Include /opt/local/etc/httpd/httpd_phpmyadmin.conf to httpd.conf when needed
    $r=`cat /opt/local/etc/httpd/httpd.conf`;
    if (!($r=~/\nInclude \/opt\/local\/etc\/httpd\/httpd_phpmyadmin.conf/s))  {
        open (M, ">>/opt/local/etc/httpd/httpd.conf");
            print M "\n# add this to make phpMyAdmin accessible through http://www.domain.com/phpmyadmin/\n";
            print M "Include /opt/local/etc/httpd/httpd_phpmyadmin.conf\n";
        close (M);
        &log2('add: Include /opt/local/etc/httpd/httpd_phpmyadmin.conf to httpd.conf');
    }

# 6.2 add httpd_phpmyadmin.conf when needed
#######################################
    if (!(-f "/opt/local/etc/httpd/httpd_phpmyadmin.conf"))  {
    $r=<<Eof;
# phpmyadmin configuration file fragment for Apache

<IfModule mod_alias.c>
	Alias /phpmyadmin "/opt/local/share/phpmyadmin/"
</IfModule>

<Directory "/opt/local/share/phpmyadmin">
	Options Indexes
	AllowOverride None
	Require all granted
</Directory>

#------------------
#
# For security, don't serve pages from the phpmyadmin scripts directories.
#
# NOTE: If you are setting up phpmyadmin for the first time you will need
# to comment this block out the first time you access your phpmyadmin
# installation.
#
<Directory "/opt/local/share/phpmyadmin/scripts">
    Order deny,allow
    Deny from all
</Directory>

Eof

  # write file
  open (M, ">/opt/local/etc/httpd/httpd_phpmyadmin.conf");
      print M "$r";
  close (M);
  &log2('create: /opt/local/etc/httpd/httpd_phpmyadmin.conf');
}

###### configurations
    if (!(-f "/opt/local/etc/phpmyadmin/config.inc.php")) {
    	`cp /opt/local/share/examples/phpmyadmin/config.inc.php /opt/local/etc/phpmyadmin/config.inc.php`;
    	&log2('copy: /opt/local/share/examples/phpmyadmin/config.inc.php /opt/local/etc/phpmyadmin/config.inc.php');
    }



#############################
## step 7: Install Owncloud
#############################

# only once
if (!(-d '/opt/local/share/owncloud')) {
         &log1('step 7: install owncloud-5.0.10');

         if (-f "/opt/local/share/owncloud-5.0.10.tar.bz2") {
           `rm /opt/local/share/owncloud-5.0.10.tar.bz2`;
         }
	`wget -P /opt/local/share/ http://download.owncloud.org/community/owncloud-5.0.10.tar.bz2`;
	`tar -xjf /opt/local/share/owncloud-5.0.10.tar.bz2 -C /opt/local/share/`;

         # remove the original archiv (if you want)
	`rm /opt/local/share/owncloud-5.0.10.tar.bz2`;

        #set owner for the new directory
	`chown -R www:www /opt/local/share/owncloud`;

}  else {
         &log1('step 7: owncloud already installed');
}

# 7.1 add Include to httpd.conf
###############################
$r=`cat /opt/local/etc/httpd/httpd.conf`;
if (!($r=~/\nInclude \/opt\/local\/etc\/httpd\/httpd_owncloud.conf/s))  {
    open (M, ">>/opt/local/etc/httpd/httpd.conf");
        print M "\n# add this to make owncloud accessible through http://www.domain.com/owncloud/\n";
        print M "Include /opt/local/etc/httpd/httpd_owncloud.conf\n";
    close (M);
    &log2('add: Include /opt/local/etc/httpd/httpd_owncloud.conf to httpd.conf');
}

# 7.2 backup httpd.conf once
    if (!(-f "/opt/local/etc/httpd/httpd.conf.orig.owncloud")) {
       `cp /opt/local/etc/httpd/httpd.conf /opt/local/etc/httpd/httpd.conf.orig.owncloud`;
    }


# create Include
   if (!(-f "/opt/local/etc/httpd/httpd_owncloud.conf"))  {
   $r=<<Eof;
# Owncloud configuration
<IfModule mod_alias.c>
	Alias /owncloud /opt/local/share/owncloud
</IfModule>

<Directory "/opt/local/share/owncloud">
	DirectoryIndex index.php
	Options All
	AllowOverride All
	Require all granted
</Directory>

Eof

    # write file
    open (M, ">/opt/local/etc/httpd/httpd_owncloud.conf");
       print M "$r";
    close (M);
    &log2('create: /opt/local/etc/httpd/httpd_owncloud.conf');

  } #/ add Include

#backup httpd.conf once to default
##################################
    if (!(-f "/opt/local/etc/httpd/httpd.conf.default")) {
       `cp /opt/local/etc/httpd/httpd.conf /opt/local/etc/httpd/httpd.conf.default`;
       &log2('backup default: /opt/local/etc/httpd/httpd.conf.default');
    }


#############################
## step 8: opt Sewafile server: ampos?
#############################


#############################
# step 9. Last actions
#############################)

    &log1('step 9. Rerun PHP ap24-php54 + Apache setup do solve dependencies like missing mod_php5.so');                       # okt 2013: 2.4.6
    $r=`$path pkgin -y install ap24-php54`;
    $r=`$path pkgin -y install apache-2.4`;
    &log2($r);
    
# 9.1 create phpinfo page
#########################
    $r=<<EoF;
<html><body><h1>It works!</h1>
phpinfo:<hr>
<?php
phpinfo();
?>
</body></html>
EoF
  if (!(-f "/opt/local/share/httpd/htdocs/index.html.default"))  {
      if (-f "/opt/local/share/httpd/htdocs/index.html") {
        `cp /opt/local/share/httpd/htdocs/index.html /opt/local/share/httpd/htdocs/index.html.default`;
        `rm /opt/local/share/httpd/htdocs/index.html`;
      }
      open (M, ">/opt/local/share/httpd/htdocs/index.php");
        print M "$r";
      close (M);
  }



#basically configure napp-it (obsolet in next release)
#####################################################
if (-d "/var/web-gui") {
        $r=`cat /var/web-gui/data/napp-it/zfsos/_lib/oslib.pl`;
        $r=~s/grep apache2/grep apache/s;
        $r=~s/svc:\/application\/database\/mysql/mysql/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/_lib/oslib.pl');
                                    print M "$r";
                                  close (M);
        
        
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/02_apache.conf/action.pl`;
        $r=~s/\/etc\/apache2\/2.2\/httpd.conf/\/opt\/local\/etc\/httpd\/httpd.conf/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/02_apache.conf/action.pl');
                                    print M "$r";
                                  close (M);
        
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/03_php.ini/action.pl`;
        $r=~s/\/etc\/php\/5.2\/php.ini/\/opt\/local\/etc\/php.ini/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/03_php.ini/action.pl');
                                    print M "$r";
                                  close (M);

        $r=`cat '/var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/05_restart Apache/action.pl'`;
        $r=~s/apache2+/apache/igs;
                                  open (M, ">/var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/05_restart Apache/action.pl");
                                    print M "$r";
                                  close (M);
        
        $r=`cat '/var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/06_disable Apache/action.pl'`;
        $r=~s/apache2+/apache/igs;
                                  open (M, ">/var/web-gui/data/napp-it/zfsos/02_services/022_Apache=-nex/06_disable Apache/action.pl");
                                    print M "$r";
                                  close (M);
        
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/action.pl`;
        $r=~s/svc:\/application\/database\/mysql/mysql/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/action.pl');
                                    print M "$r";
                                  close (M);
                                  
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/03_enable/action.pl`;
        $r=~s/svc:\/application\/database\/mysql/mysql/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/03_enable/action.pl');
                                    print M "$r";
                                  close (M);
        
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/04_disable/action.pl`;
        $r=~s/svc:\/application\/database\/mysql/mysql/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/04_disable/action.pl');
                                    print M "$r";
                                  close (M);
                                  
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/05_start/action.pl`;
        $r=~s/svc:\/application\/database\/mysql/mysql/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/05_start/action.pl');
                                    print M "$r";
                                  close (M);
        
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/06_stop/action.pl`;
        $r=~s/svc:\/application\/database\/mysql/mysql/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/06_stop/action.pl');
                                    print M "$r";
                                  close (M);
        
        
        $r=`cat /var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/02_config/action.pl`;
        $r=~s/\/etc\/mysql\/my.cnf/\/opt\/local\/my.cnf/gs;
                                  open (M, '>/var/web-gui/data/napp-it/zfsos/02_services/05_MySQL/02_config/action.pl');
                                    print M "$r";
                                  close (M);

} # /if napp-it


# enable Apache and mysql
#########################
    &log2('enable Apache and mysql');
    `svcadm disable apache`;
    sleep (2);
    `svcadm disable mysql`;
    sleep (2);
    `svcadm enable apache`;
    sleep (2);
    `svcadm enable mysql`;
    sleep (2);
    print `svcs apache`;
    print `svcs mysql`;
    sleep(3);
    
    
    $t=`echo \$HOME`;
    chomp($t);        # remove newline
    print "logfile: $t/ampo.log\n\n";

#############################
## step 10: write and run shell script (for interactive settings like mysql security)
#############################

    open (M, '>./ampo2.sh');
          print M "#!/bin/sh\n";
          print M "/opt/local/bin/mysql_secure_installation\n";
    close (M);
    `chmod 700 ./ampo2.sh`;


    print "\n\n\n";
    &log1('8: You should now run mysql_secure_installation to secure mySQL');
    print "Enter: ./ampo2.sh\n\n";
    
    exit;




############### new main action
sub log1 {
###############
    my $t=$_[0];
    $t="\n\n----------------\n$t\n----------------\n\n";
    &log2($t);
  }

############### log and print
sub log2 {
###############
  my $r=`echo \$HOME`;
  chomp $r;
      my $t=$_[0];
      $t=~s/\s+$//gs;
      $t.="\n";
      print $t;
      open (M, ">>$r/ampo.log");
          print M "$t\n";
      close (M);
  }



