OSDN Git Service

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