:<<!
 * 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 make functions
!

#!/usr/bin/bash

set -eE
# Prevent perl from complaining a lot, but also remove any unexpected side-effects
# of $LANG varying between build hosts
export LANG=C

SCRIPTNAME=$(basename $0)
export SCRIPT_HOME=$(dirname $(readlink -f $0))

if [ -d /usr/share/CreateImage ]; then
  # we have been installed in /usr
  export _PREFIX=$SCRIPT_HOME/../share/CreateImage
else
  # we have not been installed in any way
  export _PREFIX=$SCRIPT_HOME/..
fi
export _LIB=$_PREFIX/lib
source $_LIB/die

function show_options () {
    cat << EOF
Usage: create-image [OPTION]... [URL]

Options:
    -h,--help       display this help and exit
    -v,--version    display version and exit
    -r              obs repos source for mirroring
EOF
}

function show_version() {
    cat $_PREFIX/version
    exit 0
}

# Display the current file/function/line in the debug output
function _ps4 {
  IFS=" " called=($(caller 0))
  local f=$(readlink -f ${called[2]})
  printf "%-80s " "$f:${called[1]}:${called[0]}"
}
export -f _ps4
export PS4='+ $(_ps4):   '

source $_LIB/utils

REPOFILE="/tmp/_HMI_repos"
ISO=
REPODIR=
NAME=system.img
ROOT_PWD='''$6$o4rTi3d/.hh6JUYC$ClnCxd2mAQHlt0UloC4ystQg0CiuSVyhXz0sP1mDCNCgWV0rBwegwJ/bCWfjN4WxbahDa7F9U3c6/vFaNgsvX/'''
PKGS_LIST="$_PREFIX/config/rpmlist"

ARCH=`arch`

[ -f $REPOFILE ] && rm -rf $REPOFILE

if [ "$#" -eq 1 ];then
    case $1 in
    -h|--help)
       show_options
       exit 0;;
    -v|--version)
       show_version;;
    *)
       echo "error: params is invalid,please check it."
       show_options
       exit 1;;
    esac
elif [ "$#" -gt 1 ];then 
    while getopts ":s::r::d::n:p:l:" opt
    do
        case $opt in
        s)
          ISO="$OPTARG";;
        d)
     	  REPODIR="$OPTARG";;
  	r)
    	  echo "$OPTARG" >> $REPOFILE;;
  	n)
          NAME="$OPTARG".img;;
        p)
          ROOT_PWD="$OPTARG";;
        l)
          PKGS_LIST="$OPTARG";;
	*)
    	  echo "error: params is invalid,please check it."
    	  show_options
          exit 1;;
        esac
    done
    set +eE
    echo "$@" | grep "^-[srdnpl] "
    if [ "$?" -ne 0 ];then
        echo "error: params is invalid,please check it."
        show_options
        exit 1
    fi
    set -eE
else
    echo "warning: params is none,please reference help information."
    show_options
    exit 0
fi

[ ! -f $ISO ] && [ ! -f $REPOFILE] && show_options && exit 1

export ISO
export REPOFILE
export NAME
export ROOT_PWD
export PKGS_LIST
export ARCH
export REPODIR

create_workspace

create_env

run_hook_in_root pre-install

run_hook_in_root install

run_hook_in_root post_install

# ensure we do not have a lost+found directory in the root folder
# that could cause copy to fail (it will be created again later
# when creating the file system, if it needs such directory)
if [ -e "${WORKSPACE_DIR}/mnt/lost+found" ]; then
    sudo rm -rf "${WORKSPACE_DIR}/mnt/lost+found"
fi
# Free up /mnt
unmount_mnt
mv ${WORKSPACE_DIR}/mnt ${WORKSPACE_DIR}/built

# umount mount ISO FILE
[ "X$ISO" != "X" ] && umount /mnt

IMG_SIZE=3

/usr/bin/qemu-img create ${NAME} ${IMG_SIZE}G
/usr/sbin/parted ${NAME} -- mklabel msdos

if [ $ARCH == "x86_64" ]; then

    /usr/sbin/parted ${NAME} -- mkpart primary ext4 0% 100%

elif [ $ARCH == "aarch64" ]; then

    /usr/sbin/parted ${NAME} -- mkpart primary fat16 0% 5%
    /usr/sbin/parted ${NAME} -- mkpart primary ext4 5% 100%

elif [ $ARCH == "riscv64" ]; then

    /usr/sbin/parted ${NAME} -- mkpart primary ext4 0% 512MB
    /usr/sbin/parted ${NAME} -- mkpart primary ext4 512MB 100%

fi

export DEVICE=`losetup -f`
num=$(echo $DEVICE | awk -F 'loop' '{print $2}')
rm -rf "/dev/loop${num}"
mknod $DEVICE b 7 $num
/usr/sbin/losetup ${DEVICE} ${NAME}

offset=`fdisk -l ${NAME} | grep "${NAME}1" | awk '{print $2}'`
sizelimit=`fdisk -l ${NAME} | grep "${NAME}1" | awk '{print $3}'`
sizelimit=`echo "($sizelimit - $offset)*512" | bc`
offset=`echo "${offset}*512" | bc`

if [ $ARCH == "aarch64" ]; then

    export BOOT=`losetup -f`
    num=$(echo $BOOT | awk -F 'loop' '{print $2}')
    rm -rf "/dev/loop${num}"
    mknod $BOOT b 7 $num
    /usr/sbin/losetup -o ${offset} --sizelimit ${sizelimit} ${BOOT} ${NAME}
    /usr/sbin/mkfs.vfat $BOOT

    offset=`fdisk -l ${NAME} | grep "${NAME}2" | awk '{print $2}'`
    sizelimit=`fdisk -l ${NAME} | grep "${NAME}2" | awk '{print $3}'`
    sizelimit=`echo "($sizelimit - $offset)*512" | bc`
    offset=`echo "${offset}*512" | bc`

fi

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

    export BOOT=`losetup -f`
    num=$(echo $BOOT | awk -F 'loop' '{print $2}')
    rm -rf "/dev/loop${num}"
    mknod $BOOT b 7 $num
    /usr/sbin/losetup -o ${offset} --sizelimit ${sizelimit} ${BOOT} ${NAME}
    /usr/sbin/mkfs.ext4 ${BOOT}

    offset=`fdisk -l ${NAME} | grep "${NAME}2" | awk '{print $2}'`
    sizelimit=`fdisk -l ${NAME} | grep "${NAME}2" | awk '{print $3}'`
    sizelimit=`echo "($sizelimit - $offset)*512" | bc`
    offset=`echo "${offset}*512" | bc`

fi

export ROOT=`losetup -f`
num=$(echo $ROOT | awk -F 'loop' '{print $2}')
rm -rf "/dev/loop${num}"
mknod $ROOT b 7 $num
export ROOT_FS_UUID=$(uuidgen -r)
/usr/sbin/losetup -o ${offset} --sizelimit ${sizelimit} ${ROOT} ${NAME}
/usr/sbin/mkfs.ext4 -L "rootfs" ${ROOT}
/sbin/tune2fs -U ${ROOT_FS_UUID} ${ROOT}

mkdir -p ${WORKSPACE_DIR}/mnt
mount -t ext4 ${ROOT} ${MOUNT_WORKSPACE_DIR}
rm -rf "${MOUNT_WORKSPACE_DIR}/lost+found"

if [ $ARCH == "aarch64" ]; then
    mkdir -p ${MOUNT_WORKSPACE_DIR}/boot
    chmod 755 ${MOUNT_WORKSPACE_DIR}/boot
    mount -t vfat ${BOOT} ${MOUNT_WORKSPACE_DIR}/boot
    export BOOT_UUID=$(blkid -s UUID -o value ${BOOT})
    mv -f ${WORKSPACE_DIR}/built/boot/* ${MOUNT_WORKSPACE_DIR}/boot/ || true
    [ -d ${WORKSPACE_DIR}/built/boot/ ] && rm -rf ${WORKSPACE_DIR}/built/boot/
fi

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

    mkdir -p ${WORKSPACE_DIR}/mnt/boot
    chmod 755 ${WORKSPACE_DIR}/mnt/boot
    mount -t ext4 -o loop ${BOOT} ${MOUNT_WORKSPACE_DIR}/boot
    rm -rf "${MOUNT_WORKSPACE_DIR}/boot/lost+found"
    export BOOT_UUID=$(blkid -s UUID -o value ${BOOT})
    mv -f ${WORKSPACE_DIR}/built/boot/* ${MOUNT_WORKSPACE_DIR}/boot/ || true
    [ -d ${WORKSPACE_DIR}/built/boot/ ] && rm -rf ${WORKSPACE_DIR}/built/boot/

fi

sudo mv -t ${WORKSPACE_DIR}/mnt ${WORKSPACE_DIR}/built/* || true

mount_dir
run_hook_in_root finalise
remove_workspace

fstrim_mnt
# Unmount and cleanup the /mnt and /build subdirectories, to save
# space before converting the image to some other format.
unmount_mnt
remove_env
/usr/sbin/losetup -D

# All done
exit 0

