#!/usr/bin/python

"""Downloads the  initial rpm's  to run update,  calls a  shell script
that installs them, starts the necessary services and runs rpmupdate."""

import check_partitions
import urllib, os, shutil, string, re

rpm_url = 'http://web.mit.edu/afs/athena/system/rhlinux/athena-9.0/' \
          'free/RPMS'

def get_release_rpms():

    "Get a copy of the latest release-rpms file"

    from latest_version import latest_version_string
    base_name = '/afs/athena/system/rhlinux'
    control_list = os.path.join(base_name, 'control',
                                'list-' + latest_version_string)
    shutil.copy(control_list, '/var/athena/release-rpms')    

def install_rpms():

    # Get rid of some rpm's that conflict with athena-krb5
    rpms = os.popen('rpm -qa').readlines()
    to_remove = []
    for rpm_name in ['sendmail']:
        if filter(re.compile(rpm_name).match, rpms):
            to_remove.append(rpm_name)
    if to_remove:
        assert not os.system('rpm -e ' + string.join(to_remove))

    # The order of these packages reflects their interdependancies, and
    # should be preserved.
    for name in ['base-9.0-3', 'afs-9.0-17', 'rpmupdate-9.0-15',]:
        full_name = 'athena-%s.i386.rpm' % name
        path = os.path.join('/root', full_name)
        output = open(path, 'w')
        input_ = urllib.urlopen(os.path.join(rpm_url, full_name))
        while 1:
            next = input_.read(10**6)
            if next == '': break
            output.write(next)
        output.close()
        assert not os.system('/bin/rpm --replacepkgs -Uhv ' + path)

def main():

    install_rpms()
    assert not os.system('/etc/rc.d/init.d/afs start')
    
    from latest_version import latest_version_string
    os.chdir('/afs/athena.mit.edu/system/rhlinux/')
    update_command = '/etc/athena/rpmupdate -h -p /dev/null ' + \
                     'control/list-' + latest_version_string
    assert not os.system(update_command)
    
    get_release_rpms()

if __name__ == '__main__': main()
