OSDN Git Service

[update] : Use global tar_filename
[alterlinux/alterlinux.git] / build.sh
1 #!/usr/bin/env bash
2 #
3 # Yamada Hayao
4 # Twitter: @Hayao0819
5 # Email  : hayao@fascode.net
6 #
7 # (c) 2019-2021 Fascode Network.
8 #
9 # build.sh
10 #
11 # The main script that runs the build
12 #
13
14 set -eu
15
16 # Internal config
17 # Do not change these values.
18 script_path="$( cd -P "$( dirname "$(readlink -f "${0}")" )" && pwd )"
19 defaultconfig="${script_path}/default.conf"
20 tools_dir="${script_path}/tools"
21 module_dir="${script_path}/modules"
22 customized_username=false
23 customized_password=false
24 customized_kernel=false
25 customized_logpath=false
26 pkglist_args=()
27 makepkg_script_args=()
28 modules=()
29 DEFAULT_ARGUMENT=""
30 alteriso_version="3.1"
31
32 # Load config file
33 [[ ! -f "${defaultconfig}" ]] && "${tools_dir}/msg.sh" -a 'build.sh' error "${defaultconfig} was not found." && exit 1
34 for config in "${defaultconfig}" "${script_path}/custom.conf"; do
35     [[ -f "${config}" ]] && source "${config}"
36 done
37
38 umask 0022
39
40 # Message common function
41 # msg_common [type] [-n] [string]
42 msg_common(){
43     local _msg_opts=("-a" "build.sh") _type="${1}"
44     shift 1
45     [[ "${1}" = "-n" ]] && _msg_opts+=("-o" "-n") && shift 1
46     [[ "${msgdebug}" = true ]] && _msg_opts+=("-x")
47     [[ "${nocolor}"  = true ]] && _msg_opts+=("-n")
48     _msg_opts+=("${_type}" "${@}")
49     "${tools_dir}/msg.sh" "${_msg_opts[@]}"
50 }
51
52 # Show an INFO message
53 # ${1}: message string
54 msg_info() { msg_common info "${@}"; }
55
56 # Show an Warning message
57 # ${1}: message string
58 msg_warn() { msg_common warn "${@}"; }
59
60 # Show an debug message
61 # ${1}: message string
62 msg_debug() { 
63     [[ "${debug}" = true ]] && msg_common debug "${@}"
64     return 0
65 }
66
67 # Show an ERROR message then exit with status
68 # ${1}: message string
69 # ${2}: exit code number (with 0 does not exit)
70 msg_error() {
71     msg_common error "${1}"
72     [[ -n "${2:-}" ]] && exit "${2}"
73 }
74
75
76 # Usage: getclm <number>
77 # 標準入力から値を受けとり、引数で指定された列を抽出します。
78 getclm() { cut -d " " -f "${1}"; }
79
80 # Usage: echo_blank <number>
81 # 指定されたぶんの半角空白文字を出力します
82 echo_blank(){ yes " " 2> /dev/null  | head -n "${1}" | tr -d "\n"; }
83
84 _usage () {
85     echo "usage ${0} [options] [channel]"
86     echo
87     echo "A channel is a profile of AlterISO settings."
88     echo
89     echo " General options:"
90     echo "    -b | --boot-splash           Enable boot splash"
91     echo "    -e | --cleanup | --cleaning  Enable post-build cleaning"
92     echo "         --tarball               Build rootfs in tar.xz format"
93     echo "    -h | --help                  This help message and exit"
94     echo
95     echo "    -a | --arch <arch>           Set iso architecture"
96     echo "                                  Default: ${arch}"
97     echo "    -c | --comp-type <comp_type> Set SquashFS compression type (gzip, lzma, lzo, xz, zstd)"
98     echo "                                  Default: ${sfs_comp}"
99     echo "    -g | --gpgkey <key>          Set gpg key"
100     echo "                                  Default: ${gpg_key}"
101     echo "    -l | --lang <lang>           Specifies the default language for the live environment"
102     echo "                                  Default: ${locale_name}"
103     echo "    -k | --kernel <kernel>       Set special kernel type.See below for available kernels"
104     echo "                                  Default: ${defaultkernel}"
105     echo "    -o | --out <out_dir>         Set the output directory"
106     echo "                                  Default: ${out_dir}"
107     echo "    -p | --password <password>   Set a live user password"
108     echo "                                  Default: ${password}"
109     echo "    -t | --comp-opts <options>   Set compressor-specific options."
110     echo "                                  Default: empty"
111     echo "    -u | --user <username>       Set user name"
112     echo "                                  Default: ${username}"
113     echo "    -w | --work <work_dir>       Set the working directory"
114     echo "                                  Default: ${work_dir}"
115     echo
116
117     local blank="33" _arch _dirname _type
118
119     for _type in "locale" "kernel"; do
120         echo " ${_type} for each architecture:"
121         for _arch in $(find "${script_path}/system/" -maxdepth 1 -mindepth 1 -name "${_type}-*" -print0 | xargs -I{} -0 basename {} | sed "s|${_type}-||g"); do
122             echo -n "    ${_arch}$(echo_blank "$(( "${blank}" - 4 - "${#_arch}" ))")"
123             "${tools_dir}/${_type}.sh" -a "${_arch}" show
124         done
125         echo
126     done
127
128     echo " Channel:"
129     for _dirname in $(bash "${tools_dir}/channel.sh" --version "${alteriso_version}" -d -b -n show); do
130         echo -ne "    ${_dirname%.add}$(echo_blank "$(( "${blank}" - 3 - "$(echo "${_dirname%.add}" | wc -m)" ))")"
131         "${tools_dir}/channel.sh" --version "${alteriso_version}" --nocheck desc "${_dirname%.add}"
132     done
133
134     echo
135     echo " Debug options: Please use at your own risk."
136     echo "    -d | --debug                 Enable debug messages"
137     echo "    -x | --bash-debug            Enable bash debug mode(set -xv)"
138     echo "         --channellist           Output the channel list and exit"
139     echo "         --gitversion            Add Git commit hash to image file version"
140     echo "         --logpath <file>        Set log file path (use with --log)"
141     echo "         --[no]log               (No) log ;re-run script with tee"
142     echo "         --msgdebug              Enables output debugging"
143     echo "         --noaur                 Ignore aur packages (Use only for debugging)"
144     echo "         --nocolor               No output colored output"
145     echo "         --[no]confirm           (No) check the settings before building"
146     echo "         --nochkver              No check the version of the channel"
147     echo "         --nodebug               No debug message"
148     echo "         --noefi                 No efi boot (Use only for debugging)"
149     echo "         --noloopmod             No check and load kernel module automatically"
150     echo "         --nodepend              No check package dependencies before building"
151     echo "         --noiso                 No build iso image (Use with --tarball)"
152     echo "         --pacman-debug          Enable pacman debug mode"
153     echo "         --normwork              No remove working dir"
154     echo "         --nopkgbuild            Ignore PKGBUILD (Use only for debugging)"
155     echo
156     echo " Many packages are installed from AUR, so specifying --noaur can cause problems."
157     echo
158     [[ -n "${1:-}" ]] && exit "${1}"
159 }
160
161 # Unmount helper Usage: _umount <target>
162 _umount() { if mountpoint -q "${1}"; then umount -lf "${1}"; fi; }
163
164 # Mount helper Usage: _mount <source> <target>
165 _mount() { ! mountpoint -q "${2}" && [[ -f "${1}" ]] && [[ -d "${2}" ]] && mount "${1}" "${2}"; return 0; }
166
167 # Unmount work dir
168 umount_work () {
169     local _args=("${build_dir}")
170     [[ "${debug}" = true ]] && _args=("-d" "${_args[@]}")
171     [[ "${nocolor}" = true ]] && _args+=("--nocolor")
172     "${tools_dir}/umount.sh" "${_args[@]}"
173 }
174
175 # Mount airootfs on "${airootfs_dir}"
176 mount_airootfs () {
177     mkdir -p "${airootfs_dir}"
178     _mount "${airootfs_dir}.img" "${airootfs_dir}"
179 }
180
181
182 # Helper function to run make_*() only one time.
183 run_once() {
184     set -eu
185     if [[ ! -e "${lockfile_dir}/build.${1}" ]]; then
186         msg_debug "Running ${1} ..."
187         mount_airootfs
188         eval "${@}"
189         mkdir -p "${lockfile_dir}"; touch "${lockfile_dir}/build.${1}"
190         umount_work
191     else
192         msg_debug "Skipped because ${1} has already been executed."
193     fi
194 }
195
196 # Show message when file is removed
197 # remove <file> <file> ...
198 remove() {
199     local _file
200     for _file in "${@}"; do msg_debug "Removing ${_file}"; rm -rf "${_file}"; done
201 }
202
203 # 強制終了時にアンマウント
204 umount_trap() {
205     local _status="${?}"
206     umount_work
207     msg_error "It was killed by the user.\nThe process may not have completed successfully."
208     exit "${_status}"
209 }
210
211 # 設定ファイルを読み込む
212 # load_config [file1] [file2] ...
213 load_config() {
214     local _file
215     for _file in "${@}"; do [[ -f "${_file}" ]] && source "${_file}" && msg_debug "The settings have been overwritten by the ${_file}"; done
216     return 0
217 }
218
219 # Display channel list
220 show_channel_list() {
221     local _args=("-v" "${alteriso_version}" show)
222     [[ "${nochkver}" = true ]] && _args+=("-n")
223     bash "${tools_dir}/channel.sh" "${_args[@]}"
224 }
225
226 # Execute command for each module. It will be executed with {} replaced with the module name.
227 # for_module <command>
228 for_module(){
229     local module
230     for module in "${modules[@]}"; do eval "$(echo "${@}" | sed "s|{}|${module}|g")"; done
231 }
232
233 # pacstrapを実行
234 _pacstrap(){
235     msg_info "Installing packages to ${airootfs_dir}/'..."
236     local _args=("-c" "-G" "-M" "--" "${airootfs_dir}" "${@}")
237     [[ "${pacman_debug}" = true ]] && _args+=(--debug)
238     pacstrap -C "${build_dir}/pacman.conf" "${_args[@]}"
239     msg_info "Packages installed successfully!"
240 }
241
242 # chroot環境でpacmanコマンドを実行
243 # /etc/alteriso-pacman.confを準備してコマンドを実行します
244 _run_with_pacmanconf(){
245     sed "s|^CacheDir     =|#CacheDir    =|g" "${build_dir}/pacman.conf" > "${airootfs_dir}/etc/alteriso-pacman.conf"
246     eval -- "${@}"
247     remove "${airootfs_dir}/etc/alteriso-pacman.conf"
248 }
249
250 # コマンドをchrootで実行する
251 _chroot_run() {
252     msg_debug "Run command in chroot\nCommand: ${*}"
253     eval -- arch-chroot "${airootfs_dir}" "${@}"
254 }
255
256 _cleanup_common () {
257     msg_info "Cleaning up what we can on airootfs..."
258
259     # Delete pacman database sync cache files (*.tar.gz)
260     [[ -d "${airootfs_dir}/var/lib/pacman" ]] && find "${airootfs_dir}/var/lib/pacman" -maxdepth 1 -type f -delete
261
262     # Delete pacman database sync cache
263     [[ -d "${airootfs_dir}/var/lib/pacman/sync" ]] && find "${airootfs_dir}/var/lib/pacman/sync" -delete
264
265     # Delete pacman package cache
266     [[ -d "${airootfs_dir}/var/cache/pacman/pkg" ]] && find "${airootfs_dir}/var/cache/pacman/pkg" -type f -delete
267
268     # Delete all log files, keeps empty dirs.
269     [[ -d "${airootfs_dir}/var/log" ]] && find "${airootfs_dir}/var/log" -type f -delete
270
271     # Delete all temporary files and dirs
272     [[ -d "${airootfs_dir}/var/tmp" ]] && find "${airootfs_dir}/var/tmp" -mindepth 1 -delete
273
274     # Delete package pacman related files.
275     find "${build_dir}" \( -name '*.pacnew' -o -name '*.pacsave' -o -name '*.pacorig' \) -delete
276
277     # Delete all cache file
278     [[ -d "${airootfs_dir}/var/cache" ]] && find "${airootfs_dir}/var/cache" -mindepth 1 -delete
279
280     # Create an empty /etc/machine-id
281     printf '' > "${airootfs_dir}/etc/machine-id"
282
283     msg_info "Done!"
284 }
285
286 _cleanup_airootfs(){
287     _cleanup_common
288     # Delete all files in /boot
289     [[ -d "${airootfs_dir}/boot" ]] && find "${airootfs_dir}/boot" -mindepth 1 -delete
290 }
291
292 _mkchecksum() {
293     msg_info "Creating md5 checksum ..."
294     echo "$(md5sum "${1}" | getclm 1) $(basename "${1}")" > "${1}.md5"
295     msg_info "Creating sha256 checksum ..."
296     echo "$(sha256sum "${1}" | getclm 1) $(basename "${1}")" > "${1}.sha256"
297 }
298
299 # Check the value of a variable that can only be set to true or false.
300 check_bool() {
301     local _value _variable
302     for _variable in "${@}"; do
303         msg_debug -n "Checking ${_variable}..."
304         eval ': ${'${_variable}':=""}'
305         _value="$(eval echo '$'${_variable})"
306         if [[ ! -v "${1}" ]] || [[ "${_value}"  = "" ]]; then
307             [[ "${debug}" = true ]] && echo ; msg_error "The variable name ${_variable} is empty." "1"
308         elif [[ ! "${_value}" = "true" ]] && [[ ! "${_value}" = "false" ]]; then
309             [[ "${debug}" = true ]] && echo ; msg_error "The variable name ${_variable} is not of bool type (${_variable} = ${_value})" "1"
310         elif [[ "${debug}" = true ]]; then
311             echo -e " ${_value}"
312         fi
313     done
314 }
315
316 _run_cleansh(){
317     bash $([[ "${bash_debug}" = true ]] && echo -n "-x" ) "${tools_dir}/clean.sh" -o -w "$(realpath "${build_dir}")" "$([[ "${debug}" = true ]] && printf "%s" "-d")" "$([[ "${noconfirm}" = true ]] && printf "%s" "-n")" "$([[ "${nocolor}" = true ]] && printf "%s" "--nocolor")"
318 }
319
320
321 # Check the build environment and create a directory.
322 prepare_env() {
323     # Check packages
324     if [[ "${nodepend}" = false ]]; then
325         local _check_failed=false _pkg _result=0
326         msg_info "Checking dependencies ..."
327         if ! pacman -Qq pyalpm > /dev/null 2>&1; then
328             msg_error "pyalpm is not installed." 1
329         fi   
330         for _pkg in "${dependence[@]}"; do
331             eval "${tools_dir}/package.py" "${_pkg}" "$( [[ "${debug}" = false ]] && echo "> /dev/null")" || _result="${?}"
332             if (( _result == 3 )) || (( _result == 4 )); then
333                 _check_failed=true
334             fi
335             _result=0
336         done
337         [[ "${_check_failed}" = true ]] && exit 1
338     fi
339
340     # Load loop kernel module
341     if [[ "${noloopmod}" = false ]]; then
342         [[ ! -d "/usr/lib/modules/$(uname -r)" ]] && msg_error "The currently running kernel module could not be found.\nProbably the system kernel has been updated.\nReboot your system to run the latest kernel." "1"
343         [[ -z "$(lsmod | getclm 1 | grep -x "loop")" ]] && modprobe loop
344     fi
345
346     # Check work dir
347     if [[ "${normwork}" = false ]]; then
348         msg_info "Deleting the contents of ${build_dir}..."
349         _run_cleansh
350     fi
351
352     # Set gpg key
353     if [[ -n "${gpg_key}" ]]; then
354         gpg --batch --output "${work_dir}/pubkey.gpg" --export "${gpg_key}"
355         exec {ARCHISO_GNUPG_FD}<>"${build_dir}/pubkey.gpg"
356         export ARCHISO_GNUPG_FD
357     fi
358
359     # 強制終了時に作業ディレクトリを削除する
360     local _trap_remove_work
361     _trap_remove_work() {
362         local status="${?}"
363         [[ "${normwork}" = false ]] && echo && _run_cleansh
364         exit "${status}"
365     }
366     trap '_trap_remove_work' 1 2 3 15
367
368     return 0
369 }
370
371
372 # Show settings.
373 show_settings() {
374     if [[ "${boot_splash}" = true ]]; then
375         msg_info "Boot splash is enabled."
376         msg_info "Theme is used ${theme_name}."
377     fi
378     msg_info "Language is ${locale_fullname}."
379     msg_info "Use the ${kernel} kernel."
380     msg_info "Live username is ${username}."
381     msg_info "Live user password is ${password}."
382     msg_info "The compression method of squashfs is ${sfs_comp}."
383     msg_info "Use the ${channel_name%.add} channel."
384     msg_info "Build with architecture ${arch}."
385     if [[ "${noconfirm}" = false ]]; then
386         echo -e "\nPress Enter to continue or Ctrl + C to cancel."
387         read
388     fi
389     trap 1 2 3 15
390     trap 'umount_trap' 1 2 3 15
391
392     return 0
393 }
394
395
396 # Preparation for build
397 prepare_build() {
398     # Show alteriso version
399     if [[ -d "${script_path}/.git" ]]; then
400         cd  "${script_path}"
401         msg_debug "The version of alteriso is $(git describe --long --tags | sed 's/\([^-]*-g\)/r\1/;s/-/./g')."
402         cd "${OLDPWD}"
403     fi
404
405     # Load configs
406     load_config "${channel_dir}/config.any" "${channel_dir}/config.${arch}"
407
408     # Debug mode
409     if [[ "${bash_debug}" = true ]]; then
410         set -x -v
411     fi
412
413     # Legacy mode
414     if [[ "$(bash "${tools_dir}/channel.sh" --version "${alteriso_version}" ver "${channel_name}")" = "3.0" ]]; then
415         msg_warn "The module cannot be used because it works with Alter ISO3.0 compatibility."
416         if [[ ! -z "${include_extra+SET}" ]]; then
417             if [[ "${include_extra}" = true ]]; then
418                 modules=("base" "share" "share-extra" "calamares" "zsh-powerline")
419             else
420                 modules=("base" "share")
421             fi
422         fi
423     fi
424
425     local module_check
426     module_check(){
427         msg_debug "Checking ${1} module ..."
428         bash "${tools_dir}/module.sh" check "${1}" || msg_error "Module ${1} is not available." "1";
429     }
430     readarray -t modules < <(printf "%s\n" "${modules[@]}" | awk '!a[$0]++')
431     for_module "module_check {}"
432     for_module load_config "${module_dir}/{}/config.any" "${module_dir}/{}/config.${arch}"
433     msg_debug "Loaded modules: ${modules[*]}"
434     ! printf "%s\n" "${modules[@]}" | grep -x "share" >/dev/null 2>&1 && msg_warn "The share module is not loaded."
435
436     # Set kernel
437     [[ "${customized_kernel}" = false ]] && kernel="${defaultkernel}"
438
439     # Parse files
440     eval "$(bash "${tools_dir}/locale.sh" -s -a "${arch}" get "${locale_name}")"
441     eval "$(bash "${tools_dir}/kernel.sh" -s -c "${channel_name}" -a "${arch}" get "${kernel}")"
442
443     # Set username and password
444     [[ "${customized_username}" = false ]] && username="${defaultusername}"
445     [[ "${customized_password}" = false ]] && password="${defaultpassword}"
446
447     # gitversion
448     [[ "${gitversion}" = true ]] && iso_version="${iso_version}-${gitrev}"
449
450     # Generate iso file name.
451     local _channel_name="${channel_name%.add}-${locale_version}" 
452     iso_filename="${iso_name}-${_channel_name}-${iso_version}-${arch}.iso"
453     tar_filename="${iso_filename%.iso}.tar.xz"
454     [[ "${nochname}" = true ]] && iso_filename="${iso_name}-${iso_version}-${arch}.iso"
455     msg_debug "Iso filename is ${iso_filename}"
456
457     # check bool
458     check_bool boot_splash cleaning noconfirm nodepend customized_username customized_password noloopmod nochname tarball noiso noaur customized_syslinux norescue_entry debug bash_debug nocolor msgdebug noefi nosigcheck gitversion
459
460     # Check architecture for each channel
461     local _exit=0
462     bash "${tools_dir}/channel.sh" --version "${alteriso_version}" -a "${arch}" -n -b check "${channel_name}" || _exit="${?}"
463     if (( "${_exit}" != 0 )) && (( "${_exit}" != 1 )); then
464         msg_error "${channel_name} channel does not support current architecture (${arch})." "1"
465     fi
466
467     # Run with tee
468     if [[ ! "${logging}" = false ]]; then
469         [[ "${customized_logpath}" = false ]] && logging="${out_dir}/${iso_filename%.iso}.log"
470         mkdir -p "$(dirname "${logging}")" && touch "${logging}"
471         msg_warn "Re-run sudo ${0} ${ARGUMENT[*]} --nodepend --nolog --nocolor 2>&1 | tee ${logging}"
472         sudo "${0}" "${ARGUMENT[@]}" --nolog --nocolor --nodepend 2>&1 | tee "${logging}"
473         exit "${?}"
474     else
475         unset ARGUMENT
476     fi
477
478     # Set argument of pkglist.sh
479     pkglist_args=("-a" "${arch}" "-k" "${kernel}" "-c" "${channel_dir}" "-l" "${locale_name}")
480     [[ "${boot_splash}"              = true ]] && pkglist_args+=("-b")
481     [[ "${debug}"                    = true ]] && pkglist_args+=("-d")
482     [[ "${memtest86}"                = true ]] && pkglist_args+=("-m")
483     [[ "${nocolor}"                  = true ]] && pkglist_args+=("--nocolor")
484     (( "${#additional_exclude_pkg[@]}" >= 1 )) && pkglist_args+=("-e" "${additional_exclude_pkg[*]}")
485     pkglist_args+=("${modules[@]}")
486
487     # Set argument of aur.sh and pkgbuild.sh
488     [[ "${bash_debug}"   = true ]] && makepkg_script_args+=("-x")
489     [[ "${pacman_debug}" = true ]] && makepkg_script_args+=("-d")
490
491     return 0
492 }
493
494
495 # Setup custom pacman.conf with current cache directories.
496 make_pacman_conf() {
497     # Pacman configuration file used only when building
498     # If there is pacman.conf for each channel, use that for building
499     local _pacman_conf _pacman_conf_list=("${script_path}/pacman-${arch}.conf" "${channel_dir}/pacman-${arch}.conf" "${script_path}/system/pacman-${arch}.conf")
500     for _pacman_conf in "${_pacman_conf_list[@]}"; do
501         if [[ -f "${_pacman_conf}" ]]; then
502             build_pacman_conf="${_pacman_conf}"
503             break
504         fi
505     done
506
507     msg_debug "Use ${build_pacman_conf}"
508     sed -r "s|^#?\\s*CacheDir.+|CacheDir     = ${cache_dir}|g" "${build_pacman_conf}" > "${build_dir}/pacman.conf"
509
510     [[ "${nosigcheck}" = true ]] && sed -ir "s|^s*SigLevel.+|SigLevel = Never|g" "${build_pacman_conf}"
511
512     [[ -n "$(find "${cache_dir}" -maxdepth 1 -name '*.pkg.tar.*' 2> /dev/null)" ]] && msg_info "Use cached package files in ${cache_dir}"
513
514     # Share any architecture packages
515     #while read -r _pkg; do
516     #    if [[ ! -f "${cache_dir}/$(basename "${_pkg}")" ]]; then
517     #        ln -s "${_pkg}" "${cache_dir}"
518     #    fi
519     #done < <(find "${cache_dir}/../" -type d -name "$(basename "${cache_dir}")" -prune -o -type f -name "*-any.pkg.tar.*" -printf "%p\n")
520
521     return 0
522 }
523
524 # Base installation (airootfs)
525 make_basefs() {
526     msg_info "Creating ext4 image of 32GiB..."
527     truncate -s 32G -- "${airootfs_dir}.img"
528     mkfs.ext4 -O '^has_journal,^resize_inode' -E 'lazy_itable_init=0' -m 0 -F -- "${airootfs_dir}.img" 32G
529     tune2fs -c "0" -i "0" "${airootfs_dir}.img"
530     msg_info "Done!"
531
532     msg_info "Mounting ${airootfs_dir}.img on ${airootfs_dir}"
533     mount_airootfs
534     msg_info "Done!"
535     return 0
536 }
537
538 # Additional packages (airootfs)
539 make_packages_repo() {
540     msg_debug "pkglist.sh ${pkglist_args[*]}"
541     readarray -t _pkglist < <("${tools_dir}/pkglist.sh" "${pkglist_args[@]}")
542
543     # Create a list of packages to be finally installed as packages.list directly under the working directory.
544     echo -e "# The list of packages that is installed in live cd.\n#\n" > "${build_dir}/packages.list"
545     printf "%s\n" "${_pkglist[@]}" >> "${build_dir}/packages.list"
546
547     # Install packages on airootfs
548     _pacstrap "${_pkglist[@]}"
549
550     return 0
551 }
552
553 make_packages_aur() {
554     readarray -t _pkglist_aur < <("${tools_dir}/pkglist.sh" --aur "${pkglist_args[@]}")
555
556     # Create a list of packages to be finally installed as packages.list directly under the working directory.
557     echo -e "\n# AUR packages.\n#\n" >> "${build_dir}/packages.list"
558     printf "%s\n" "${_pkglist_aur[@]}" >> "${build_dir}/packages.list"
559
560     # prepare for yay
561     cp -rf --preserve=mode "${script_path}/system/aur.sh" "${airootfs_dir}/root/aur.sh"
562
563     # Run aur script
564     _run_with_pacmanconf _chroot_run "bash" "/root/aur.sh" "${makepkg_script_args[@]}" "${_pkglist_aur[@]}"
565
566     # Remove script
567     remove "${airootfs_dir}/root/aur.sh"
568
569     return 0
570 }
571
572 make_pkgbuild() {
573     # Get PKGBUILD List
574     local _pkgbuild_dirs=("${channel_dir}/pkgbuild.any" "${channel_dir}/pkgbuild.${arch}")
575     for_module '_pkgbuild_dirs+=("${module_dir}/{}/pkgbuild.any" "${module_dir}/{}/pkgbuild.${arch}")'
576
577     # Copy PKGBUILD to work
578     mkdir -p "${airootfs_dir}/pkgbuilds/"
579     for _dir in $(find "${_pkgbuild_dirs[@]}" -type f -name "PKGBUILD" -print0 2>/dev/null | xargs -0 -I{} realpath {} | xargs -I{} dirname {}); do
580         msg_info "Find $(basename "${_dir}")"
581         cp -r "${_dir}" "${airootfs_dir}/pkgbuilds/"
582     done
583     
584     # copy buold script
585     cp -rf --preserve=mode "${script_path}/system/pkgbuild.sh" "${airootfs_dir}/root/pkgbuild.sh"
586
587     # Run build script
588     _run_with_pacmanconf _chroot_run "bash" "/root/pkgbuild.sh" "${makepkg_script_args[@]}" "/pkgbuilds"
589
590     # Remove script
591     remove "${airootfs_dir}/root/pkgbuild.sh"
592
593     return 0
594 }
595
596 # Customize installation (airootfs)
597 make_customize_airootfs() {
598     # Overwrite airootfs with customize_airootfs.
599     local _airootfs _airootfs_script_options _script _script_list _airootfs_list=() _main_script
600
601     for_module '_airootfs_list+=("${module_dir}/{}/airootfs.any" "${module_dir}/{}/airootfs.${arch}")'
602     _airootfs_list+=("${channel_dir}/airootfs.any" "${channel_dir}/airootfs.${arch}")
603
604     for _airootfs in "${_airootfs_list[@]}";do
605         if [[ -d "${_airootfs}" ]]; then
606             msg_debug "Copying airootfs ${_airootfs} ..."
607             cp -af "${_airootfs}"/* "${airootfs_dir}"
608         fi
609     done
610
611     # Replace /etc/mkinitcpio.conf if Plymouth is enabled.
612     if [[ "${boot_splash}" = true ]]; then
613         cp -f "${script_path}/mkinitcpio/mkinitcpio-plymouth.conf" "${airootfs_dir}/etc/mkinitcpio.conf"
614     else
615         cp -f "${script_path}/mkinitcpio/mkinitcpio.conf" "${airootfs_dir}/etc/mkinitcpio.conf"
616     fi
617     
618     # customize_airootfs options
619     # -b                        : Enable boot splash.
620     # -d                        : Enable debug mode.
621     # -g <locale_gen_name>      : Set locale-gen.
622     # -i <inst_dir>             : Set install dir
623     # -k <kernel config line>   : Set kernel name.
624     # -o <os name>              : Set os name.
625     # -p <password>             : Set password.
626     # -s <shell>                : Set user shell.
627     # -t                        : Set plymouth theme.
628     # -u <username>             : Set live user name.
629     # -x                        : Enable bash debug mode.
630     # -z <locale_time>          : Set the time zone.
631     # -l <locale_name>          : Set language.
632     #
633     # -j is obsolete in AlterISO3 and cannot be used.
634     # -r is obsolete due to the removal of rebuild.
635     # -k changed in AlterISO3 from passing kernel name to passing kernel configuration.
636
637     # Generate options of customize_airootfs.sh.
638     _airootfs_script_options="-p '${password}' -k '${kernel} ${kernel_filename} ${kernel_mkinitcpio_profile}' -u '${username}' -o '${os_name}' -i '${install_dir}' -s '${usershell}' -a '${arch}' -g '${locale_gen_name}' -l '${locale_name}' -z '${locale_time}' -t ${theme_name}"
639     [[ "${boot_splash}" = true ]] && _airootfs_script_options="${_airootfs_script_options} -b"
640     [[ "${debug}" = true       ]] && _airootfs_script_options="${_airootfs_script_options} -d"
641     [[ "${bash_debug}" = true  ]] && _airootfs_script_options="${_airootfs_script_options} -x"
642
643     _main_script="root/customize_airootfs.sh"
644
645     _script_list=(
646         "${airootfs_dir}/root/customize_airootfs_${channel_name}.sh"
647         "${airootfs_dir}/root/customize_airootfs_${channel_name%.add}.sh"
648     )
649
650     for_module '_script_list+=("${airootfs_dir}/root/customize_airootfs_{}.sh")'
651
652     # Create script
653     for _script in "${_script_list[@]}"; do
654         if [[ -f "${_script}" ]]; then
655             echo -e "\n$(cat "${_script}")" >> "${airootfs_dir}/${_main_script}"
656             remove "${_script}"
657         else
658             msg_debug "${_script} was not found."
659         fi
660     done
661
662     chmod 755 "${airootfs_dir}/${_main_script}"
663     cp "${airootfs_dir}/${_main_script}" "${build_dir}/$(basename ${_main_script})"
664     _chroot_run "${_main_script} ${_airootfs_script_options}"
665     remove "${airootfs_dir}/${_main_script}"
666
667     # /root permission https://github.com/archlinux/archiso/commit/d39e2ba41bf556674501062742190c29ee11cd59
668     chmod -f 750 "${airootfs_dir}/root"
669
670     return 0
671 }
672
673 # Copy mkinitcpio archiso hooks and build initramfs (airootfs)
674 make_setup_mkinitcpio() {
675     local _hook
676     mkdir -p "${airootfs_dir}/etc/initcpio/hooks" "${airootfs_dir}/etc/initcpio/install"
677
678     for _hook in "archiso" "archiso_shutdown" "archiso_pxe_common" "archiso_pxe_nbd" "archiso_pxe_http" "archiso_pxe_nfs" "archiso_loop_mnt"; do
679         cp "${script_path}/system/initcpio/hooks/${_hook}" "${airootfs_dir}/etc/initcpio/hooks"
680         cp "${script_path}/system/initcpio/install/${_hook}" "${airootfs_dir}/etc/initcpio/install"
681     done
682
683     sed -i "s|/usr/lib/initcpio/|/etc/initcpio/|g" "${airootfs_dir}/etc/initcpio/install/archiso_shutdown"
684     cp "${script_path}/system/initcpio/install/archiso_kms" "${airootfs_dir}/etc/initcpio/install"
685     cp "${script_path}/system/initcpio/archiso_shutdown" "${airootfs_dir}/etc/initcpio"
686     if [[ "${boot_splash}" = true ]]; then
687         cp "${script_path}/mkinitcpio/mkinitcpio-archiso-plymouth.conf" "${airootfs_dir}/etc/mkinitcpio-archiso.conf"
688     else
689         cp "${script_path}/mkinitcpio/mkinitcpio-archiso.conf" "${airootfs_dir}/etc/mkinitcpio-archiso.conf"
690     fi
691     if [[ "${gpg_key}" ]]; then
692       gpg --export "${gpg_key}" >"${build_dir}/gpgkey"
693       exec 17<>"${build_dir}/gpgkey"
694     fi
695
696     _chroot_run "mkinitcpio -c /etc/mkinitcpio-archiso.conf -k /boot/${kernel_filename} -g /boot/archiso.img"
697
698     [[ "${gpg_key}" ]] && exec 17<&-
699     
700     return 0
701 }
702
703 # Prepare kernel/initramfs ${install_dir}/boot/
704 make_boot() {
705     mkdir -p "${isofs_dir}/${install_dir}/boot/${arch}"
706     cp "${airootfs_dir}/boot/archiso.img" "${isofs_dir}/${install_dir}/boot/${arch}/archiso.img"
707     cp "${airootfs_dir}/boot/${kernel_filename}" "${isofs_dir}/${install_dir}/boot/${arch}/${kernel_filename}"
708
709     return 0
710 }
711
712 # Add other aditional/extra files to ${install_dir}/boot/
713 make_boot_extra() {
714     if [[ -e "${airootfs_dir}/boot/memtest86+/memtest.bin" ]]; then
715         install -m 0644 -- "${airootfs_dir}/boot/memtest86+/memtest.bin" "${isofs_dir}/${install_dir}/boot/memtest"
716         install -d -m 0755 -- "${isofs_dir}/${install_dir}/boot/licenses/memtest86+/"
717         install -m 0644 -- "${airootfs_dir}/usr/share/licenses/common/GPL2/license.txt" "${isofs_dir}/${install_dir}/boot/licenses/memtest86+/"
718     fi
719
720     local _ucode_image
721     msg_info "Preparing microcode for the ISO 9660 file system..."
722
723     for _ucode_image in {intel-uc.img,intel-ucode.img,amd-uc.img,amd-ucode.img,early_ucode.cpio,microcode.cpio}; do
724         if [[ -e "${airootfs_dir}/boot/${_ucode_image}" ]]; then
725             msg_info "Installimg ${_ucode_image} ..."
726             install -m 0644 -- "${airootfs_dir}/boot/${_ucode_image}" "${isofs_dir}/${install_dir}/boot/"
727             if [[ -e "${airootfs_dir}/usr/share/licenses/${_ucode_image%.*}/" ]]; then
728                 install -d -m 0755 -- "${isofs_dir}/${install_dir}/boot/licenses/${_ucode_image%.*}/"
729                 install -m 0644 -- "${airootfs_dir}/usr/share/licenses/${_ucode_image%.*}/"* "${isofs_dir}/${install_dir}/boot/licenses/${_ucode_image%.*}/"
730             fi
731         fi
732     done
733     msg_info "Done!"
734
735     return 0
736 }
737
738 # Prepare /${install_dir}/boot/syslinux
739 make_syslinux() {
740     mkdir -p "${isofs_dir}/syslinux"
741
742     # 一時ディレクトリに設定ファイルをコピー
743     mkdir -p "${build_dir}/syslinux/"
744     cp -a "${script_path}/syslinux/"* "${build_dir}/syslinux/"
745     if [[ -d "${channel_dir}/syslinux" ]] && [[ "${customized_syslinux}" = true ]]; then
746         cp -af "${channel_dir}/syslinux"* "${build_dir}/syslinux/"
747     fi
748
749     # copy all syslinux config to work dir
750     for _cfg in "${build_dir}/syslinux/"*.cfg; do
751         sed "s|%ARCHISO_LABEL%|${iso_label}|g;
752              s|%OS_NAME%|${os_name}|g;
753              s|%KERNEL_FILENAME%|${kernel_filename}|g;
754              s|%ARCH%|${arch}|g;
755              s|%INSTALL_DIR%|${install_dir}|g" "${_cfg}" > "${isofs_dir}/syslinux/${_cfg##*/}"
756     done
757
758     # Replace the SYSLINUX configuration file with or without boot splash.
759     local _use_config_name _no_use_config_name _pxe_or_sys
760     if [[ "${boot_splash}" = true ]]; then
761         _use_config_name=splash
762         _no_use_config_name=nosplash
763     else
764         _use_config_name=nosplash
765         _no_use_config_name=splash
766     fi
767     for _pxe_or_sys in "sys" "pxe"; do
768         remove "${isofs_dir}/syslinux/archiso_${_pxe_or_sys}_${_no_use_config_name}.cfg"
769         mv "${isofs_dir}/syslinux/archiso_${_pxe_or_sys}_${_use_config_name}.cfg" "${isofs_dir}/syslinux/archiso_${_pxe_or_sys}.cfg"
770     done
771
772     # Set syslinux wallpaper
773     if [[ -f "${channel_dir}/splash.png" ]]; then
774         cp "${channel_dir}/splash.png" "${isofs_dir}/syslinux"
775     else
776         cp "${script_path}/syslinux/splash.png" "${isofs_dir}/syslinux"
777     fi
778
779     # remove config
780     local _remove_config
781     function _remove_config() {
782         remove "${isofs_dir}/syslinux/${1}"
783         sed -i "s|$(grep "${1}" "${isofs_dir}/syslinux/archiso_sys_load.cfg")||g" "${isofs_dir}/syslinux/archiso_sys_load.cfg" 
784     }
785
786     [[ "${norescue_entry}" = true  ]] && _remove_config archiso_sys_rescue.cfg
787     [[ "${memtest86}"      = false ]] && _remove_config memtest86.cfg
788
789     # copy files
790     cp "${airootfs_dir}/usr/lib/syslinux/bios/"*.c32 "${isofs_dir}/syslinux"
791     cp "${airootfs_dir}/usr/lib/syslinux/bios/lpxelinux.0" "${isofs_dir}/syslinux"
792     cp "${airootfs_dir}/usr/lib/syslinux/bios/memdisk" "${isofs_dir}/syslinux"
793
794
795     if [[ -e "${isofs_dir}/syslinux/hdt.c32" ]]; then
796         install -d -m 0755 -- "${isofs_dir}/syslinux/hdt"
797         if [[ -e "${airootfs_dir}/usr/share/hwdata/pci.ids" ]]; then
798             gzip -c -9 "${airootfs_dir}/usr/share/hwdata/pci.ids" > "${isofs_dir}/syslinux/hdt/pciids.gz"
799         fi
800         find "${airootfs_dir}/usr/lib/modules" -name 'modules.alias' -print -exec gzip -c -9 '{}' ';' -quit > "${isofs_dir}/syslinux/hdt/modalias.gz"
801     fi
802
803     return 0
804 }
805
806 # Prepare /isolinux
807 make_isolinux() {
808     install -d -m 0755 -- "${isofs_dir}/syslinux"
809     sed "s|%INSTALL_DIR%|${install_dir}|g" "${script_path}/system/isolinux.cfg" > "${isofs_dir}/syslinux/isolinux.cfg"
810     install -m 0644 -- "${airootfs_dir}/usr/lib/syslinux/bios/isolinux.bin" "${isofs_dir}/syslinux/"
811     install -m 0644 -- "${airootfs_dir}/usr/lib/syslinux/bios/isohdpfx.bin" "${isofs_dir}/syslinux/"
812
813     return 0
814 }
815
816 # Prepare /EFI
817 make_efi() {
818     local _bootfile _use_config_name="nosplash" _efi_config_list=() _efi_config
819     [[ "${boot_splash}" = true ]] && _use_config_name="splash"
820     _bootfile="$(basename "$(ls "${airootfs_dir}/usr/lib/systemd/boot/efi/systemd-boot"*".efi" )")"
821
822     install -d -m 0755 -- "${isofs_dir}/EFI/boot"
823     install -m 0644 -- "${airootfs_dir}/usr/lib/systemd/boot/efi/${_bootfile}" "${isofs_dir}/EFI/boot/${_bootfile#systemd-}"
824
825     install -d -m 0755 -- "${isofs_dir}/loader/entries"
826     sed "s|%ARCH%|${arch}|g;" "${script_path}/efiboot/${_use_config_name}/loader.conf" > "${isofs_dir}/loader/loader.conf"
827
828     readarray -t _efi_config_list < <(find "${script_path}/efiboot/${_use_config_name}/" -mindepth 1 -maxdepth 1 -type f -name "archiso-usb*.conf" -printf "%f" | grep -v "rescue")
829     [[ "${norescue_entry}" = false ]] && readarray -t _efi_config_list < <(find "${script_path}/efiboot/${_use_config_name}/" -mindepth 1 -maxdepth 1 -type f  -name "archiso-usb*rescue*.conf" -printf "%f")
830
831     for _efi_config in "${_efi_config_list[@]}"; do
832         sed "s|%ARCHISO_LABEL%|${iso_label}|g;
833             s|%OS_NAME%|${os_name}|g;
834             s|%KERNEL_FILENAME%|${kernel_filename}|g;
835             s|%ARCH%|${arch}|g;
836             s|%INSTALL_DIR%|${install_dir}|g" \
837         "${_efi_config}" > "${isofs_dir}/loader/entries/$(basename "${_efi_config}" | sed "s|usb|${arch}|g")"
838     done
839
840     # edk2-shell based UEFI shell
841     local _efi_shell_arch
842     if [[ -d "${airootfs_dir}/usr/share/edk2-shell" ]]; then
843         for _efi_shell_arch in $(find "${airootfs_dir}/usr/share/edk2-shell" -mindepth 1 -maxdepth 1 -type d -print0 | xargs -0 -I{} basename {}); do
844             if [[ -f "${airootfs_dir}/usr/share/edk2-shell/${_efi_shell_arch}/Shell_Full.efi" ]]; then
845                 cp "${airootfs_dir}/usr/share/edk2-shell/${_efi_shell_arch}/Shell_Full.efi" "${isofs_dir}/EFI/shell_${_efi_shell_arch}.efi"
846             elif [[ -f "${airootfs_dir}/usr/share/edk2-shell/${_efi_shell_arch}/Shell.efi" ]]; then
847                 cp "${airootfs_dir}/usr/share/edk2-shell/${_efi_shell_arch}/Shell.efi" "${isofs_dir}/EFI/shell_${_efi_shell_arch}.efi"
848             else
849                 continue
850             fi
851             echo -e "title  UEFI Shell ${_efi_shell_arch}\nefi    /EFI/shell_${_efi_shell_arch}.efi" > "${isofs_dir}/loader/entries/uefi-shell-${_efi_shell_arch}.conf"
852         done
853     fi
854
855     return 0
856 }
857
858 # Prepare efiboot.img::/EFI for "El Torito" EFI boot mode
859 make_efiboot() {
860     truncate -s 128M "${build_dir}/efiboot.img"
861     mkfs.fat -n ARCHISO_EFI "${build_dir}/efiboot.img"
862
863     mkdir -p "${build_dir}/efiboot"
864     mount "${build_dir}/efiboot.img" "${build_dir}/efiboot"
865
866     mkdir -p "${build_dir}/efiboot/EFI/alteriso/${arch}"
867     cp "${isofs_dir}/${install_dir}/boot/${arch}/${kernel_filename}" "${build_dir}/efiboot/EFI/alteriso/${arch}/${kernel_filename}.efi"
868     cp "${isofs_dir}/${install_dir}/boot/${arch}/archiso.img" "${build_dir}/efiboot/EFI/alteriso/${arch}/archiso.img"
869
870     local _ucode_image _efi_config _use_config_name="nosplash" _bootfile
871     for _ucode_image in "${airootfs_dir}/boot/"{intel-uc.img,intel-ucode.img,amd-uc.img,amd-ucode.img,early_ucode.cpio,microcode.cpio}; do
872         [[ -e "${_ucode_image}" ]] && cp "${_ucode_image}" "${build_dir}/efiboot/EFI/alteriso/"
873     done
874
875     mkdir -p "${build_dir}/efiboot/EFI/boot"
876
877     cp "${airootfs_dir}/usr/share/efitools/efi/HashTool.efi" "${build_dir}/efiboot/EFI/boot/"
878
879     _bootfile="$(basename "$(ls "${airootfs_dir}/usr/lib/systemd/boot/efi/systemd-boot"*".efi" )")"
880     cp "${airootfs_dir}/usr/lib/systemd/boot/efi/${_bootfile}" "${build_dir}/efiboot/EFI/boot/${_bootfile#systemd-}"
881
882     [[ "${boot_splash}" = true ]] && _use_config_name="splash"
883     mkdir -p "${build_dir}/efiboot/loader/entries"
884     sed "s|%ARCH%|${arch}|g;" "${script_path}/efiboot/${_use_config_name}/loader.conf" > "${build_dir}/efiboot/loader/loader.conf"
885
886     find "${isofs_dir}/loader/entries/" -maxdepth 1 -mindepth 1 -name "uefi-shell*" -type f -printf "%p\0" | xargs -0 -I{} cp {} "${build_dir}/efiboot/loader/entries/"
887
888     readarray -t _efi_config_list < <(find "${script_path}/efiboot/${_use_config_name}/" -mindepth 1 -maxdepth 1 -type f -name "archiso-cd*.conf" -printf "%f" | grep -v "rescue")
889     [[ "${norescue_entry}" = false ]] && readarray -t _efi_config_list < <(find "${script_path}/efiboot/${_use_config_name}/" -mindepth 1 -maxdepth 1 -type f  -name "archiso-cd*rescue*.conf" -printf "%f")
890
891     for _efi_config in "${_efi_config_list[@]}"; do
892         sed "s|%ARCHISO_LABEL%|${iso_label}|g;
893             s|%OS_NAME%|${os_name}|g;
894             s|%KERNEL_FILENAME%|${kernel_filename}|g;
895             s|%ARCH%|${arch}|g;
896             s|%INSTALL_DIR%|${install_dir}|g" \
897         "${_efi_config}" > "${build_dir}/efiboot/loader/entries/$(basename "${_efi_config}" | sed "s|cd|${arch}|g")"
898     done
899
900     find "${isofs_dir}/EFI" -maxdepth 1 -mindepth 1 -name "shell*.efi" -printf "%p\0" | xargs -0 -I{} cp {} "${build_dir}/efiboot/EFI/"
901     umount -d "${build_dir}/efiboot"
902
903     return 0
904 }
905
906 # Compress tarball
907 make_tarball() {
908     # backup airootfs.img for tarball
909     msg_info "Copying airootfs.img ..."
910     cp "${airootfs_dir}.img" "${airootfs_dir}.img.org"
911
912     # Run script
913     mount_airootfs
914     [[ -f "${airootfs_dir}/root/optimize_for_tarball.sh" ]] && _chroot_run "bash /root/optimize_for_tarball.sh -u ${username}"
915
916     _cleanup_common
917     _chroot_run "mkinitcpio -P"
918
919     remove "${airootfs_dir}/root/optimize_for_tarball.sh"
920
921     mkdir -p "${out_dir}"
922     msg_info "Creating tarball..."
923     cd -- "${airootfs_dir}"
924     tar -v -J -p -c -f "${out_dir}/${tar_filename}" ./*
925     cd -- "${OLDPWD}"
926
927     _mkchecksum "${out_dir}/${tar_filename}"
928     msg_info "Done! | $(ls -sh "${out_dir}/${tar_filename}")"
929
930     remove "${airootfs_dir}.img"
931     mv "${airootfs_dir}.img.org" "${airootfs_dir}.img"
932
933     [[ "${noiso}" = true ]] && msg_info "The password for the live user and root is ${password}."
934     
935     return 0
936 }
937
938
939 # Build airootfs filesystem image
940 make_prepare() {
941     mount_airootfs
942
943     # Create packages list
944     msg_info "Creating a list of installed packages on live-enviroment..."
945     pacman-key --init
946     pacman -Q --sysroot "${airootfs_dir}" | tee "${isofs_dir}/${install_dir}/pkglist.${arch}.txt" "${build_dir}/packages-full.list" > /dev/null
947
948     # Cleanup
949     remove "${airootfs_dir}/root/optimize_for_tarball.sh"
950     _cleanup_airootfs
951
952     # Create squashfs
953     mkdir -p -- "${isofs_dir}/${install_dir}/${arch}"
954     msg_info "Creating SquashFS image, this may take some time..."
955     mksquashfs "${airootfs_dir}" "${build_dir}/iso/${install_dir}/${arch}/airootfs.sfs" -noappend -comp "${sfs_comp}" "${sfs_comp_opt[@]}"
956
957     # Create checksum
958     msg_info "Creating checksum file for self-test..."
959     echo "$(sha512sum "${isofs_dir}/${install_dir}/${arch}/airootfs.sfs" | getclm 1) airootfs.sfs" > "${isofs_dir}/${install_dir}/${arch}/airootfs.sha512"
960     msg_info "Done!"
961
962     # Sign with gpg
963     if [[ -v gpg_key ]] && (( "${#gpg_key}" != 0 )); then
964         msg_info "Creating signature file ($gpg_key) ..."
965         cd -- "${isofs_dir}/${install_dir}/${arch}"
966         gpg --detach-sign --default-key "${gpg_key}" "airootfs.sfs"
967         cd -- "${OLDPWD}"
968         msg_info "Done!"
969     fi
970
971     umount_work
972
973     [[ "${cleaning}" = true ]] && remove "${airootfs_dir}" "${airootfs_dir}.img"
974
975     return 0
976 }
977
978 make_alteriso_info(){
979     # iso version info
980     if [[ "${include_info}" = true ]]; then
981         local _info_file="${isofs_dir}/alteriso-info" _version="${iso_version}"
982         remove "${_info_file}"; touch "${_info_file}"
983         [[ -d "${script_path}/.git" ]] && [[ "${gitversion}" = false ]] && _version="${iso_version}-${gitrev}"
984         "${tools_dir}/alteriso-info.sh" -a "${arch}" -b "${boot_splash}" -c "${channel_name%.add}" -d "${iso_publisher}" -k "${kernel}" -o "${os_name}" -p "${password}" -u "${username}" -v "${_version}" > "${_info_file}"
985     fi
986
987     return 0
988 }
989
990 # Add files to the root of isofs
991 make_overisofs() {
992     local _over_isofs_list _isofs
993     _over_isofs_list=("${channel_dir}/over_isofs.any""${channel_dir}/over_isofs.${arch}")
994     for_module '_over_isofs_list+=("${module_dir}/{}/over_isofs.any""${module_dir}/{}/over_isofs.${arch}")'
995     for _isofs in "${_over_isofs_list[@]}"; do
996         [[ -d "${_isofs}" ]] && cp -af "${_isofs}"/* "${isofs_dir}"
997     done
998
999     return 0
1000 }
1001
1002 # Build ISO
1003 make_iso() {
1004     local _iso_efi_boot_args=()
1005     # If exists, add an EFI "El Torito" boot image (FAT filesystem) to ISO-9660 image.
1006     if [[ -f "${build_dir}/efiboot.img" ]]; then
1007         _iso_efi_boot_args=(-append_partition 2 C12A7328-F81F-11D2-BA4B-00A0C93EC93B "${build_dir}/efiboot.img" -appended_part_as_gpt -eltorito-alt-boot -e --interval:appended_partition_2:all:: -no-emul-boot -isohybrid-gpt-basdat)
1008     fi
1009
1010     mkdir -p -- "${out_dir}"
1011     msg_info "Creating ISO image..."
1012     xorriso -as mkisofs \
1013         -iso-level 3 \
1014         -full-iso9660-filenames \
1015         -joliet \
1016         -joliet-long \
1017         -rational-rock \
1018         -volid "${iso_label}" \
1019         -appid "${iso_application}" \
1020         -publisher "${iso_publisher}" \
1021         -preparer "prepared by AlterISO" \
1022         -eltorito-boot syslinux/isolinux.bin \
1023         -eltorito-catalog syslinux/boot.cat \
1024         -no-emul-boot -boot-load-size 4 -boot-info-table \
1025         -isohybrid-mbr "${build_dir}/iso/syslinux/isohdpfx.bin" \
1026         "${_iso_efi_boot_args[@]}" \
1027         -output "${out_dir}/${iso_filename}" \
1028         "${build_dir}/iso/"
1029     _mkchecksum "${out_dir}/${iso_filename}"
1030     msg_info "Done! | $(ls -sh -- "${out_dir}/${iso_filename}")"
1031
1032     msg_info "The password for the live user and root is ${password}."
1033
1034     return 0
1035 }
1036
1037
1038 # Parse options
1039 ARGUMENT=("${@}" ${DEFAULT_ARGUMENT})
1040 OPTS=("a:" "b" "c:" "d" "e" "g:" "h" "j" "k:" "l:" "o:" "p:" "r" "t:" "u:" "w:" "x")
1041 OPTL=("arch:" "boot-splash" "comp-type:" "debug" "cleaning" "cleanup" "gpgkey:" "help" "lang:" "japanese" "kernel:" "out:" "password:" "comp-opts:" "user:" "work:" "bash-debug" "nocolor" "noconfirm" "nodepend" "gitversion" "msgdebug" "noloopmod" "tarball" "noiso" "noaur" "nochkver" "channellist" "config:" "noefi" "nodebug" "nosigcheck" "normwork" "log" "logpath:" "nolog" "nopkgbuild" "pacman-debug" "confirm")
1042 if ! OPT=$(getopt -o "$(printf "%s," "${OPTS[@]}")" -l "$(printf "%s," "${OPTL[@]}")" --  "${ARGUMENT[@]}"); then
1043     exit 1
1044 fi
1045
1046 eval set -- "${OPT}"
1047 msg_debug "Argument: ${OPT}"
1048 unset OPT OPTS OPTL DEFAULT_ARGUMENT
1049
1050 while true; do
1051     case "${1}" in
1052         -a | --arch)
1053             arch="${2}"
1054             shift 2
1055             ;;
1056         -b | --boot-splash)
1057             boot_splash=true
1058             shift 1
1059             ;;
1060         -c | --comp-type)
1061             case "${2}" in
1062                 "gzip" | "lzma" | "lzo" | "lz4" | "xz" | "zstd") sfs_comp="${2}" ;;
1063                 *) msg_error "Invaild compressors '${2}'" '1' ;;
1064             esac
1065             shift 2
1066             ;;
1067         -d | --debug)
1068             debug=true
1069             shift 1
1070             ;;
1071         -e | --cleaning | --cleanup)
1072             cleaning=true
1073             shift 1
1074             ;;
1075         -g | --gpgkey)
1076             gpg_key="${2}"
1077             shift 2
1078             ;;
1079         -h | --help)
1080             _usage
1081             exit 0
1082             ;;
1083         -j | --japanese)
1084             msg_error "This option is obsolete in AlterISO 3. To use Japanese, use \"-l ja\"." "1"
1085             ;;
1086         -k | --kernel)
1087             customized_kernel=true
1088             kernel="${2}"
1089             shift 2
1090             ;;
1091         -l | --lang)
1092             locale_name="${2}"
1093             shift 2
1094             ;;
1095         -o | --out)
1096             out_dir="${2}"
1097             shift 2
1098             ;;
1099         -p | --password)
1100             customized_password=true
1101             password="${2}"
1102             shift 2
1103             ;;
1104         -r | --tarball)
1105             tarball=true
1106             shift 1
1107             ;;
1108         -t | --comp-opts)
1109             if [[ "${2}" = "reset" ]]; then
1110                 sfs_comp_opt=()
1111             else
1112                 sfs_comp_opt=(${2})
1113             fi
1114             shift 2
1115             ;;
1116         -u | --user)
1117             customized_username=true
1118             username="$(echo -n "${2}" | sed 's/ //g' | tr '[:upper:]' '[:lower:]')"
1119             shift 2
1120             ;;
1121         -w | --work)
1122             work_dir="${2}"
1123             shift 2
1124             ;;
1125         -x | --bash-debug)
1126             debug=true
1127             bash_debug=true
1128             shift 1
1129             ;;
1130         --noconfirm)
1131             noconfirm=true
1132             shift 1
1133             ;;
1134         --confirm)
1135             noconfirm=false
1136             shift 1
1137             ;;
1138         --nodepend)
1139             nodepend=true
1140             shift 1
1141             ;;
1142         --nocolor)
1143             nocolor=true
1144             shift 1
1145             ;;
1146         --gitversion)
1147             if [[ -d "${script_path}/.git" ]]; then
1148                 gitversion=true
1149             else
1150                 msg_error "There is no git directory. You need to use git clone to use this feature." "1"
1151             fi
1152             shift 1
1153             ;;
1154         --msgdebug)
1155             msgdebug=true;
1156             shift 1
1157             ;;
1158         --noloopmod)
1159             noloopmod=true
1160             shift 1
1161             ;;
1162         --noiso)
1163             noiso=true
1164             shift 1
1165             ;;
1166         --noaur)
1167             noaur=true
1168             shift 1
1169             ;;
1170         --nochkver)
1171             nochkver=true
1172             shift 1
1173             ;;
1174         --nodebug)
1175             debug=false
1176             msgdebug=false
1177             bash_debug=false
1178             shift 1
1179             ;;
1180         --noefi)
1181             noefi=true
1182             shift 1
1183             ;;
1184         --channellist)
1185             show_channel_list
1186             exit 0
1187             ;;
1188         --config)
1189             source "${2}"
1190             shift 2
1191             ;;
1192         --pacman-debug)
1193             pacman_debug=true
1194             shift 1
1195             ;;
1196         --nosigcheck)
1197             nosigcheck=true
1198             shift 1
1199             ;;
1200         --normwork)
1201             normwork=true
1202             shift 1
1203             ;;
1204         --log)
1205             logging=true
1206             shift 1
1207             ;;
1208         --logpath)
1209             logging="${2}"
1210             customized_logpath=true
1211             shift 2
1212             ;;
1213         --nolog)
1214             logging=false
1215             shift 1
1216             ;;
1217         --nopkgbuild)
1218             nopkgbuild=true
1219             shift 1
1220             ;;
1221         --)
1222             shift
1223             break
1224             ;;
1225         *)
1226             msg_error "Invalid argument '${1}'"
1227             _usage 1
1228             ;;
1229     esac
1230 done
1231
1232 # Check root.
1233 if (( ! "${EUID}" == 0 )); then
1234     msg_warn "This script must be run as root." >&2
1235     msg_warn "Re-run 'sudo ${0} ${ARGUMENT[*]}'"
1236     sudo "${0}" "${ARGUMENT[@]}"
1237     exit "${?}"
1238 fi
1239
1240 # Show config message
1241 msg_debug "Use the default configuration file (${defaultconfig})."
1242 [[ -f "${script_path}/custom.conf" ]] && msg_debug "The default settings have been overridden by custom.conf"
1243
1244 # Debug mode
1245 [[ "${bash_debug}" = true ]] && set -x -v
1246
1247 # Check for a valid channel name
1248 if [[ -n "${1+SET}" ]]; then
1249     case "$(bash "${tools_dir}/channel.sh" --version "${alteriso_version}" -n check "${1}"; printf "${?}")" in
1250         "2")
1251             msg_error "Invalid channel ${1}" "1"
1252             ;;
1253         "1")
1254             channel_dir="${1}"
1255             channel_name="$(basename "${1%/}")"
1256             ;;
1257         "0")
1258             channel_dir="${script_path}/channels/${1}"
1259             channel_name="${1}"
1260             ;;
1261     esac
1262 else
1263     channel_dir="${script_path}/channels/${channel_name}"
1264 fi
1265
1266 # Set vars
1267 work_dir="$(realpath "${work_dir}")"
1268 build_dir="${work_dir}/build/${arch}"
1269 cache_dir="${work_dir}/cache/${arch}"
1270 airootfs_dir="${build_dir}/airootfs"
1271 isofs_dir="${build_dir}/iso"
1272 lockfile_dir="${build_dir}/lockfile"
1273 gitrev="$(cd "${script_path}"; git rev-parse --short HEAD)"
1274
1275 # Create dir
1276 for _dir in "${build_dir}" "${cache_dir}" "${airootfs_dir}" "${isofs_dir}" "${lockfile_dir}"; do
1277     mkdir -p "${_dir}"
1278 done
1279
1280 # Set for special channels
1281 if [[ -d "${channel_dir}.add" ]]; then
1282     channel_name="${1}"
1283     channel_dir="${channel_dir}.add"
1284 elif [[ "${channel_name}" = "clean" ]]; then
1285    _run_cleansh
1286     exit 0
1287 fi
1288
1289 # Check channel version
1290 msg_debug "channel path is ${channel_dir}"
1291 if [[ ! "$(bash "${tools_dir}/channel.sh" --version "${alteriso_version}" ver "${channel_name}" | cut -d "." -f 1)" = "$(echo "${alteriso_version}" | cut -d "." -f 1)" ]] && [[ "${nochkver}" = false ]]; then
1292     msg_error "This channel does not support Alter ISO 3."
1293     if [[ -d "${script_path}/.git" ]]; then
1294         msg_error "Please run \"git checkout alteriso-2\"" "1"
1295     else
1296         msg_error "Please download old version here.\nhttps://github.com/FascodeNet/alterlinux/releases" "1"
1297     fi
1298 fi
1299
1300 set -eu
1301
1302 prepare_env
1303 prepare_build
1304 show_settings
1305 run_once make_pacman_conf
1306 run_once make_basefs # Mount airootfs
1307 run_once make_packages_repo
1308 [[ "${noaur}" = false ]] && run_once make_packages_aur
1309 [[ "${nopkgbuild}" = false ]] && run_once make_pkgbuild
1310 run_once make_customize_airootfs
1311 run_once make_setup_mkinitcpio
1312 [[ "${tarball}" = true ]] && run_once make_tarball
1313 if [[ "${noiso}" = false ]]; then
1314     run_once make_syslinux
1315     run_once make_isolinux
1316     run_once make_boot
1317     run_once make_boot_extra
1318     if [[ "${noefi}" = false ]]; then
1319         run_once make_efi
1320         run_once make_efiboot
1321     fi
1322     run_once make_alteriso_info
1323     run_once make_prepare
1324     run_once make_overisofs
1325     run_once make_iso
1326 fi
1327
1328 [[ "${cleaning}" = true ]] && _run_cleansh
1329
1330 exit 0