OSDN Git Service

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