#
#coding:utf-8
#
#Author  : QCSun
#Email   : qcsun@sunhpc.com
#Times   : 2023-04-14 05:21:02
#WebSite : https://www.sunhpc.com

import os
import sys
import sunhpc
import shutil

class command(sunhpc.commands.soft.command):
    pass

class Command(command):
    """
    Build the Gaussian software.

    <arg type="string" name="version">
    Specifies the software version. e.g,, version=03/09/16
    </arg>

    <param type="path" name="prefix">
    Specifies the software install path.
    </param>

    <param type="path" name="envs">
    Specifies the software env path.
    </param>

    <param type="path" name="source">
    Specifies the software source path. e.g,, /mnt/usb
    </param>

    <example cmd='soft gaussian prefix=/share/apps/soft version=16'>
    install the gaussian software.
    </example>
    """
    def run(self, params, args):

        (prefix, version, source, envs) = self.fillParams([
            ('prefix', '/share/apps/soft'),
            ('version', None),
            ('source', '/mnt/usb'),
            ('envs', '/share/apps/envs'),
            ])

        if not version:
            self.msg('must supply an "Gaussian version" e.g,, version=03/09/16', 'a')

        try:
            os.makedirs(prefix)
            self.msg("The %s directory does not exist,and it will be created." % prefix, 'w')
        except FileExistsError:
            pass

        if not os.path.exists(envs):
            os.makedirs(envs)

        softname = 'Gaussian%s' % version

        softdirs = os.path.join(source, 'hpcsoft')
        softlist = os.listdir(softdirs)

        if 'Gaussian' not in softlist:
            self.msg('The "%s" software was not found in the %s directory.' % (softname, softdirs), 'a')

        gspathname = os.path.join(softdirs, 'Gaussian', softname, 'Gaussian16-a03.tbz')


        gaussian = os.path.join(prefix, 'g%s' % version)
        if os.path.exists(gaussian):
            self.msg('The %s already exists,to reinstall it, remove it first.' % gaussian)
        else:
            self.msg('Start installing the %s software to the %s directory...' % (softname, prefix))
            os.system('tar -xf %s -C %s' % (gspathname, prefix))

        gsenv = os.path.join(envs, 'g16-env.sh')
        with open(gsenv, 'w') as f:
            f.write('#!/bin/sh\n')
            f.write('#\n# %s env config\n#\n\n' % gaussian)
            f.write('export g%sroot=%s\n' % (version, prefix))
            f.write('source $g%sroot/g%s/bsd/g%s.profile\n\n' % (version, version, version))
            f.write('export GAUSS_SCDIR=~/gstmp\n')

        # create shared user and group.
        self.msg('Create a shared group to run the %s software.' % softname) 
        self.msg('  1, groupadd -g 888    public ')
        self.msg('  2, usermod  -G public dell   ')
        self.msg('  3, chown    -R root:public %s/g%s' % (prefix, version))




























