#!/bin/bash
#
# Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
#
# 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 3 of the License, or
# any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Read kernel parameter and set global variables.

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

auto_install_mode=0

cd_rom() {
    if [ -d /lib/live/mount/medium/live ]; then
        CDROM=/lib/live/mount/medium
    else
        CDROM=/run/live/medium
    fi
    echo ${CDROM}
}
# 添加本地仓库，为英伟达显卡安装驱动所用
setup_repo_sources() {
    # 本地仓库的路径
    local LIVE_DIR=$(cd_rom)
    local LOC_REPO_PATH=$LIVE_DIR/dists

    # add cdrom to sources.list
    if [ -d $LOC_REPO_PATH ]; then
        # commented source.list to let apt-get just using cdrom repo.
        sed -i 's/^/#/g' /etc/apt/sources.list

        dir=$(find  $LOC_REPO_PATH -name "Release" | xargs awk -F '[ :]+' '/Codename/{print $2}')
        for name in $dir; do
            # ident the cdrom first.
            echo "deb [trusted=yes] file:$LIVE_DIR ${name} main" >> /etc/apt/sources.list
        done

        apt-get update || true
    else
        echo "$LOC_REPO_PATH is not a debian repository. Skipped." >> /var/log/deepin-installer-init.log
    fi
}

deepin_nvidia_installer() {
    if [ -f /usr/sbin/deepin-nvidia-installer ]; then
        setup_repo_sources
        deepin-nvidia-installer 0 || echo "run deepin-nvidia-installer 0 error"
    else
        echo "/usr/sbin/deepin-nvidia-installer is not found"
    fi
}
parse_cmdline() {
  for x in $(cat /proc/cmdline); do
    case $x in
      install-mode-cli=true)
        echo $x
        cli_mode=true
        ;;
	auto-deepin-installer)
        auto_install_mode=1
        ;;
      esac
  done
}

parse_cmdline

if [ x"$cli_mode" = xtrue ]; then
    systemctl stop lightdm
    chvt 2
    systemctl restart deepin-installer-cli
else
    # 启动前英伟达显卡驱动设置
    deepin_nvidia_installer >> /var/log/deepin-installer-init.log 2>&1
    if [ $auto_install_mode -eq 1 ]; then
       /usr/lib/live/config/1081-deepin-auto-install
    else
       /usr/lib/live/config/1082-deepin-livecd true
    fi
fi

