#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# === This file is part of Chakra - <https://www.chakralinux.org> ===
#
#   Copyright 2015, Luca Giambonini <almack@chakralinux.org>
#
#   Calamares 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 3 of the License, or
#   (at your option) any later version.
#
#   Calamares 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 Calamares. If not, see <http://www.gnu.org/licenses/>.
#  MA 02110-1301, USA.

import os
import subprocess
import shutil
import urllib.request
import re

import libcalamares

def run():
    """ Clean up unused drivers """

    print('configure_pacman')

    install_path = libcalamares.globalstorage.value("rootMountPoint")

    # remove any db.lck
    db_lock = os.path.join(install_path, "var/lib/pacman/db.lck")
    if os.path.exists(db_lock):
        with misc.raised_privileges():
            os.remove(db_lock)

    if libcalamares.globalstorage.value("hasInternet"):
      # uncomment all mirrors in default mirrorlist
      with open(os.path.join(install_path,'etc/pacman.d/mirrorlist'), "r") as sources:
          lines = sources.readlines()
      with open(os.path.join(install_path,'etc/pacman.d/mirrorlist'), "w") as sources:
          for line in lines:
              sources.write(re.sub(r'^#Server', 'Server', line))

      # run rankmirrors and check for the 3 best mirrors
      p = subprocess.Popen("rankmirrors -t -n 3 -r core {!s} | grep repo | cut -d ' ' -f 1".format(os.path.join(install_path,'etc/pacman.d/mirrorlist')),
                          shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

      # Iterates over every found mirror and put each one in a list
      mirrors = []
      for line in p.stdout.readlines():
          s = line.decode('ascii')
          s = s.rstrip('\n')
          mirrors.append(s)

      # create a new mirrorlist
      #mirrorlist = open('/etc/pacman.d/mirrorlist.new', 'w+')
      with open(os.path.join(install_path,'etc/pacman.d/mirrorlist.new'),"a+") as f:
          f.write("# mirrorlist generated by rankmirrors during chakra installation\n")
          f.write("# the original file was saved to /etc/pacman.d/mirrorlist.pacsave\n\n")
          for mirror in mirrors:
              f.write("Server = {!s}\n".format(mirror))

      # backup old mirrorlist
      os.rename(os.path.join(install_path,'etc/pacman.d/mirrorlist'), os.path.join(install_path,'etc/pacman.d/mirrorlist.pacsave'))
      # install new mirrorlist
      os.rename(os.path.join(install_path,'etc/pacman.d/mirrorlist.new'), os.path.join(install_path,'etc/pacman.d/mirrorlist'))
      # update pacman db
      libcalamares.utils.target_env_call(["pacman", "-Syy", "--noconfirm"])
    else:
      print('no internet connection available. enable default server')
      # backup old mirrorlist
      shutil.copy(os.path.join(install_path,'etc/pacman.d/mirrorlist'), os.path.join(install_path,'etc/pacman.d/mirrorlist.pacsave'))

      # enable default server
      with open(os.path.join(install_path,'etc/pacman.d/mirrorlist'), "r") as sources:
          lines = sources.readlines()
      with open(os.path.join(install_path,'etc/pacman.d/mirrorlist'), "w") as sources:
          for line in lines:
              sources.write(re.sub(r'^#Server = http://archlinux.puzzle.ch', 'Server = http://archlinux.puzzle.ch', line))

    print('configure_pacman complete')

    return None
