#!/usr/bin/python
# -*- coding: utf8 -*-

# A script to convert the Akabei local database into a Pacman one
# Still experimental and work-in-progress, do not rely on it.
#
#   Copyright (C) 2016 Lisa Vitolo <shainer@chakralinux.org>

#   This program 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.

import getopt
import sys
import os
import sqlite3

from akabeipackageparser import AkabeiPackageParser
from db_import import *

def parseLocalDatabase(akabeiDb, schemeFile):
    c = sqlite3.connect(akabeiDb)
    packages = []

    # TODO: use progress bar here.
    for row in c.execute('SELECT * FROM packages;'):
        akabeiParser = AkabeiPackageParser(c, row)
        if not akabeiParser.parsePackage():
            print '[!!] Invalid package, skipping.'
            continue

        packages.append(akabeiParser.getPackage())
        print(akabeiParser.getPackage())

    return packages


def DoConversion(pacmanConf, inputFile, schemeFile):
    # Gets the database path from the pacman configuration
    print "[**] Reading Pacman database path from " + pacmanConf + "...",
    dbpath = getDatabasePath(pacmanConf)
    print "done."
    if len(dbpath) == 0:
        dbpath = "/var/lib/pacman" # if not explicitly set there, then go back to the default value
    
    pacmanLocalPath = os.path.join(dbpath, "local")
    
    # Get local packages from akabei, then write them into the pacman "database" in the right format
    
    print "[**] Parsing Akabei local database..."
    localPackages = parseLocalDatabase(inputFile, schemeFile)
    print "done."
    
    # TODO
    #dbwriter = PacmanDbWriter(outputFile, schemeFile)
    #dbwriter.addPackages(localPackages)
    
    print "[**] Database converted successfully. Hope to see you again soon!"

# Entry point.
# TODO: needs more extensive testing.
if __name__ == "__main__":
    
    # Default values for files
    pacmanConf = "/etc/pacman.conf"
    inputFile = "local.db"
    schemeFile = "/usr/share/akabei/dbschema.sql"
    opts = None
    
    # Reads options from command line.
    try:
        opts = getopt.getopt(sys.argv[1:], "hp:i:s:", ["help", "--pacman=" "--db-input=", "--db-scheme="])
    except getopt.GetoptError, error:
        print str(error)
        usage()
        sys.exit(-1)
    
    # Parse options and overrides defaults if needed.
    for opt, arg in opts[0]:
        if len(arg) > 0 and arg[0] == '=':
            arg = arg[1:]
        
        if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif opt in ("-p", "--pacman"):
            pacmanConf = arg
        elif opt in ("-i", "--db-input"):
            inputFile = arg
        elif opt in ("-s", "--db-scheme"):
            schemeFile = arg
            
    print "==== Akabei database conversion script v0.1 ==== "
    print "This script may take some time to finish."
    print
   
    DoConversion(pacmanConf, inputFile, schemeFile)
