#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2018 The gPodder Team
#
# gPodder 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 3 of the License, or
# (at your option) any later version.
#
# gPodder 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, see <http://www.gnu.org/licenses/>.
#


# gpodder-migrate2tres - Migrate data from gPodder 2.x to gPodder 3
# by Thomas Perl <thp@gpodder.org>; 2011-04-28


import configparser
import os
import shutil
import sys

gpodder_script = sys.argv[0]
gpodder_script = os.path.realpath(gpodder_script)
gpodder_dir = os.path.join(os.path.dirname(gpodder_script), '..')
prefix = os.path.abspath(os.path.normpath(gpodder_dir))

src_dir = os.path.join(prefix, 'src')

if os.path.exists(os.path.join(src_dir, 'gpodder', '__init__.py')):
    # Run gPodder from local source folder (not installed)
    sys.path.insert(0, src_dir)

import gpodder  # isort:skip

gpodder.prefix = prefix

from gpodder import schema, util  # isort:skip

old_database = os.path.expanduser('~/.config/gpodder/database.sqlite')
new_database = gpodder.database_file

old_config = os.path.expanduser('~/.config/gpodder/gpodder.conf')
new_config = gpodder.config_file

if not os.path.exists(old_database):
    print("""
    Turns out that you never ran gPodder 2.
    Can't find this required file:

       %(old_database)s
    """ % locals(), file=sys.stderr)
    sys.exit(1)

old_downloads = None

if os.path.exists(old_config):
    parser = configparser.RawConfigParser()
    parser.read(old_config)
    try:
        old_downloads = parser.get('gpodder-conf-1', 'download_dir')
    except configparser.NoSectionError:
        # The file is empty / section (gpodder-conf-1) not found
        pass
    except configparser.NoOptionError:
        # The section is available, but the key (download_dir) is not
        pass

if old_downloads is None:
    # The user has no configuration. This usually happens when
    # only the CLI version of gPodder is used. In this case, the
    # download directory is most likely the default (bug 1434)
    old_downloads = os.path.expanduser('~/gpodder-downloads')

new_downloads = gpodder.downloads

if not os.path.exists(old_downloads):
    print("""
    Old download directory does not exist. Creating empty one.
    """, file=sys.stderr)
    os.makedirs(old_downloads)

if any(os.path.exists(x) for x in (new_database, new_downloads)):
    print("""
    Existing gPodder 3 user data found.
    To continue, please remove:

       %(new_database)s
       %(new_downloads)s
    """ % locals(), file=sys.stderr)
    sys.exit(1)

print("""
  Would carry out the following actions:

      Move downloads from %(old_downloads)s
                       to %(new_downloads)s

      Convert database from %(old_database)s
                         to %(new_database)s

""" % locals(), file=sys.stderr)

result = input('Continue? (Y/n) ')

if result in 'Yy':
    util.make_directory(gpodder.home)
    schema.convert_gpodder2_db(old_database, new_database)
    if not os.path.exists(new_database):
        print('Could not convert database.', file=sys.stderr)
        sys.exit(1)

    shutil.move(old_downloads, new_downloads)
    if not os.path.exists(new_downloads):
        print('Could not move downloads.', file=sys.stderr)
        sys.exit(1)

    print('Done. Have fun with gPodder 3!')
