:<<!
 * Copyright (c) Huawei Technologies Co., Ltd. 2018-2023. All rights reserved.
 * oemaker licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 * Author:
 * Create: 2023-05-05
 * Description: provide qcow2 create root
!

#!/bin/bash

if [ "${DEBUG_TRACE:-0}" -gt 0 ]; then
  set -x
fi
set -eu
set -o pipefail

sudo mkdir -p $TARGET_ROOT/proc $TARGET_ROOT/dev $TARGET_ROOT/sys
sudo mount -t proc none $TARGET_ROOT/proc
sudo mount --bind /dev $TARGET_ROOT/dev
sudo mount --bind /dev/pts $TARGET_ROOT/dev/pts
sudo mount -t sysfs none $TARGET_ROOT/sys


mkdir -p ${HOOKS_WORKSPACE_DIR}/yum.repos.d/
repo_config=${HOOKS_WORKSPACE_DIR}/yum.repos.d/tmp.repo

if [ "X$ISO" != "X" ] || [ "X$REPODIR" != "X" ]; then
    [ "X$ISO" != "X" ] && mount -o loop $ISO /mnt || echo > /dev/null

    echo "[openEuler]" > $repo_config
    echo "name=openEuler" >> $repo_config
    echo -n "baseurl=" >> $repo_config

    [ "X$ISO" != "X" ] && REPODIR="file:///mnt/"

    echo $REPODIR >> $repo_config
    echo "enable=1" >> $repo_config
    echo "gpgcheck=0" >> $repo_config

else
    i=0
    for repo in `cat $REPOFILE`
    do
        repo_config=${HOOKS_WORKSPACE_DIR}/yum.repos.d/tmp_${i}.repo
        echo "[openEuler_${i}]" > $repo_config
        echo "name=openEuler_${i}" >> $repo_config
        echo -n "baseurl=" >> $repo_config
        echo "$repo" >> $repo_config
        echo "enable=1" >> $repo_config
        echo "gpgcheck=0" >> $repo_config
        ((i++)) || echo > /dev/null
    done
    rm -rf $REPOFILE
fi

packages="openEuler-release basesystem filesystem setup yum "
yum install -y  \
    --disableexcludes=all \
    --setopt=reposdir=${HOOKS_WORKSPACE_DIR}/yum.repos.d \
    --installroot=${TARGET_ROOT} \
    $packages

# Install package from inside
[ "X$ISO" != "X" ] && mount --bind /mnt ${TARGET_ROOT}/mnt

[ "X$REPODIR" != "X" ] && mkdir ${TARGET_ROOT}${REPODIR:7} && mount --bind ${REPODIR:7} ${TARGET_ROOT}${REPODIR:7}

if [ ! -d ${TARGET_ROOT}/etc/yum.repos.d/ ]; then
    mkdir -p ${TARGET_ROOT}/etc/yum.repos.d/
fi
cp ${HOOKS_WORKSPACE_DIR}/yum.repos.d/tmp*.repo ${TARGET_ROOT}/etc/yum.repos.d/

#disbale other repos
if [ -f ${TARGET_ROOT}/etc/yum.repos.d/openEuler-base.repo ]; then
   sed -i "s/enabled=1/enabled=0/g" ${TARGET_ROOT}/etc/yum.repos.d/openEuler-base.repo
fi

chroot ${TARGET_ROOT} rpm --rebuilddb
chroot ${TARGET_ROOT} yum  clean all

# populate the lang reduction macro in the chroot
echo "%_install_langs C:en_US:en_US.UTF-8" | \
    sudo tee -a $TARGET_ROOT/etc/rpm/macros.langs > /dev/null

if [ $ARCH == "riscv64" ]; then
    # Set DNS
    echo "nameserver 8.8.8.8" | sudo tee $TARGET_ROOT/etc/resolv.conf  > /dev/null
fi

# bootstrap the environment within the chroot; bring in new
# metadata with an update and install some base packages we need.
sudo -E chroot $TARGET_ROOT rm -rf etc/yum.repos.d/openEuler.repo
sudo -E chroot $TARGET_ROOT ls etc/yum.repos.d/
sudo -E chroot $TARGET_ROOT yum -y update
sudo -E chroot $TARGET_ROOT yum -y reinstall openEuler-release

sudo -E chroot $TARGET_ROOT yum -y install vi passwd findutils sudo util-linux-ng logrotate
sudo -E chroot $TARGET_ROOT yum -y install openssh-server setup

if [ $ARCH != "riscv64" ]; then

    if [ $ARCH == "x86_64" ]; then
        MODULE="xen-netfront xen-blkfront virtio_blk virtio_net virtio_balloon virtio virtio_pci virtio_ring virtio_scsi virtio-rng virtio_console virtio-input nls_utf8 isofs ipt_MASQUERADE nf_nat_masquerade_ipv4 iptable_nat nf_conntrack_ipv4 nf_nat_ipv4 xt_addrtype iptable_filter xt_conntrack nf_nat br_netfilter dm_thin_pool dm_persistent_data dm_bio_prison dm_bufio vport_vxlan openvswitch nf_defrag_ipv6 nf_defrag_ipv4 gre kbox dm_mirror dm_region_hash dm_log dm_mod ablk_helper cryptd ses enclosure sg ib_core shpchp ip_tables sr_mod cdrom marvell usb_storage mpt3sas "
    else
        MODULE="xen-netfront xen-blkfront virtio_blk virtio_net virtio_balloon virtio virtio_pci virtio_ring virtio_scsi virtio-rng virtio_console virtio-input nls_utf8 isofs ipt_MASQUERADE nf_nat_masquerade_ipv4 iptable_nat nf_conntrack_ipv4 nf_nat_ipv4 xt_addrtype iptable_filter xt_conntrack nf_nat br_netfilter dm_thin_pool dm_persistent_data dm_bio_prison dm_bufio vport_vxlan openvswitch nf_defrag_ipv6 nf_defrag_ipv4 gre kbox dm_mirror dm_region_hash dm_log dm_mod hns_roce crc32_arm64 aes_ce_blk ablk_helper cryptd ses aes_ce_cipher enclosure ghash_ce sha2_ce sha1_ce sg hns_dsaf ib_core ib_addr shpchp ip_tables sr_mod cdrom hns_enet_drv marvell hnae hns_mdio usb_storage mpt3sas "
    fi

    FS="ext4 "
    sudo -E chroot $TARGET_ROOT yum -y install dracut
    sudo -E chroot $TARGET_ROOT sed -i "s/#add_drivers+=\"\"/add_drivers+=\"${MODULE}\"/" /etc/dracut.conf
    sudo -E chroot $TARGET_ROOT sed -i "s/#filesystems+=\"\"/filesystems+=\"${FS}\"/" /etc/dracut.conf
fi

if [ $ARCH == "x86_64" ]; then
    sudo -E chroot $TARGET_ROOT yum -y install grub2 kernel
elif [ $ARCH == "aarch64" ]; then
    sudo -E chroot $TARGET_ROOT yum -y install grub2-efi grub2-efi-modules grub2-tools kernel
elif [ $ARCH == "riscv64" ]; then
    sudo -E chroot $TARGET_ROOT yum -y install kernel
fi

function change_uname()
{
    cat << EOF > "${1}"
#!/bin/sh

OUTPUT=\$(uname.bin \$*)
NOT_INSTALLED="is not installed"

if [[ \$* == "-r" ]];then
    dir=\$(rpm -q --qf '%{VERSION}-%{RELEASE}.%{ARCH}\n' kernel | head -n 1)
    if [ -z "\$(echo "\${dir}" | grep "\${NOT_INSTALLED}")" ]; then
        [ -n "\${dir}" ] && echo \${dir} && exit 0
    fi
    dir=\$(rpm -q --qf '%{VERSION}-%{RELEASE}.%{ARCH}\n' kernel-devel | head -n 1)
    if [ -z "\$(echo "\${dir}" | grep "\${NOT_INSTALLED}")" ]; then
        [ -n "\${dir}" ] && echo \${dir} && exit 0
    fi
    dir=\$(rpm -q --qf '%{VERSION}-%{RELEASE}.%{ARCH}\n' kernel-headers | head -n 1)
    if [ -z "\$(echo "\${dir}" | grep "\${NOT_INSTALLED}")" ]; then
        [ -n "\${dir}" ] && echo \${dir} && exit 0
    fi
    echo "error: you must installed kernel or kernel-headers" && exit 1
else
    echo \${OUTPUT}
fi
EOF
}

sudo -E chroot $TARGET_ROOT mv /usr/bin/uname /usr/bin/uname.bin
change_uname "$TARGET_ROOT/usr/bin/uname"
sudo -E chroot $TARGET_ROOT chmod +x /usr/bin/uname

if [ "X$PKGS_LIST" != "X" ]
then
    rpms=`cat $PKGS_LIST | tr "\n" " "`
    sudo -E chroot $TARGET_ROOT yum -y install $rpms
fi

# set the most reliable UTF-8 locale
echo -e 'LANG="en_US.UTF-8"' | sudo tee $TARGET_ROOT/etc/locale.conf

# default to UTC
sudo -E chroot $TARGET_ROOT ln -sf /usr/share/zoneinfo/UTC /etc/localtime

# default to multi-user.target
rm -f $TARGET_ROOT/etc/systemd/system/default.target
sudo -E chroot $TARGET_ROOT ln -sf /usr/lib/systemd/system/multi-user.target /etc/systemd/system/default.target

if [ $ARCH == "aarch64" ]; then
    cp $_PREFIX/config/grub.cfg $TARGET_ROOT/
fi

# this integrates with the global exit cleanup path.
if [ $ARCH != "riscv64" ]; then
    [ "X$ISO" != "X" ] && sudo umount $TARGET_ROOT/mnt
    [ "X$REPODIR" != "X" ] && umount ${TARGET_ROOT}${REPODIR:7} && rm -rf  ${TARGET_ROOT}${REPODIR:7}
fi

sudo umount $TARGET_ROOT/proc
sudo umount $TARGET_ROOT/dev/pts || true
sudo umount $TARGET_ROOT/dev
sudo umount $TARGET_ROOT/sys

# RPM doesn't know whether files have been changed since install
# At this point though, we know for certain that we have changed no
# config files, so anything marked .rpmnew is just a bug.
for newfile in $(sudo find $TARGET_ROOT -type f -name '*rpmnew') ; do
    sudo mv $newfile $(echo $newfile | sed 's/.rpmnew$//')
done

