#! /usr/bin/python
# This program is free software: you can redistribute it and/or modify it
# under the terms of the the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the applicable version of the GNU Lesser 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/>.
#
# Copyright (C) 2013 Canonical, Ltd.

import argparse
import logging
import tempfile
import StringIO
import os
from phabletutils.device import AndroidBridge
from phabletutils import downloads
from phabletutils import fileutils

logging.basicConfig(level=logging.INFO, format='%(message)s')
log = logging.getLogger()
log.name = 'phablet-demo-setup'


basic_template = '''#!/bin/sh
set -ex
'''

SERVER_URL = 'http://people.canonical.com/~cwayne/phablet-tools'
TMP_DOWNLOAD_DIR = fileutils.create_temp_dir()


def download(artifact):
    '''Downloads demo content onto the host, to be pushed to device'''
    remote_file = '%s/%s' % (SERVER_URL, artifact)
    download_path = os.path.join(TMP_DOWNLOAD_DIR, artifact)
    if not os.path.isfile(download_path):
        downloads._download(remote_file, download_path)
    return download_path


def parse_arguments():
    '''Parses arguments passed in to script.'''
    parser = argparse.ArgumentParser(
        description='''phablet demo setup tool. Requires a prior run
                       of phablet-networking-setup -i. If called with
                       no options all demo content available is setup.''')
    parser.add_argument('-s',
                        '--serial',
                        help='''Device serial. Use when more than
                                one device is connected.''',
                        )
    parser.add_argument('--disable-fake-contacts',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Disables setup of demo contacts.'
                        )
    parser.add_argument('--disable-fake-messages',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Disables setup of demo messages.'
                        )
    parser.add_argument('--disable-fake-pictures',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Disables setup of demo pictures.'
                        )
    return parser.parse_args()


def setup_fake_pictures(script):
    script.write('tar -C /home/phablet/Pictures/ --strip-components=1 -xzf '
                 '/tmp/pictures.tgz\n')
    return script


def setup_fake_contacts(script):
    script.write('tar -C /home/phablet -xzf /tmp/contacts.tgz \n')
    script.write('/home/phablet/.local/bin/manage-address-books create \n')
    return script


def setup_fake_conversations(script):
    script.write('tar -C /home/phablet -xzf /tmp/conversations.tgz \n')
    return script


def provision_device(adb, serial, script):
    script_dst = '/tmp/provision'
    adb.push(script, script_dst)
    adb.chmod(script_dst, '700')
    adb.shell('sh ' + script_dst)
    log.info('Getting ready to restart')
    adb.shell('sync')


def main(args):
    if args.serial:
        adb = AndroidBridge(args.serial)
    else:
        adb = AndroidBridge()
    dest = '/tmp'
    script = StringIO.StringIO()
    script.write(basic_template)
    if not args.disable_fake_contacts:
        log.info('Setting up for demo contacts')
        contact_tar = download('contacts.tgz')
        adb.push(contact_tar, dest)
        script = setup_fake_contacts(script)
    if not args.disable_fake_messages:
        log.info('Setting up for demo conversations')
        convo_tar = download('conversations.tgz')
        adb.push(convo_tar, dest)
        script = setup_fake_conversations(script)
    if not args.disable_fake_pictures:
        log.info('Setting up for demo pictures')
        pictures_tar = download('pictures.tgz')
        adb.push(pictures_tar, dest)
        script = setup_fake_pictures(script)
    script_file = tempfile.NamedTemporaryFile(delete=False)
    with script_file as f:
        f.write(script.getvalue())
    script.close()
    provision_device(adb, args.serial, script_file.name)


if __name__ == "__main__":
    args = parse_arguments()
    main(args)
