#!/bin/bash


# build-env.sh kare-u16 --file=xxxx
machine=`uname -m`
if [ "$machine" = "x86_64" ]; then  
    BUILD_ARCH="amd64"  
elif [ "$machine" = "aarch64" ]; then  
    BUILD_ARCH="arm64" 
else
   echo 架构不支持
   exit -1
fi


ROOTFS_DIR=$(pwd)/$1
declare -A BUILD_SUITE_HASH MIRRORS_HASH
BUILD_SUITE_HASH["kare-u16"]="xenial"
BUILD_SUITE_HASH["kare-u18"]="bionic"
BUILD_SUITE_HASH["kare-u20"]="focal"
BUILD_SUITE_HASH["kare-ok1"]="yangtze"
BUILD_SUITE_HASH["kare-v10"]="10.0"
BUILD_SUITE_HASH["kare-v10sp1"]="10.1"
BUILD_SUITE=${BUILD_SUITE_HASH[$1]}


MIRRORS_HASH["kare-u16"]="http://mirrors.tuna.tsinghua.edu.cn/ubuntu/"
MIRRORS_HASH["kare-u18"]="http://mirrors.tuna.tsinghua.edu.cn/ubuntu/"
MIRRORS_HASH["kare-u20"]="http://mirrors.tuna.tsinghua.edu.cn/ubuntu/"
MIRRORS_HASH["kare-ok1"]="http://archive.build.openkylin.top/openkylin/"
MIRRORS_HASH["kare-v10"]="http://archive.kylinos.cn/kylin/KYLIN-ALL/"
MIRRORS_HASH["kare-v10sp1"]="http://archive.kylinos.cn/kylin/KYLIN-ALL/"
MIRRORS=${MIRRORS_HASH[$1]}

EXSUITES=()
OK_INCLUDES=(
    bash
    bash-completion
    curl
    wget
    file
    libc-bin
    lsb-release
    grub-efi-$BUILD_ARCH
    dialog
    locales
    gettext-base
    language-pack-zh-hans
    fonts-droid-fallback
    xinit
    sudo
)
OK_COMPONENTS=(
    main
    cross
    pty
)

UBUNTU_INCLUDES=(
    bash
    bash-completion
    curl
    wget
    file
    libc-bin
    lsb-release
    grub-efi-$BUILD_ARCH
    dialog
    locales
    gettext-base
    language-pack-zh-hans
    fonts-wqy-microhei
    fonts-droid-fallback
    xinit
    nodm
    slim
    openbox
    xterm
    feh
    sudo
)
UBUNTU_COMPONENTS=(
    main
    universe
    multiverse
    restricted
)

KYLIN_INCLUDES=(
    adduser
    apt
    bsdutils
    busybox-initramfs
    coreutils
    cpio
    dash
    debconf
    debianutils
    diffutils
    dpkg
    findutils
    gpgv
    grep
    gzip
    hostname
    init-system-helpers
    initramfs-tools
    initramfs-tools-bin
    initramfs-tools-core
    klibc-utils
    kmod
    kylin-keyring
    libc-bin
    libcap2-bin
    login
    logsave
    lsb-base
    lzma
    mawk
    mount
    ncurses-base
    ncurses-bin
    passwd
    sed
    selinux-utils
    sensible-utils
    systemd
    sysvinit-utils
    tar
    tzdata
    udev
    util-linux
    xz-utils
    base-files
    base-passwd
    e2fsprogs
    readline-common
    zlib1g
    dbus
    gcc-10-base
    gcc-9-base
    kysec-daemon
    policycoreutils
    perl-base
    linux-base
    systemd-timesyncd
    sudo
)

V10_INCLUDES=(
    bash
    bash-completion
    curl
    wget
    file
    libc-bin
    lsb-release
    dialog
    locales
    gettext-base
    libtinfo5
    language-pack-zh-hans
    fonts-droid-fallback
    kysec-daemon
    kylin-keyring
    xinit
    sudo
)

case $1 in
    kare-ok1)
        INCLUDES=(${OK_INCLUDES[@]})
        COMPONENTS=(${OK_COMPONENTS[@]}) 
        ;;
    kare-u16)
        INCLUDES=(${UBUNTU_INCLUDES[@]})
        COMPONENTS=(${UBUNTU_COMPONENTS[@]})
        ;;
    kare-u18)
        INCLUDES=(${UBUNTU_INCLUDES[@]})
        COMPONENTS=(${UBUNTU_COMPONENTS[@]})
        ;;
    kare-u20)
        INCLUDES=(${UBUNTU_INCLUDES[@]})
        COMPONENTS=(${UBUNTU_COMPONENTS[@]})
        ;;
    kare-v10sp1)
        INCLUDES=(${KYLIN_INCLUDES[@]})
        COMPONENTS=(${UBUNTU_COMPONENTS[@]})
        ;;
    kare-v10)
        INCLUDES=(${V10_INCLUDES[@]})
        COMPONENTS=(${UBUNTU_COMPONENTS[@]})
        ;;
    *) 
        echo 暂不支持
        exit -1
        ;;
esac


if [ $# -eq 2 ]; then
    arg=`echo "$2" | cut -d'=' -f1`
    data=`echo "$2" | cut -d'=' -f2`
fi

if [ "$arg" = "--file" ]; then 
    INCLUDES=()  
    while IFS= read -r line; do  
        for word in $line; do  
            INCLUDES+=("$word")  
        done  
    done < "$data"  
fi 
KEYRING=
VARIANT=minbase

# Suite
for SUITE in "${EXSUITES[@]}"; do
    EX_SUITES="${EX_SUITES:+${EX_SUITES},}${SUITE}"
done

# Packages
for PKG in "${INCLUDES[@]}"; do
    EX_PKGS="${EX_PKGS:+${EX_PKGS},}${PKG}"
done

# Components
for COM in "${COMPONENTS[@]}"; do
    EX_COMS="${EX_COMS:+${EX_COMS},}${COM}"
done

BOOTSTRAP_OPTS=
if [ "$1" = "kare-v10" ]; then  
    BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--verbose --no-merged-usr"
else
    BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--verbose"
fi
BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--variant=${VARIANT}"
BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--arch=${BUILD_ARCH}"


if [ -n "${EX_SUITES}" ]; then
    BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--extra-suites=${EX_SUITES}"
fi

if [ -n "${EX_PKGS}" ]; then
    BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--include=${EX_PKGS}"
fi

if [ -n "${EX_COMS}" ]; then
    BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--components=${EX_COMS}"
fi

if [ -n "${KEYRING}" ]; then
    BOOTSTRAP_OPTS="${BOOTSTRAP_OPTS:+${BOOTSTRAP_OPTS} }--keyring=${KEYRING}"
fi

sudo rm -rf "${ROOTFS_DIR}"
sudo mkdir -p "${ROOTFS_DIR}"
eval sudo debootstrap "${BOOTSTRAP_OPTS}" "${BUILD_SUITE}" "${ROOTFS_DIR}" "${MIRRORS}"


# 构建目录
if [ -d "/$1" ]; then
    read -p "基础环境已存在重新构建? (Y/N): " response 
    if [ ${response,,} = "y" ]; then
        rm -rf /$1
    else
        exit
    fi
fi

sudo mv $1 /$1
KARE_PATH=/$1
SHAREDDIRS=(
    box
    data
    home
    media
    mnt
    run
    sys
    tmp
)

KAREDIRS=(
    bin
    etc
    lib
    lib64
    sbin
    usr
    var
)

BWRRAP_OPTS="--uid 0 --gid 0"

for DIR in "${KAREDIRS[@]}"; do
    if [ -d "/$KARE_PATH/$DIR" ]; then
        BWRRAP_OPTS="$BWRRAP_OPTS --bind $KARE_PATH/$DIR /$DIR"
    fi
done

for DIR in "${SHAREDDIRS[@]}"; do
    if [ -d "/$DIR" ]; then
        BWRRAP_OPTS="$BWRRAP_OPTS --bind /$DIR /$DIR"
    fi
done

BWRRAP_OPTS="$BWRRAP_OPTS --dev-bind /dev /dev --proc /proc"

BWRRAP_OPTS="$BWRRAP_OPTS --setenv DISPLAY :0"

eval sudo /usr/bin/bwrap $BWRRAP_OPTS apt update

eval sudo /usr/bin/bwrap $BWRRAP_OPTS apt install -f -y


# 复制用户配置
USERCONFIG=(
    passwd
    shadow
    group
    gshadow
    subgid
    subuid
    passwd-
    shadow-
    group-
    gshadow-
    subgid-
    subuid-
    uid_list
)

for CONFIG in "${USERCONFIG[@]}"; do
    sudo cp /etc/$CONFIG $KARE_PATH/etc/ > /dev/null 2>&1
done

#获取宿主机可登录用户
usernames=$(getent passwd |grep -E "/bin/(bash|sh)$" | grep -vE "nologin|false|sync|shutdown|root" | cut -d: -f1)

for user in $usernames; do
    echo "$user:qwer1234" | sudo /usr/bin/bwrap $BWRRAP_OPTS chpasswd
done


/usr/bin/buildCompatibilityEnv.sh non