#! /usr/bin/python2.7
#
# Migrate data from the rss2email 2.x format to the 3.x format.
#
# Copyright (c) 2013, Etienne Millon <me@emillon.org>
# Redistributable under the GPL version 2 or later
#
# Please report bugs and suggestion on the Debian bugtracker using the
# "reportbug rss2email" command.
#
# Changelog:

#   v2 (2013-09-17)
#      - Preserve paused status (Denis Laxalde)
#
#   v1 (2013-08-12)
#      - Migrate feed names only.
#

import os.path
import pickle
import string
import subprocess
import sys


class Feed:
    def __init__(self, url, to):
        self.url, self.etag, self.modified, self.seen = url, None, None, {}
        self.active = True
        self.to = to

    def __repr__(self):
        fmt = '\n'.join(['Feed(url={url},',
                         '     etag={etag},',
                         '     modified={modified},',
                         '     seen={seen},',
                         '     active={active},',
                         '     to={to},',
                         ')',
                         ])
        return fmt.format(**self.__dict__)


def new_db_exists():
    config = os.path.expanduser('~/.config/rss2email.cfg')
    data = os.path.expanduser('~/.local/rss2email.json')
    return os.path.exists(config) or os.path.exists(data)


def set_email(s):
    return subprocess.call(['r2e', 'email', s])


def slugify_char(c):
    allowed = string.ascii_letters + string.digits + '._-'
    if c in allowed:
        return c
    else:
        return '_'


def slugify(s):
    return ''.join([slugify_char(c) for c in s])


def add(url):
    return subprocess.call(['r2e', 'add', slugify(url), url])

def pause(url):
    return subprocess.call(['r2e', 'pause', slugify(url)])

def main():
    if new_db_exists():
        print """
        It seems that a rss2email 3.x database already exists, exiting.
        If you want to import your old (rss2email 2.x) database, please remove
        ~/.config/rss2email.cfg and ~/.local/rss2email.json and re-run
        r2e-migrate.
        """
        sys.exit(1)

    old_feed_data_file = os.path.expanduser('~/.rss2email/feeds.dat')
    with open(old_feed_data_file) as f:
        data = pickle.load(f)

    email = data[0]
    feeds = data[1:]

    print 'Default email address: {}'.format(email)
    set_email(email)

    print 'Adding feeds:'
    for feed in feeds:
        url = feed.url
        print url
        add(url)
        if not feed.active:
            pause(url)

if __name__ == '__main__':
    main()
