#!/usr/bin/python3

# Copyright (C) 2015 Martin Wimpress <code@ubuntu-mate.org>
#
# 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 glob
import os
import platform
import subprocess
import sys
import 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'])

if __name__ == "__main__":
    if len(sys.argv) >= 3:
        repository = sys.argv[1]
        action = sys.argv[2]
    else:
        print('No repository supplied')
        sys.exit(1)

    codename = platform.dist()[2]

    if action == 'install':
        if repository ==  'appgrid':
            enable_partner_repository()
            enable_ppa('ppa:appgrid/stable')
        if repository ==  'dropbox':
            if codename == 'wily':
                codename = 'vivid'
            add_apt_key_from_keyserver('pgp.mit.edu', '5044912E')
            add_apt_sources(['deb http://linux.dropbox.com/ubuntu/ ' + codename + ' main'], repository)
        elif repository ==  'eviacam':
            enable_ppa('ppa:cesar-crea-si/eviacam')
        elif repository ==  'adobe-flashplugin':
            enable_partner_repository()
            enable_ppa('ppa:flexiondotorg/hal-flash')
        elif repository ==  'google-chrome':
            add_apt_key_from_url('http://dl.google.com/linux/linux_signing_key.pub')
            add_apt_sources(['deb http://dl.google.com/linux/chrome/deb/ stable main'], repository)
        elif repository ==  'google-earth':
            add_apt_key_from_url('http://dl.google.com/linux/linux_signing_key.pub')
            add_apt_sources(['deb http://dl.google.com/linux/earth/deb/ stable main'], repository)
        elif repository ==  'google-talkplugin':
            add_apt_key_from_url('http://dl.google.com/linux/linux_signing_key.pub')
            add_apt_sources(['deb http://dl.google.com/linux/talkplugin/deb/ stable main'], repository)
        elif repository ==  'google-musicmanager':
            add_apt_key_from_url('http://dl.google.com/linux/linux_signing_key.pub')
            add_apt_sources(['deb http://dl.google.com/linux/musicmanager/deb/ stable main'], repository)
        elif repository ==  'handbrake':
            if codename != 'wily':
                enable_ppa('ppa:stebbins/handbrake-releases')
        elif repository ==  'insync':
            if codename == 'wily':
                codename = 'vivid'
            add_apt_key_from_url('https://d2t3ff60b2tol4.cloudfront.net/services@insynchq.com.gpg.key')
            add_apt_sources(['deb http://apt.insynchq.com/ubuntu ' + codename + ' non-free contrib'], repository)
        elif repository ==  'libdvdcss2':
            add_apt_key_from_url('http://download.videolan.org/pub/debian/videolan-apt.asc')
            add_apt_sources(['deb http://download.videolan.org/pub/debian/stable/ /',
                             'deb-src http://download.videolan.org/pub/debian/stable/ /'], repository)
        elif repository == 'makemkv':
            enable_ppa('ppa:heyarje/makemkv-beta')
        elif repository ==  'minecraft':
            enable_ppa('ppa:minecraft-installer-peeps/minecraft-installer')
        elif repository ==  'mumble':
            if codename == 'precise' or codename == 'trusty':
                enable_ppa('ppa:mumble/release')
        elif repository ==  'pithos':
            if codename == 'precise' or codename == 'trusty':
                enable_ppa('ppa:pithos/ppa')
        elif repository ==  'skype':
            enable_partner_repository()
        elif repository ==  'simplescreenrecorder':
            enable_ppa('ppa:maarten-baert/simplescreenrecorder')
            if codename == 'wily':
                add_apt_sources(['deb http://ppa.launchpad.net/maarten-baert/simplescreenrecorder/ubuntu vivid main',
                                 'deb-src http://ppa.launchpad.net/maarten-baert/simplescreenrecorder/ubuntu vivid main'],
                                 'maarten-baert-ubuntu-simplescreenrecorder-' + codename)
        elif repository == 'spideroakone':
            add_apt_key_from_url('https://spideroak.com/dist/spideroak-apt-2013.asc')
            add_apt_sources(['deb http://APT.spideroak.com/ubuntu-spideroak-hardy/ release restricted',
                             ' '], repository)
        elif repository ==  'spotify':
            add_apt_key_from_keyserver('keyserver.ubuntu.com', 'D2C19886')
            add_apt_sources(['deb http://repository.spotify.com testing non-free'], repository)
        elif repository ==  'steam':
            add_apt_key_from_url('http://repo.steampowered.com/steam/signature.gpg')
            add_apt_sources(['deb [arch=amd64,i386] http://repo.steampowered.com/steam/ precise steam',
                             'deb-src [arch=amd64,i386] http://repo.steampowered.com/steam/ precise steam',
                             ''], repository)

        elif repository ==  'synapse':
            enable_ppa('ppa:synapse-core/testing')
        elif repository ==  'syncthing':
            add_apt_key_from_url('https://syncthing.net/release-key.txt')
            add_apt_sources(['deb http://apt.syncthing.net/ syncthing release'], repository)
        elif repository ==  'telegram':
            enable_ppa('ppa:atareao/telegram')
        elif repository ==  'ubuntu-sdk':
            enable_ppa('ppa:ubuntu-sdk-team/ppa')
        elif repository ==  'uget':
            enable_ppa('ppa:plushuang-tw/uget-stable')
        elif repository ==  'veracrypt':
            enable_ppa('ppa:unit193/encryption')
        elif repository == 'virtualbox':
            if codename == 'wily':
                codename = 'vivid'
            add_apt_key_from_url('https://www.virtualbox.org/download/oracle_vbox.asc')
            add_apt_sources(['deb http://download.virtualbox.org/virtualbox/debian ' + codename + ' contrib'], repository)
        elif repository ==  'x2go':
            enable_ppa('ppa:x2go/stable')
        else:
            print('Repository ' + repository + ' is unknown.')
    elif action == 'remove':
        del_apt_sources(repository)
