#coding:utf-8

import os
import sys
import yaml
import sunhpc
import shutil
import textwrap

class Command(sunhpc.commands.report.command):
    """
    Output the yum/dnf repos content for the location of the Sunhpc distribution.

    <arg type="strings" name="orig">
    Recovery to the original state content
    </arg>

    <param type="address" name="url">
    Specify an yum repos address source
    </param>

    <param type="https" name="proto">
    Specify an web addr protocol http/https
    </param>

    <example cmd='report yumrepos orig=1'>
    Output the current path prefix to the distribution.
    </example>
    """
    def run(self, params, args):

        (url, protocol) = self.fillParams([
            ('url', 'mirrors.ustc.edu.cn'), 
            ('proto', 'https'),
            ])

        orig = False
        if len(args) and args[0] == 'orig':
            orig = True


        '''
        ports = 80 if protocol == 'http' else 443
        status = self.netup(url, port=ports)
        if not status:
            self.msg('The "%s://%s" url unable to access.' % (protocol, url), 'a')
        '''

        sysbackup = '/etc/sunhpc-backups'
        yumbackup = os.path.join(sysbackup, 'yumRepos')
        tagbackup = os.path.join(sysbackup, '.backupinfo')

        reposdirs = '/etc/yum.repos.d'

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

        s = self.confinfo(tagbackup, 'yum')
        if not s:
            # start backup yum repos
            for name in os.listdir(reposdirs):
                fsrc = os.path.join(reposdirs, name)
                fdst = os.path.join(yumbackup, name)
                shutil.copyfile(fsrc, fdst)
                os.remove(fsrc)

            self.msg('yum repos already backup finished. backup to %s' % yumbackup, 'i')
            
        if orig:
            rocky_appstream_url = 'mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=AppStream-$releasever'
            rocky_baseos_url    = 'mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=BaseOS-$releasever'
            rocky_extras_url    = 'mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=extras-$releasever'
            epel_base_url   = 'metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-8&arch=$basearch&infra=$infra&content=$contentdir'
            epel_source_url = 'metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-source-8&arch=$basearch&infra=$infra&content=$contentdir'

            elrepo_base_url = 'baseurl=https://mirrors.ustc.edu.cn/elrepo/elrepo/el$releasever/$basearch'
            elrepo_test_url = 'baseurl=https://mirrors.ustc.edu.cn/elrepo/testing/el$releasever/$basearch'
            elrepo_kernel_url = 'baseurl=https://mirrors.ustc.edu.cn/elrepo/kernel/el$releasever/$basearch'
            elrepo_extras_url = 'baseurl=https://mirrors.ustc.edu.cn/elrepo/extras/el$releasever/$basearch'
        else:
            rocky_appstream_url = 'baseurl=%s://%s/rocky/$releasever/AppStream/$basearch/os/' % (protocol, url)
            rocky_baseos_url    = 'baseurl=%s://%s/rocky/$releasever/BaseOS/$basearch/os/' % (protocol, url)
            rocky_extras_url    = 'baseurl=%s://%s/rocky/$releasever/extras/$basearch/os/' % (protocol, url)
            epel_base_url       = 'baseurl=%s://%s/epel/8/Everything/$basearch' % (protocol, url)
            epel_source_url     = 'baseurl=%s://%s/epel/8/Everything/source/tree' % (protocol, url)

            elrepo_base_url   = 'baseurl=%s://%s/elrepo/elrepo/el$releasever/$basearch' % (protocol, url)
            elrepo_test_url   = 'baseurl=%s://%s/elrepo/testing/el$releasever/$basearch' % (protocol, url)
            elrepo_kernel_url = 'baseurl=%s://%s/elrepo/kernel/el$releasever/$basearch' % (protocol, url)
            elrepo_extras_url = 'baseurl=%s://%s/elrepo/extras/el$releasever/$basearch' % (protocol, url)


        yum_list = []
        # AppStream
        rocky_appstream_file = '/etc/yum.repos.d/Rocky-AppStream.repo'
        rocky_appstream_info = """
        # 
        # Generated by sunhpc report yumrepos commands.
        #
        [appstream]
        name=Rocky Linux $releasever - AppStream
        %s
        gpgcheck=1
        enabled=1
        countme=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
        """ % rocky_appstream_url
        appstream_text = textwrap.dedent(rocky_appstream_info)
        yum_list.append([rocky_appstream_file, appstream_text])

        # BaseOS
        rocky_baseos_file = '/etc/yum.repos.d/Rocky-BaseOS.repo'
        rocky_baseos_info = """
        # 
        # Generated by sunhpc report yumrepos commands.
        #
        [appstream]
        name=Rocky Linux $releasever - BaseOS
        %s
        gpgcheck=1
        enabled=1
        countme=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
        """ % rocky_baseos_url
        baseos_text = textwrap.dedent(rocky_baseos_info)
        yum_list.append([rocky_baseos_file, baseos_text])

        # Extras
        rocky_extras_file = '/etc/yum.repos.d/Rocky-Extras.repo'
        rocky_extras_info = """
        # 
        # Generated by sunhpc report yumrepos commands.
        #
        [appstream]
        name=Rocky Linux $releasever - Extras
        %s
        gpgcheck=1
        enabled=0
        countme=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
        """ % rocky_extras_url
        extras_text = textwrap.dedent(rocky_extras_info)
        yum_list.append([rocky_extras_file, extras_text])

        # Media
        media_local = 0
        try:
            if len(os.listdir('/mnt/cdrom/BaseOS')):
                media_local = 1
        except FileNotFoundError:
            pass

        rocky_media_file = '/etc/yum.repos.d/Rocky-Media.repo'
        rocky_media_info = """
        # 
        # Generated by sunhpc report yumrepos commands.
        #
        [media-baseos]
        name=Rocky Linux $releasever - Media - BaseOS
        baseurl=file:///mnt/cdrom/BaseOS
        gpgcheck=1
        enabled=%s
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial

        [media-appstream]
        name=Rocky Linux $releasever - Media - AppStream
        baseurl=file:///mnt/cdrom/AppStream
        gpgcheck=1
        enabled=%s
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
        """ % (media_local, media_local)
        media_text = textwrap.dedent(rocky_media_info)
        yum_list.append([rocky_media_file, media_text])

        # epel repos
        epel_file = '/etc/yum.repos.d/epel.repo'
        epel_info = """
        # 
        # Generated by sunhpc report yumrepos commands.
        #
        [epel]
        name=Extra Packages for Enterprise Linux 8 - $basearch
        %s
        enabled=1
        gpgcheck=1
        countme=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8

        [epel-source]
        name=Extra Packages for Enterprise Linux 8 - $basearch - Source
        %s
        enabled=0
        gpgcheck=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8
        """ % (epel_base_url, epel_source_url)
        epel_text = textwrap.dedent(epel_info)
        yum_list.append([epel_file, epel_text])


        # elrepo repos
        elrepo_file = '/etc/yum.repos.d/elrepo.repo'
        elrepo_info = """
        # 
        # Generated by sunhpc report yumrepos commands.
        #
        [elrepo]
        name=ELRepo.org Community Enterprise Linux Repository - el8
        %s
        enabled=1
        countme=1
        gpgcheck=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-elrepo.org

        [elrepo-testing]
        name=ELRepo.org Community Enterprise Linux Testing Repository - el8
        %s
        enabled=0
        countme=1
        gpgcheck=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-elrepo.org

        [elrepo-kernel]
        name=ELRepo.org Community Enterprise Linux Kernel Repository - el8
        %s
        enabled=0
        countme=1
        gpgcheck=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-elrepo.org

        [elrepo-extras]
        name=ELRepo.org Community Enterprise Linux Extras Repository - el8
        %s
        enabled=1
        countme=1
        gpgcheck=1
        gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-elrepo.org
        """ % (elrepo_base_url, elrepo_test_url, elrepo_kernel_url, elrepo_extras_url)
        elrepo_text = textwrap.dedent(elrepo_info)
        yum_list.append([elrepo_file, elrepo_text])

        for f, t in yum_list:
            with open(f, 'w') as fn:
                fn.write('%s\n' % t)

        elrepo_key_file ='/etc/pki/rpm-gpg/RPM-GPG-KEY-elrepo.org'
        elrepo_key_info = """
        -----BEGIN PGP PUBLIC KEY BLOCK-----
        Version: GnuPG v1.4.5 (GNU/Linux)

        mQGiBEm+/6QRBAC5mbtqOFSQ0FkTLIMdIoqxtraIeUqwbPp3IBYQ/u/EREjyEf1D
        qFyBEXII0dD8JDT85vRZ81jhB7nFWa0VbUfY0xfghkbnokiNBVNpiQcvszw3UYDF
        aLAaOC8Z98vmlsQaBBTQG6704ZXLr7FJyG3GP5WE6egXIQQbrMcdmCoRBwCg/dwC
        HLWjuemoDc5SX7hKHbB4zZ8D/jP+oMbqz+bDn8OZ2UuaGdxr+mHW8tzTdPjnEU8e
        hUt1ws8eBqn/gMfKvUBa8xFSILe8Ty99u+VjFbcRsdf0H6dRre9AdDVUz5oxzoPw
        gamA8mhPQvFh3wt9smtRUh5IoM2LiM1s5pGMLuYuvSnVUPArEnSfW6K5I6v7OarU
        3WfrBACDEGGcaWKjfdkRtmKIQrzu6AnldVC1ISLVAoqxHnKNFTk1BgO0PSZDpfJI
        x8fMCnGlusoL6F5+LYEk4K4B0zvlj1ur3JocjxpuBLccl94JTo/+I9ZbS8ptUqLw
        LBUkgIQJzzIH4G5NZsQ3FpzSWGRFVa7etqTv9BfUMUmJxhEoobQ/ZWxyZXBvLm9y
        ZyAoUlBNIFNpZ25pbmcgS2V5IGZvciBlbHJlcG8ub3JnKSA8c2VjdXJlQGVscmVw
        by5vcmc+iGAEExECACAFAkm+/6QCGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAK
        CRAwm8MFuq2uUlgWAKCGWOpyodbzxS7Xy/0X9m9qVnHq+ACfUHrQzYAtFRpT07Sg
        giosE+mvAKu5Ag0ESb7/pxAIALgT0q0HhwugE717a7N+gAtCbFu8pCXOZcrAnJpG
        cMA9VWmsODZStPTxXYM2ggCMSzUnNis8pPZOPIP5C+t2IYtVjLshM4C9UiY7u5ET
        jErWCxWmF+2QLO50K56E4qxj0wufZt9P+Ih0USUM5L2oyrQG51uj/2v3Qq3igc8Z
        NTtmEOfis3losusQbAfZtTBmNQ0570kkhMxiyavgAUxLenXHYrkDJFuL7XdBCmna
        kykTn2dzU81rIDZ+QPxII4V/eZ5xGiRY/EDUIAysEV2m0NNZgWi/twUnZICm7zYp
        VRviJrBnFTvNEPMhiGRnJgQp/Krv4WIHQ67N8lQg3q5RJX8AAwUH/0UBjBgbsuWR
        dB+ZYWjKPBy+bJY/6HefPUuLrt3QDNINMW8kY7VzWRMWyGc4IlPJDW0nwOn/vT5H
        Dgc3YmA3tm7cKj5wpFijzff61Db8eq+CUKGscKxDBGzHq6oirM5U7DQLmipCs5Eb
        efwHIjE3aOUSnoQmniEnBWI2hm/rftmY9oJSi8xgns4wAokDPiMcucADtbV3fznx
        ppuowtBi8bcGB1vJZjTySQcSKWv+IVp5ej06uZ9501BEm6HxUZkuAGPecP65kcQu
        5bg7B7LQeI5AWyujqvfuWgAF34xhl9QU/sDWxM3wUog+bw7y8pyWCqnJhp70yx8o
        SqzhFygT62eISQQYEQIACQUCSb7/pwIbDAAKCRAwm8MFuq2uUq8PAKC1+E2pSwiS
        oHXkKYPYDwApsP1mVACfRe1YnggLYQtG9LMeweVQQC77rK8=
        =qyRr
        -----END PGP PUBLIC KEY BLOCK-----
        """
        elrepo_key_text = textwrap.dedent(elrepo_key_info)
        # rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org

        with open(elrepo_key_file, 'w') as fn:
            fn.write(elrepo_key_text)
        os.chmod(elrepo_key_file, 0o644)

RollName = "base"
































