OSDN Git Service

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