#!/usr/bin/env python3
# vim: set ts=4 sw=4 fileencoding=utf-8:
# Luomio <nohappiness@gmail.com>
# Filename: dde-first-run.py
# Create Date: 27-03, 13

from os import path, remove
import locale
import os
import pwd
import shutil
import getpass
import re
import subprocess
import time
import logging
from gi.repository import GLib


logging.basicConfig(filename=os.path.expanduser("~") + '/.config/dde-first-run.log_' + pwd.getpwuid(os.getuid())[0], level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('=== Start logging')

def querySystemType():
    f = open("/etc/deepin-version", "r")
    content = f.read()

    r = re.search(r"^Type=(.*)$", content, re.M)

    return r.group(1)


def queryXDGDesktopDir():
    return GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP)


def copyDesktopFile(user_desktop_path, desktop_files):
    logging.debug('Copy desktop file')
    if not path.exists(user_desktop_path):
        os.makedirs(user_desktop_path)
    for file in desktop_files:
        desktop_file = path.join("/usr/share/applications", file)
        if path.exists(desktop_file):
            logging.debug('Copy desktop file: {}'.format(desktop_file))
            dst_desktop_file = path.join(user_desktop_path, file)
            shutil.copyfile(desktop_file, dst_desktop_file)
            try:
                subprocess.run(["sync", dst_desktop_file])
                logging.debug('Sync desktop file: {} success'.format(desktop_file)) 
            except subprocess.CalledProcessError as e:
                logging.warning('Sync desktop file: {} failed'.format(desktop_file)) 
        else:
            logging.debug('File not exists: {}, abandoned'.format(desktop_file))
    logging.debug('Copy desktop file done')


def checkDesktopFiles(user_desktop_path, desktop_files):
    logging.debug('Check desktop file')
    for file in desktop_files:
        src_desktop_file = path.join("/usr/share/applications", file)
        dst_desktop_file = path.join(user_desktop_path, file)
        if path.exists(src_desktop_file):
            if path.exists(dst_desktop_file) == False:
                logging.debug('Destination desktop file not exists: {}'.format(dst_desktop_file))
                return False
            if os.path.getsize(src_desktop_file) != os.path.getsize(dst_desktop_file):
                logging.debug('File size not match between {} and {}'.format(src_desktop_file, dst_desktop_file))
                return False
            logging.debug('Check desktop file: {}'.format(dst_desktop_file))
        else:
            logging.debug('Source desktop file not exists: {}, abandoned'.format(src_desktop_file))
    logging.debug('Check desktop file done')
    return True


if __name__ == "__main__":
    lang, charset = locale.getdefaultlocale()
    sys_type = querySystemType()
    desktop_path = queryXDGDesktopDir()

    introduction = "/usr/bin/dde-introduction"
    if path.exists(introduction):
        logging.debug('Open {}'.format(introduction))
        subprocess.Popen(introduction)
    else:
        logging.warning('File not exists: {}'.format(introduction))

    # create symlink for introduction video
    # fix introduction to demo.mp4,different mirror interfaces are consistent,but the content is different
    introduction_video_path = "/usr/share/dde-introduction/demo.mp4"
    introduction_video_link_path = "~/Videos/dde-introduction.mp4"
    if path.exists(introduction_video_path):
        if path.exists(path.expanduser(introduction_video_link_path)):
            remove(path.expanduser(introduction_video_link_path))
        os.symlink(introduction_video_path, path.expanduser('~/Videos/dde-introduction.mp4'))
        logging.debug('Create symlink from {} to {}'.format(introduction_video_path, introduction_video_link_path))
    else:
        logging.debug('File not exists {}, abandoned'.format(introduction_video_path))

    desktops = ['dde-computer.desktop', 'dde-trash.desktop', 'dde-home.desktop', 'deepin-tooltips.desktop']
    retry_count = 3
    if sys_type != "Desktop":
        copyDesktopFile(desktop_path, desktops)

        # To avoid copy file failed, check it 3 times
        while(checkDesktopFiles(desktop_path, desktops) == False and retry_count > 0):
            retry_count = retry_count - 1
            time.sleep(1)
            copyDesktopFile(desktop_path, desktops)

    chrome_config = None
    if not path.exists(path.expanduser('~/.config/google-chrome')):
        if path.exists('/usr/share/deepin-default-settings/google-chrome/override-chrome-config.tar'):
            chrome_config = '/usr/share/deepin-default-settings/google-chrome/override-chrome-config.tar'
        elif path.exists('/usr/share/deepin-default-settings/google-chrome/chrome-config-%s.tar' % lang):
            chrome_config = '/usr/share/deepin-default-settings/google-chrome/chrome-config-%s.tar' % lang
        elif path.exists('/usr/share/deepin-default-settings/google-chrome/chrome-config.tar'):
            chrome_config = '/usr/share/deepin-default-settings/google-chrome/chrome-config.tar'
        else:
            chrome_config = None

    if chrome_config is not None:
        import tarfile
        tar = tarfile.open(chrome_config)
        tar.extractall(path.expanduser('~/.config/'))
        tar.close()

    if path.exists(path.expanduser('~/.config/google-chrome/PepperFlash/latest-component-updated-flash')):
        user_name=getpass.getuser()
        pepperflash = path.expanduser('~/.config/google-chrome/PepperFlash/latest-component-updated-flash')
        with open(pepperflash,"r") as f:
            lines = f.readlines()
        with open(pepperflash,"w") as f:
            for line in lines:
                f.write(re.sub(r'deepin',user_name,line))

    if path.exists(path.expanduser('~/.config/autostart/dde-first-run.desktop')):
        remove(path.expanduser('~/.config/autostart/dde-first-run.desktop'))
