#!/usr/bin/python
# Security Hardening upgrade script
import logging
import os
import time
import re
import sys
import syslog
import time
import isi.hardening.util as util
import subprocess

from isi.app.lib import safelockfile
import isi.sys.version as sysver

IFS_BACKUP_PATH = "/ifs/.ifsvar/tmp"
LOG_FILE = os.path.join(IFS_BACKUP_PATH, "hardening-upgrade.log")
HARD_UPGRADE_FILE = os.path.join(IFS_BACKUP_PATH, "hardening-upgraded")

logger = logging.getLogger("hardening_upgrade")

def modify_zsh_command(user):
    """This function execute the isi auth command to set
       the root default shell to zsh.  This function executes
       only when lsass is running
    """
    try:
        cmd  = 'isi auth users modify '
        cmd += user
        cmd += ' --shell /usr/local/bin/zsh'
        retcode = subprocess.call(cmd, shell=True)
        if retcode < 0:
            logger.error("%s: isi auth command %s was terminated by signal. Retcode is %d" %
                        (time.ctime(), cmd, -retcode))
            return -retcode
        elif retcode > 0:
            logger.error("%s: isi auth command %s returned %d " % (time.ctime(), cmd, retcode))
            return retcode
        else:
            logger.info("%s: isi auth command completed sucessfully " % (time.ctime()))
            return retcode
    except Exception, e:
        logger.error("%s: Error during executing the isi auth command, %s" %
                    (time.ctime(), e))
        return 1

def run_isi_auth_command():
    """This function execute the isi auth command to set
       the local provider policy.  This function executes
       only when lsass is running
    """
    try:
        cmd  = 'isi auth local modify system --add-password-complexity=lowercase '
        cmd += '--add-password-complexity=uppercase '
        cmd += '--add-password-complexity=numeric '
        cmd += '--add-password-complexity=symbol '
        cmd += '--min-password-length=14 '
        cmd += '--password-history-length=5 '
        cmd += '--login-shell=/usr/local/bin/bash'
        retcode = subprocess.call(cmd, shell=True)
        if retcode < 0:
            logger.error("%s: isi auth command %s was terminated by signal. Retcode is %d" %
                        (time.ctime(), cmd, -retcode))
            return -retcode
        elif retcode > 0:
            logger.error("%s: isi auth command %s returned %d " % (time.ctime(), cmd, retcode))
            return retcode
        else:
            logger.info("%s: isi auth command completed sucessfully " % (time.ctime()))
            return retcode
    except Exception, e:
        logger.error("%s: Error during executing the isi auth command, %s" %
                    (time.ctime(), e))
        return 1

def main():
    try:
         logger.setLevel(logging.DEBUG)
         fh = logging.FileHandler(LOG_FILE, 'a')
         fh.setLevel(logging.DEBUG)
         logger.addHandler(fh)
    except EnvironmentError, e:
         syslog.syslog(syslog.LOG_NOTICE,
                      "Error during logging "
                      "in bg-hardening-upgrade script, %s" % e)
         return 1
    logger.setLevel(logging.DEBUG)

    try:
         # isi auth command fails due to some issue at bootime
         for x in xrange(1, 20):
             if(util.check_for_lsass() != 0):
                 time.sleep(5)
             else:
                 time.sleep(5)
                 break
         success = True
         if (run_isi_auth_command() != 0):
             logger.error("%s: run_isi_auth_command() Failed" % time.ctime())
             success = False

         success = True
         if (util.delete_user('ftp') != 0):
             logger.error("%s: run_pw_command() Failed for ftp user" % time.ctime())
             success = False

         success = True
         if (util.delete_group('news') != 0):
             logger.error("%s: run_pw_command() Failed news group" % time.ctime())
             success = False

         # Modify shell of root and admin to zsh
         userlist = ['root', 'admin']
         for user in userlist:
             if (modify_zsh_command(user) != 0):
                 logger.error("%s: modify_zsh_command() Failed for %s user" % (time.ctime(), user))
                 success = False

    except Exception, e:
         success = False
         logger.error("%s: Error during Hardening Upgrade %s (errno: %d)" %
                         (time.ctime(), LOG_FILE, e.errno))

if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception, e:
        syslog.syslog(syslog.LOG_ERR,
                      "Error running hardening-upgrade script, %s" % e)

