#!/bin/bash
set -e
set -u

logDir=/opt/compatibility_layer/logs/
logFile=/opt/compatibility_layer/logs/buildOciImage.log
if [ ! -d $logDir ]; then
    mkdir -p $logDir
    touch $logFile
elif [ ! -f $logFile ]; then
    touch $logFile
fi

echo -e "\n\n\n" >>$logFile
echo $(date) >>$logFile

# 检测系统版本 v10 v10sp1 v11
systemVersion=$(cat /etc/os-release | grep -i PROJECT_CODENAME | awk -F= '{print $2}')
echo "DEBUG - 宿主机系统版本是: "$systemVersion >>$logFile

# 制作相应系统版本的 OCI image
# 创建docker工作空间
echo "DEBUG - 创建工作空间" >>$logFile
docker_ws=/opt/compatibility_layer/image
if [ -d $docker_ws ]; then
    rm -rf $docker_ws/*
else
    mkdir -p $docker_ws
fi
# 创建Dockerfile文件
echo "DEBUG - 创建Dockerfile文件" >>$logFile
echo "FROM scratch" >$docker_ws/Dockerfile
echo "DEBUG - Dockerfile文件路径为: $docker_ws/Dockerfile" >>$logFile

# 补充Dockerfile文件 - 环境变量
echo -e "ENV  DISPLAY=:0 \\ \n\t LANG=zh_CN.UTF-8 \\ \n\t GTK_IM_MODULE=fcitx \\ \n\t QT4_IM_MODULE=fcitx \\
 \t XMODIFIERS=@im=fcitx \\ \n\t CLUTTER_IM_MODULE=fcitx \\ \n\t QT_IM_MODULE=fcitx" >>$docker_ws/Dockerfile

# 补充工作空间资源 - v10、v10 sp1在某个路径中寻找资源目录
resourceDir='/fs.old'
aidList=("/bin" "/etc" "/lib" "/lib64" "/lib32" "/opt" "/sbin" "/usr" "/var")
# otherList=("/backup" "/cdrom" "/box" "/lost+found" "/run" "/sys" "/data" "/home" "/media" "/proc" "/tmp" "/boot" "/dev" "/mnt" "/root" "/srv" "/run")
for eachFsOld in $resourceDir/*; do
    # 过滤非目录和链接目录
    if [ ! -d "$eachFsOld" ] || [ -L "$eachFsOld" ]; then
        continue
    fi
    # 过滤前缀
    eachFs=${eachFsOld#*${resourceDir}}
    for eachAidList in ${aidList[@]}; do
        if [ $eachAidList == $eachFs ]; then
            echo "COPY $eachFs $eachFs" >>$docker_ws/Dockerfile
            # p保留权限
            cp -rp $eachFsOld $docker_ws
            break
        fi
    done
done

# 补充Dockerfile文件 - 其他信息
echo "USER 1000" >>$docker_ws/Dockerfile
echo 'CMD ["/bin/bash"]' >>$docker_ws/Dockerfile

# 构建OCI镜像
dockerIsoName="baseimage_v10"
systemVersion=${systemVersion,,}
if [ "$systemVersion" == "v10sp1" ]; then
    # 在sp1机器上使用，构建的应该是v10的镜像
    dockerIsoName="baseimage_v10"
elif [ "$systemVersion" == "v11" ]; then
    # 在v11机器上使用，构建的可能是v10sp1 v10 v11镜像三者之一
    echo "TODO"
fi
echo "DEBUG - OCI镜像名称为: $dockerIsoName" >>$logFile
echo "DEBUG - 开始制作 OCI 镜像" >>$logFile
docker build -t $dockerIsoName $docker_ws >>$logFile 2>&1
if [ $? -eq 0 ]; then
    echo "DEBUG - OCI镜像构建成功" >>$logFile
    exit 0
else
    echo "ERROR - OCI镜像构建失败" >>$logFile
    exit -1
fi
