#!/usr/bin/python3
import argparse
from contextlib import closing
import os
import sqlite3
import sys
from termcolor import colored

db_file = os.path.join(os.environ["HOME"],
                       ".cache/check-kernel-fix/conf_file_map.sqlite")
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--db-file', default=os.path.join(os.environ["HOME"],
                            ".cache/check-kernel-fix/conf_file_map.sqlite"))
parser.add_argument('-D', '--detail', action='store_true')
parser.add_argument('path', nargs='+')
args = parser.parse_args()

if not os.path.exists(args.db_file):
    sys.exit(f"db '{args.db_file}' not found")

with closing(sqlite3.connect(args.db_file)) as db:
    db.execute('PRAGMA foreign_keys = ON;')
    with closing(db.cursor()) as cursor:
        for path in args.path:
            (dir, filename) = os.path.split(path)
            print(colored(path, 'green'))
            for row in cursor.execute('''SELECT config.config, branch.branch
                    FROM conf_file_map AS map
                    LEFT JOIN config ON map.config = config.id
                    LEFT JOIN branch ON map.branch = branch.id
                    WHERE map.file = (SELECT id FROM file WHERE file = ?
                        AND dir = (SELECT id FROM dir WHERE dir = ?))
                    ORDER BY 2, 1;''', (filename, dir)):
                print(f"\t{row[1]:>25}: {row[0]}")
