#!/usr/bin/python3

# Copyright (C) 2015 Martin Wimpress <code@ubuntu-mate.org>
# Copyright (C) 2016 Luke Horwell <lukehorwell37+code@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

import os, sys, platform, subprocess, json, glob, urllib.request

def del_apt_sources(listname):
    for filename in glob.glob(os.path.join('/','etc','apt','sources.list.d','*'+listname+'*.list*')):
        os.remove(filename)

def add_apt_sources(source, listname):
    #subprocess.call(['aptdcon', '--add-repository=' + source, '--sources-file', listname + '.list'])
    sources_file = os.path.join('/','etc','apt','sources.list.d',listname + '.list')
    print('Writing: ' + sources_file)
    with open(sources_file, 'w') as f:
        f.write('\n'.join(source))

def add_apt_key_from_url(key_url):
    #subprocess.call(['aptdcon', '--add-vendor-key=' + os.path.join('/', 'tmp', 'pub.key')])
    temp_key = os.path.join('/', 'tmp', 'pub.key')
    print('Processing: ' + key_url)
    if os.path.exists(temp_key):
        os.remove(temp_key)

    # Download the file from `url` and save it locally under `file_name`:
    with urllib.request.urlopen(key_url) as response, open(temp_key, 'wb') as out_file:
        data = response.read() # a `bytes` object
        out_file.write(data)
    subprocess.call(['apt-key', 'add', temp_key])

def add_apt_key_from_keyserver(keyserver, key):
    subprocess.call(['apt-key', 'adv', '--keyserver', keyserver, '--recv-keys', key])

def enable_ppa(ppa):
    subprocess.call(['apt-add-repository', '--enable-source', '--yes', ppa])

def enable_partner_repository():
    subprocess.call(['apt-add-repository', '--enable-source', '--yes', 'http://archive.canonical.com/ubuntu partner'])


def finish(err=0):
    ''' Close the application '''
    print('--------------------------------------------------------------')
    sys.exit(err)

if __name__ == "__main__":
    '''
        This script requires the following variables:
            [0] = Path to the Application Index JSON
            [1] = Function to perform
            [2] = Program's category
            [3] = Program ID
            [4] = "Target" instructions to read. Contains a codename or "all"

        This script will directly read the Application Index JSON.
    '''
    print('--- Repository Installer -------------------------------------')

    # Set important variables.
    os_version = platform.dist()[1]
    codename = platform.dist()[2]

    try:
        json_path = sys.argv[1]
        function = sys.argv[2]
        category = sys.argv[3]
        program_id = sys.argv[4]
        target = sys.argv[5]
    except:
        print('This script requires parameters that are retrieved via ubuntu-mate-welcome.')
        finish(1)

    # Load the Application Index
    if os.path.exists(json_path):
        with open(json_path) as data_file:
            index = json.load(data_file)
    else:
        print('The application index does not exist: "' + json_file + '".')
        finish(1)

    # Perform functions based on the parameters.
    if function == 'add_apt_key_from_keyserver':
        keyserver = index[category][program_id]['pre-install'][target]['apt-key-server'][0]
        key = index[category][program_id]['pre-install'][target]['apt-key-server'][1]
        add_apt_key_from_keyserver(keyserver, key)

    elif function == 'add_apt_key_from_url':
        url = index[category][program_id]['pre-install'][target]['apt-key-url']
        add_apt_key_from_url(url)

    elif function == 'add_apt_sources':
        source_raw = index[category][program_id]['pre-install'][target]['apt-sources']
        source_data = []
        for line in source_raw:
            source_data.append(line.replace('OSVERSION',os_version).replace('CODENAME',codename))
        list_name = index[category][program_id]['pre-install'][target]['source-file']
        list_name = list_name.replace('OSVERSION',os_version).replace('CODENAME',codename)
        add_apt_sources(source_data, list_name)

    elif function == 'del_apt_sources':
        list_name = index[category][program_id]['pre-install'][target]['source-file']
        list_name = list_name.replace('OSVERSION',os_version).replace('CODENAME',codename)
        del_apt_sources(list_name)

    elif function == 'enable_partner_repository':
        enable_partner_repository()

    elif function == 'enable_ppa':
        ppa = index[category][program_id]['pre-install'][target]['enable-ppa']
        enable_ppa(ppa)

    else:
        print('Invalid function specified: ' + function)
        finish(1)

    print('Successfully performed function: "' + function + '" for "' + program_id + '".')
    finish(0)
