#!/usr/bin/python

import os
import sys
import subprocess

def display_messages(suffix):
    """Display opening messages"""

    print "\nNOTE:\tUbuntu 9.04 ('Jaunty'), is end of life."
    print "\tYour system is now being pointed at a new software archive that"
    print "\tcontains Ubuntu 9.04 software."
    print
    print "\tFor information about Ubuntu releases, see:" 
    print "\t\thttp://wiki.ubuntu.com/Releases"
    print "\n\tYour /etc/apt/sources.list and /etc/apt/sources.list.d/*list"
    print "\tfiles are being copied with the following file  name suffix: "
    print "\t" + suffix
    print "Working..."
            
def backup(f, suffix):
    """Copy file with backup suffix"""

    back = f + suffix
    cmd = ['cp', f, back]
    subprocess.call(cmd)

def fix_urls(f, old, new):
    """replace end-of-life urls with the new"""

    #open s.l into list, one line per list item
    f_ = open(f, 'r')
    lines = f_.readlines()
    f_.close()

    new_lines = []

    f_ = open(f, 'w')

    for line in lines:
        if line.startswith("#"): #pass commented lines through
            new_lines.append(line)
        elif len(line) <= 1: #pass empty lines through
            new_lines.append(line)
        else:
            for item in old: #replace all pre end of life dns strings with the new one
                line = line.replace(item, new)
            if not line in new_lines: # but don't add if the line is already extant
                new_lines.append(line)

    for line in new_lines:
        f_.write(line)

    #properly complete file operation
    f_.flush()
    f_.close()


if __name__ == "__main__":

    # set vars

    SUFFIX = ".jaunty-end-of-life.orig"

    LOC = os.path.join("/etc", "apt")

    #TODO: comment next line out when not testing:
    #LOC = os.path.join(os.getcwd(), "etc", "apt")

    S_L = os.path.join(LOC, 'sources.list')

    # get files in sources.list.d/
    S_L_Ds_all = os.listdir(os.path.join(LOC, "sources.list.d"))
    S_L_Ds = []

    # but only work with sources.list.d/ files that end with ".list"
    for item in S_L_Ds_all:
        if item.endswith(".list"):
            S_L_Ds.append(item)

    # set search strings that need to be found/replaced
    OLD = [
            'http://archive.ubuntu.com/ubuntu jaunty',
            'http://archive.ubuntu.com/ubuntu/ jaunty',
            'http://ports.ubuntu.com/ jaunty',
            'http://security.ubuntu.com/ubuntu jaunty',
            'http://security.ubuntu.com/ubuntu/ jaunty',
            ]

    # replacement 
    NEW = 'http://old-releases.ubuntu.com/ubuntu jaunty'

    # display opening messages to stdout
    display_messages(SUFFIX)

    # backup sources.list, if any
    if os.path.exists(S_L):
        backup(S_L, SUFFIX)

    # backup *.list files in sources.list.d/
    for item in S_L_Ds:
        backup(os.path.join(LOC, "sources.list.d", item), SUFFIX)

    # fix urls in sources.list, if it exists
    if os.path.exists(S_L):
        fix_urls(S_L, OLD, NEW)

    # fix urls in sources.list.d/*list files, if any
    for item in S_L_Ds:
        fix_urls(os.path.join(LOC, "sources.list.d", item), OLD, NEW)

    print "\nCompleted.\n"

    sys.exit(0)
