#coding:utf-8

import os
import sys
import sunhpc
import shutil
import textwrap
import subprocess
class Command(sunhpc.commands.pxelinux.build.command):
    """
    Build the http service for the sunhpc cluster.

    <param type='Path' name='PxeDir'>
    supply an pxelinux base directory.default:/httpboot/pxelinux
    </param>

    <param type='Bool' name='Quiet'>
    Whether to output detailed information, default: no
    </param>
    
    <example cmd='pxelinux build httpd'>
    In local build the http service.
    </example>

    <example cmd='pxelinux build httpd pxedir=/httpboot/pxelinux'>
    In local /httpboot/pxelinux directory build the http service.
    </example>
    """
    def run(self, params, args):

        (quiet, ) = self.fillParams([('quiet', 'no')])
        cwd = os.getcwd()
        q = self.str2bool(quiet)
        self.msg('Starting build the httpd service...', q=q)

        # sunhpc-dist
        distname    = self.db.getHostAttr('localhost', 'distribution')
        # /export/sunhpc/install
        distbase    = self.command('report.distro',[]).strip()
        # /export/sunhpc/install/sunhpc-dist/x86_64/build
        install     = os.path.join(distbase, distname, self.arch, 'build')
        # /export/sunhpc/install/sunhpc-dist/x86_64/build/sbin
        src_sbin    = os.path.join(distname, self.arch, 'build', 'sbin')
        # /export/sunhpc/install/sbin
        dst_sbin    = os.path.join(distbase, 'sbin')

        os.chdir(distbase)
        if not os.path.exists(os.path.join(src_sbin, 'kickstart.cgi')):
            self.msg('Install the cgi-module-kickstart rpm ...', q=q)
            self.command('create.distro')

        if not os.path.exists(dst_sbin):
            os.symlink(src_sbin, dst_sbin)

        # chmod kickstart perms 755
        kickstart_cgi = os.path.join(src_sbin, 'kickstart.cgi')
        os.chmod(kickstart_cgi, 0o0755)

        # enable yum file repos.
        self.command('create.repos', ['file=1'])

        self.installHttpd(q)

        # enable yum http repos.
        self.command('create.repos', ['web=1'])
        os.chdir(cwd)

    def installHttpd(self, q):
        html = '/var/www/html'
        conf = '/etc/httpd/conf/httpd.conf'
        hostname = self.db.getHostAttr('localhost', 'Kickstart_PrivateHostname')
        basedirs = self.db.getHostAttr('localhost', 'Kickstart_BaseDir')
        distdirs = self.command('report.distro')

        # The httpd is not installed.
        if not os.path.exists(conf):
            self.shcmd('yum clean all; yum makecache')
            self.shcmd('yum install -y httpd httpd-tools httpd-devel')

        self.fw.addports(['80', '443'], ['tcp'])

        sunhpc_httpd_conf = '/etc/httpd/conf.d/sunhpc.conf'
        with open(sunhpc_httpd_conf, 'w') as f:
            f.write(textwrap.dedent(f"""\
                #
                # Sunhpc specific apache configuration.
                #
                <IfModule mod_mime.c>
                    AddHandler cgi-script .cgi
                </IfModule>

                UseCanonicalName Off
                ServerName {hostname}

                <Directory "/var/www/html">
                    Options FollowSymLinks Indexes ExecCGI
                    AllowOverride None
                    Order allow,deny
                    Allow from all
                </Directory>
            """))
        os.chmod(sunhpc_httpd_conf, 0o0644)

        central_httpd_conf = '/etc/httpd/conf.d/central.conf'
        with open(central_httpd_conf, 'w') as f:
            f.write(textwrap.dedent(f"""\
                #
                # Export Root Access Config
                #
                <Directory /var/www/html/{basedirs}>
                    Options FollowSymLinks Indexes ExecCGI
                    AllowOverride None
                    Allow from all
                </Directory>

                # HTTPS access for serving kickstart files
                <Directory /var/www/html/{basedirs}/sbin>
                    Options ExecCGI
                    AllowOverride None
                    Order allow,deny
                    Allow from all
                </Directory>

                # allow all access to the rolls RPMS
                <Directory /var/www/html/{basedirs}/rolls>
                    Allow from all
                </Directory>
            """))
        os.chmod(central_httpd_conf, 0o0644)

        address = self.db.getHostAttr('localhost', 'Kickstart_PrivateAddress')
        network = '.'.join(address.split('.')[:3])
        safe_httpd_conf = '/etc/httpd/conf.d/safe.conf'
        with open(safe_httpd_conf, 'w') as f:
            f.write(textwrap.dedent(f"""\
                #
                # sunhpc pxelinux build httpd
                #
                Listen 372
                <VirtualHost {address}:372>
                Alias /safe.d/ "/etc/safe.d/"
                Alias /safe.d  "/etc/safe.d"

                <Directory /etc/safe.d>

                    Options Indexes MultiViews
                    IndexOptions FancyIndexing NameWidth=*
                    RemoveHandler .var

                    AllowOverride None
                    Require ip {network}

                </Directory>
                </VirtualHost>
            """))
        os.chmod(safe_httpd_conf, 0o0644)

        # sylink the /export/sunhpc/install to /var/www/html
        html = os.path.join(html, basedirs)
        if not os.path.islink(html):
            os.symlink(distdirs.strip(), html.strip())

        self.shcmd('systemctl daemon-reload')
        self.shcmd('systemctl stop httpd')
        self.shcmd('systemctl start httpd')
        self.shcmd('systemctl enable httpd')

RollName = "base"



























