#!/usr/bin/python3

# system76-driver: Universal driver for System76 computers
# Copyright (C) 2005-2016 System76, Inc.
#
# This file is part of `system76-driver`.
#
# `system76-driver` 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 2 of the License, or
# (at your option) any later version.
#
# `system76-driver` 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 `system76-driver`; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import argparse
import os
from os import path
import sys
import logging

import system76driver
from system76driver.products import PRODUCTS
from system76driver.actions import ActionRunner
from system76driver.util import create_logs

parser = argparse.ArgumentParser()
parser.add_argument('--strict', action='store_true', default=False,
    help='Exit with a non-zero status if not a valid system76 product',
)
parser.add_argument('--model', help='force model rather than detecting it')
parser.add_argument('--logs', help='Store logs to specified home directory')
args = parser.parse_args()
exitcode = (2 if args.strict else 0)

# Because system76-driver-cli will be called automatically from the postinst
# script, we don't log to /var/log/system76-driver.log
logging.basicConfig(
    level=logging.DEBUG,
    format='%(levelname)s\t%(message)s',
)
log = logging.getLogger()

# This is a hack so that the driver doesn't get run in the VM when mastering
# and maintaining the golden images:
MARKER = '/var/cache/system76-pre-master.marker'
if path.exists(MARKER):
    log.warning('Pre-master marker exists: %r', MARKER)
    sys.exit(0)


product_version = args.model or system76driver.get_product_version()
try:
    product = PRODUCTS[product_version]
    log.info('product_version: %r', product_version)
except KeyError:
    log.warning('invalid product_version: %r', product_version)
    sys.exit(exitcode)

if os.getuid() != 0:
    log.error('must be run as root')
    sys.exit(exitcode)

try:
    if args.logs is not None:
        tgz = create_logs(args.logs)
        log.info('logs stored in %s', tgz)
    else:
        action_runner = ActionRunner(product['drivers'])
        for msg in action_runner.run_iter():
            log.info('* %s', msg)
except Exception:
    log.exception('Error running actions:')
    sys.exit(exitcode)

