#!/usr/bin/env python3


from pprint import pprint
import daemon
import time
import argparse
import os
import json
from pyf import download, prt, sha256


WORKDIR = os.getcwd()


def init_parser():
    ''' initialize the argument parser
        @return agrs: the parsed arguments
    '''
    parser = argparse.ArgumentParser(description='flash linux operating systems on the fly')
    parser.add_argument('os',
                        default='arch',
                        metavar='os',
                        help='the operating system that should be flashed')
    parser.add_argument('storage',
                        metavar='storage',
                        help='the storage where the os shall be flashed')
    return parser.parse_args()


# c: is there a *testfile_sha256* sum?
# -> no: download image file
# -> yes: goto d
# 
# d: download testfile
# is sha256 sum of testfile and *testfile_sha256* equivalent?
# -> no: download image file
# -> yes: break
def check_update(database):
    ''' check if update is necessary '''
    from urllib.parse import urlparse
    from os import path
    from datetime import datetime
    for name, dist in database.items():
        prt('checking operating system {} ...'.format(name))

        if dist['file_url'] == '':
            prt('database.txt: `file_url` not specified, skipping ...')
            continue

        #TODO check if donwload was successful, if not do stuff
        if dist['file_name'] == '':
            prt('database.txt: `file_name` not specified')
            #TODO get real file_name and save it to database.txt
            file_name = urlparse(dist['file_url'])
            file_name = file_name.path
            file_name = '{}/dist/{}'.format(WORKDIR, path.basename(file_name))
            download(dist['file_url'], file_name)
            continue

        file_name = '{}/dist/{}'.format(WORKDIR, dist['file_name'])
        if not path.isfile(file_name):
            prt('database.txt: `file_name` {} does not exist on your filesystem'.format(file_name))
            download(dist['file_url'], file_name)
            continue

        if dist['interval'] == '':
            prt('database.txt: `interval` not specified')
            download(dist['file_url'], file_name)
            continue

        file_mod = datetime.fromtimestamp(path.getmtime(file_name))
        file_age = (datetime.now() - file_mod).days
        if file_age < int(dist['interval']):
            prt('{} is younger than {} days, skipping ...'.format(
                name, dist['interval']))
            continue
        else:
            prt('{} is older than {} days'.format(name, file_age))

        if dist['test_url'] == '':
            prt('database.txt: `test_url` not specified')
            download(dist['file_url'], file_name)
            continue

        if dist['test_name'] == '':
            prt('database.txt: `test_name` not specified')
            #TODO write test_name to database.txt
            test_name = urlparse(dist['test_url'])
            test_name = test_name.path
            test_name = '{}/dist/{}'.format(WORKDIR, path.basename(test_name))
        else:
            test_name = '{}/dist/{}'.format(WORKDIR, dist['test_name'])

        if not path.isfile(test_name):
            prt('database.txt: `test_name` {} does not exist on your filesystem'.format(test_name))
            download(dist['test_url'], test_name)
            download(dist['file_url'], file_name)
            continue

        prt(test_name)
        test_sha256_old = sha256(test_name)
        download(dist['test_url'], test_name)
        test_sha256_new = sha256(test_name)

        if not test_sha256_old == test_sha256_new:
            prt('`test_file` {} has changed'.format(test_name))
            download(dist['file_url'], file_name)
            continue

        prt('{} is still up to date, skipping ...'.format(name))


def read_os_database():
    ''' read the os database.txt file
        @return a json object of the database
    '''
    with open('{}/database.txt'.format(WORKDIR), 'r') as f:
        return json.load(f)


# https://stackoverflow.com/questions/4637420/efficient-python-daemon#8375012
def run_daemon():
    ''' run the daemon '''
    with daemon.DaemonContext():
        check_update()


if __name__ == '__main__':
    args = init_parser()
    database = read_os_database()
    check_update(database)
#     run_daemon()
