#!/bin/sh
printf '\033[8;60;172t'
clear

LocalScriptVer="v1.0.5"
RemoteScriptVer=""
RemoteScriptPath="https://raw.githubusercontent.com/crazybirdy/MBR-Manual-Method/master/Q6-DownloadFullApp"
LocateScriptPath="$HOME/Desktop/"
ScriptName="installScript_110fullapp"

FileNameArray=(
  )

autodownload() {
if [[ ! -d "${LocateScriptPath}" ]]; then
  mkdir -p "${LocateScriptPath}"
fi
let index=0
for filename in "${FileNameArray[@]}"; do
  if [[ ! -f "${LocateScriptPath}/${filename}" ]]; then
    echo
    echo "Downloading: ${filename} ..."
    curl "${RemoteScriptPath}/${filename}" -o "${LocateScriptPath}/${filename}"
  fi
  let index++
done
if [[ ! -f "${LocateScriptPath}/${ScriptName}" ]]; then
  cat "$0" > "${LocateScriptPath}/${ScriptName}"
  chmod +x "${LocateScriptPath}/${ScriptName}"
  exec "${LocateScriptPath}/${ScriptName}"
fi
}
selfUpdate() {
  echo
  cat "/private/tmp/${ScriptName}" > "${LocateScriptPath}/${ScriptName}"
  chmod +x "${LocateScriptPath}/${ScriptName}"
  open "${LocateScriptPath}"
  exec "${LocateScriptPath}/${ScriptName}"
}
IsNumericOnly() {
  [[ "${1}" =~ ^-?[0-9]+$ ]] && return 0 || return 1
}
updatescript() {
  autodownload
  rm -f "/private/tmp/${ScriptName}"
  curl "${RemoteScriptPath}/${ScriptName}" -o "/private/tmp/${ScriptName}" 2>/dev/null

  RemoteScriptVer=$( cat /private/tmp/${ScriptName} | grep 'LocalScriptVer="v' | grep -v grep | tr -cd '.0-9' )
  LVALUE=$( echo $LocalScriptVer | tr -cd [:digit:] )
  RVALUE=$( echo $RemoteScriptVer | tr -cd [:digit:] )

  if [[ -d "$HOME/MBR-Manual-Method/" ]]; then
    if [[ ! -f "$HOME/MBR-Manual-Method/RunMe" ]]; then
      rm -rf "$HOME/MBR-Manual-Method/"
    fi
  fi

  echo
  if IsNumericOnly $RVALUE; then
    [[ $LVALUE -eq $RVALUE ]] && printf "\e[1;34mLocal: ${LocalScriptVer}  ..  Remote: v${RemoteScriptVer}\e[1;32m%*s\e[0m" $((40-${#LocalScriptVer})) "No update available."
    [[ $LVALUE -gt $RVALUE ]] && printf "\e[1;34mLocal: ${LocalScriptVer}  ..  Remote: v${RemoteScriptVer}\e[1;31m%*s\e[0m" $((40-${#LocalScriptVer})) "Wow, are you coming from the future?"
    [[ $LVALUE -lt $RVALUE ]] && printf "\e[1;34mLocal: ${LocalScriptVer}  ..  Remote: v${RemoteScriptVer}\e[1;5;34m%*s\e[0m" $((40-${#LocalScriptVer})) "Update available (v$RemoteScriptVer)" && selfUpdate 
  else
    printf "${LocalScriptVer}\e[1;31m\n%s\e[0m" "Remote version unavailable due to unknown reasons!"
  fi
  clear
}

#
# This script is refer to Pike R. Alpha's work as follow, also thanks to Pike R. Alpha.       by crazybirdy. v9.20200708
#

########################################################################################################################
# https://github.com/Piker-Alpha/HandyScripts/blob/master/installScriptTemplate.sh                                     #
# Bash script to download macOS High Sierra installation packages from sucatalog.gz and build the installer.pkg for it.#
# version 2.1 - Copyright (c) 2017 by Pike R. Alpha (PikeRAlpha@yahoo.com)                                             #
########################################################################################################################

printred() {
  printf "\e[1;31m${1}\e[0m"
}
printgreen() {
  printf "\e[1;32m${1}\e[0m"
}
printyellow() {
  printf "\e[1;33m${1}\e[0m"
}
printblue() {
  printf "\e[1;34m${1}\e[0m"
}
printpurple() {
  printf "\e[1;35m${1}\e[0m"
}
printLatest() {
  printf "\e[1;31m${1}\e[0m"
}
function headline()
{
  echo 
  printf "從 swscan.apple.com 下載完整安裝app.    Download the full installer app from swscan.apple.com.\n"
  echo 
}
function catalogselect()
{
  # CatalogURL for Regular Software Updates
  CatalogURLRegular="https://swscan.apple.com/content/catalogs/others/index-10.16-10.15-10.14-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz"
  # CatalogURL for Public Beta Program Members
  CatalogURLPublic="https://swscan.apple.com/content/catalogs/others/index-10.16beta-10.16-10.15-10.14-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz"
  # CatalogURL for Developer Beta Program Members
  CatalogURLDeveloper="https://swscan.apple.com/content/catalogs/others/index-10.16seed-10.16-10.15-10.14-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz"

  echo
  printred "1.選用 正式版 下載渠道。\n"
  printred "1.Use CatalogURL for Regular Software Updates\n"
  echo "${CatalogURLRegular}"
  echo
  printred "2.選用 公開測試版 下載渠道。\n"
  printred "2.Use CatalogURL for Public Beta Program Members\n"
  echo "${CatalogURLPublic}"
  echo
  printred "3.選用 開發者測試版 下載渠道。\n"
  printred "3.Use CatalogURL for Developer Beta Program Members\n"
  echo "${CatalogURLDeveloper}"
  echo
  read -p "請選擇 要下載的 版本  Select the CatalogURL ( 1 / 2 / 3 ) : " macOSver

  case $macOSver in
    1)
      # CatalogURL for Regular Software Updates
      CatalogURL="${CatalogURLRegular}"
      CatalogURLver="正式版 下載渠道 Regular Software Updates"
    ;;
    2)
      # CatalogURL for Developer Beta Program Members
      CatalogURL="${CatalogURLPublic}"
      CatalogURLver="公開測試版 下載渠道 Public Beta Updates"
    ;;
    3)
      # CatalogURL for Developer Beta Program Members
      CatalogURL="${CatalogURLDeveloper}"
      CatalogURLver="開發者測試版 下載渠道 Developer Beta Updates"
    ;;
    *)
      # CatalogURL for Regular Software Updates
      CatalogURL="${CatalogURLRegular}"
      CatalogURLver="正式版 下載渠道 Regular Software Updates"
    ;;
  esac

  echo
  printf "選用版本  The selected CatalogURL:  \e[1;32m$CatalogURLver\e[0m\n"
  echo "${CatalogURL}"
  echo
  echo
  echo "正在搜尋完整安裝app，請耐心等候！ Searching for full installer app from catalogs of swscan.apple.com. Be patient!"
  echo 

  cd /private/tmp
  rm -f fullapp-*
  curl ${CatalogURL} -o fullapp-catalogs.gz 2>/dev/null

  found404=`cat fullapp-catalogs.gz | grep Not | grep Found `
  if [[ ! $found404 == "" ]]; then
      printf "  未找到  Not found the CatalogURL: \e[1;32m$CatalogURLver\e[0m\n"
      echo
      exit
  fi

  gunzip fullapp-catalogs.gz
  catalogfile="/private/tmp/fullapp-catalogs"
}
function fullapparray()
{
  # 10.15
  macOSdmgAllArray=`cat ${catalogfile} | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}'`
  let index=0
  for element in "${macOSdmgAllArray[@]}"; do
    macOSdmgAAll[$index]="${element}"
    let index++
  done

  # 10.16 11.0
  macOSpkgAllArray=`cat ${catalogfile} | grep InstallAssistant.pkg | grep -v integrityData | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}'`
  let index=0
  for element in "${macOSpkgAllArray[@]}"; do
    macOSpkgAAll[$index]="${element}"
    let index++
  done

  macOSdmgA=($(echo "${macOSdmgAAll[@]}" "${macOSpkgAAll[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))

	index=0
	for macOSdmglist in "${macOSdmgA[@]}"
	do
    checkdmg=`echo $macOSdmglist | grep BaseSystem.dmg `
    checkpkg=`echo $macOSdmglist | grep InstallAssistant.pkg `
    # 10.15
    if [[ ! $checkdmg == "" ]]; then
			macOSdmgpath=${macOSdmglist%%'BaseSystem.dmg'*}

			macOSUpdkey[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $7;}' `
			macOSUpdkeydistribution[$index]=`echo ${macOSUpdkey[$index]} | sed 's/.\{9\}/& /g' | awk '{print $1;}' `

			url="${macOSdmgpath}"
			distribution="${macOSUpdkeydistribution[$index]}.English.dist"
			rm -f *dist

			curl $url$distribution -o ${macOSUpdkeydistribution[$index]}.English.dist 2>/dev/null
			macOSupdateosver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep InstallAssistantAuto | grep version | awk '{print $4;}' | sed 's/version="//g' | sed 's/.\{7\}/& /g' | awk '{print $1;}' `
			macOSupdatebuildver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep -A1 BUILD | grep -A1 key | grep string | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}' `
			macOSupdatebeta[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep SU_TITLE | grep strings | grep macOS | grep Beta | sed 's/<strings language="English">"SU_TITLE" = "//g' | sed 's/";//g' | sed 's/Install //g' | sed 's/    //g' | sed 's/    //g' | sed 's/  //g' `
			rm -f *dist

			macOSupdatebuildver[$index]="${macOSupdateosver[$index]}.${macOSupdatebuildver[$index]}"

			macOSver=`echo ${macOSupdateosver[$index]} | sed 's/.\{5\}/& /g' | awk '{print $1;}' `
			if [[ ${macOSver} < 10.16 ]]; then
				if [[ ${macOSupdatebeta[$index]} == "" ]]; then
					macOSdmgBAll[$index]="${macOSupdatebuildver[$index]}=${macOSdmglist}"
					let index++
				fi 
			elif [[ ${macOSver} > 10.15 ]]; then
				macOSdmgBAll[$index]="${macOSupdatebuildver[$index]}=${macOSdmglist}"
				let index++
			fi
		fi
    # 10.16 11.0
    if [[ ! $checkpkg == "" ]]; then
      macOSdmgpath=${macOSdmglist%%'InstallAssistant.pkg'*}

      macOSUpdkey[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $7;}' `
      macOSUpdkeydistribution[$index]=`echo ${macOSUpdkey[$index]} | sed 's/.\{9\}/& /g' | awk '{print $1;}' `

      url="${macOSdmgpath}"
      distribution=`cat ${catalogfile} | grep ${macOSUpdkey[$index]} | grep English.dist | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `
      rm -f *dist

      curl $url$distribution -o ${macOSUpdkeydistribution[$index]}.English.dist 2>/dev/null
      macOSupdateosver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep -A1 VERSION | grep -A1 key | grep string | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}' `
      macOSverFive=`echo ${macOSupdateosver[$index]} | sed 's/.\{5\}/& /g' | awk '{print $2;}' `
      if [[ ${macOSverFive} == "" ]]; then
        macOSupdateosver[$index]="${macOSupdateosver[$index]}.0"
      fi
      macOSupdatebuildver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep -A1 BUILD | grep -A1 key | grep string | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}' `
      macOSupdatebeta[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep SU_TITLE | grep strings | grep macOS | grep Beta | sed 's/<strings language="English">"SU_TITLE" = "//g' | sed 's/";//g' | sed 's/Install //g' | sed 's/    //g' | sed 's/    //g' | sed 's/  //g' `
      rm -f *dist

      macOSupdatebuildver[$index]="${macOSupdateosver[$index]}.${macOSupdatebuildver[$index]}"

      macOSver=`echo ${macOSupdateosver[$index]} | sed 's/.\{5\}/& /g' | awk '{print $1;}' `
      if [[ ${macOSver} < 10.16 ]]; then
        if [[ ${macOSupdatebeta[$index]} == "" ]]; then
          macOSdmgBAll[$index]="${macOSupdatebuildver[$index]}=${macOSdmglist}"
          let index++
        fi 
      elif [[ ${macOSver} > 10.15 ]]; then
        macOSdmgBAll[$index]="${macOSupdatebuildver[$index]}=${macOSdmglist}"
        let index++
      fi
    fi
	done
	
	macOSdmgB=($(echo "${macOSdmgBAll[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))

	index=0
	for macOSdmglist in "${macOSdmgB[@]}"
	do
		if [[ ! $macOSdmglist == "" ]]; then
			macOSdmg[$index]=`echo $macOSdmglist | sed 's/=/ /g' | awk '{print $2;}' `
			let index++
		fi
	done
}
function fullapplist()
{
  index=0
  for macOSdmglist in "${macOSdmg[@]}"
  do
    checkdmg=`echo $macOSdmglist | grep BaseSystem.dmg `
    checkpkg=`echo $macOSdmglist | grep InstallAssistant.pkg `
    # 10.15
    if [[ ! $checkdmg == "" ]]; then
      macOSdmgpath=${macOSdmglist%%'BaseSystem.dmg'*}
      macOSUpdver[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $9;}' | sed 's/macOSUpd//g' | sed 's/.pkg//g' `
      macOSUpdversion1[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $5;}' `
      macOSUpdversion2[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $6;}' `
      macOSUpdversion[$index]="${macOSUpdversion1[$index]}/${macOSUpdversion2[$index]}"
      macOSUpdkey[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $7;}' `
      macOSUpdkeydistribution[$index]=`echo ${macOSUpdkey[$index]} | sed 's/.\{9\}/& /g' | awk '{print $1;}' `
      macOSUpdsalt[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $8;}' `

      url="${macOSdmgpath}"
      distribution="${macOSUpdkeydistribution[$index]}.English.dist"
      rm -f *dist

      curl $url$distribution -o ${macOSUpdkeydistribution[$index]}.English.dist 2>/dev/null
      macOSupdateosver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep InstallAssistantAuto | grep version | awk '{print $4;}' | sed 's/version="//g' | sed 's/.\{7\}/& /g' | awk '{print $1;}' `
      macOSupdatebeta[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep SU_TITLE | grep strings | grep macOS | sed 's/<strings language="English">"SU_TITLE" = "//g' | sed 's/";//g' | sed 's/Install //g' | sed 's/    //g' | sed 's/    //g' | sed 's/  //g' `
      macOSupdatebuildver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep -A1 BUILD | grep -A1 key | grep string | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}' `
      rm -f *dist

      macOSupdatebuildver[$index]="${macOSupdateosver[$index]}.${macOSupdatebuildver[$index]}"
      macOSuptime[$index]=`cat ${catalogfile} | grep -A 5 PostDate | grep -B 7 ${macOSUpdkeydistribution[$index]} | grep \<date\> | sed 's/<date>//g' | sed 's/<\/date>//g' | awk '{print $1;}' | sed 's/T/ /g' | sed 's/Z//g' | awk NR==1 `
      macOSupdate[$index]="${macOSuptime[$index]} .. ${macOSUpdkeydistribution[$index]} .. ${macOSupdatebuildver[$index]} ${macOSupdatebeta[$index]}"
      macOSlist[$index]=`echo ${macOSdmglist} `
      let index++
    fi
    # 10.16 11.0
    if [[ ! $checkpkg == "" ]]; then
      macOSdmgpath=${macOSdmglist%%'InstallAssistant.pkg'*}
      macOSUpdver[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $9;}' | sed 's/macOSUpd//g' | sed 's/.pkg//g' `
      macOSUpdversion1[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $5;}' `
      macOSUpdversion2[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $6;}' `
      macOSUpdversion[$index]="${macOSUpdversion1[$index]}/${macOSUpdversion2[$index]}"
      macOSUpdkey[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $7;}' `
      macOSUpdkeydistribution[$index]=`echo ${macOSUpdkey[$index]} | sed 's/.\{9\}/& /g' | awk '{print $1;}' `
      macOSUpdsalt[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $8;}' `

      url="${macOSdmgpath}"
      distribution=`cat ${catalogfile} | grep ${macOSUpdkey[$index]} | grep English.dist | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `
      rm -f *dist

      curl $url$distribution -o ${macOSUpdkeydistribution[$index]}.English.dist 2>/dev/null
      macOSupdateosver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep -A1 VERSION | grep -A1 key | grep string | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}' `
      macOSverFive=`echo ${macOSupdateosver[$index]} | sed 's/.\{5\}/& /g' | awk '{print $2;}' `
      if [[ ${macOSverFive} == "" ]]; then
        macOSupdateosver[$index]="${macOSupdateosver[$index]}.0"
      fi
      macOSupdatebeta[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep title | grep \/title | grep macOS | sed 's/<title>//g' | sed 's/<\/title>//g' | sed 's/    //g'  `
      macOSupdatebuildver[$index]=`cat ${macOSUpdkeydistribution[$index]}.English.dist | grep -A1 BUILD | grep -A1 key | grep string | sed 's/<string>//g' | sed 's/<\/string>//g' | awk '{print $1;}' `
      rm -f *dist

      macOSupdatebuildver[$index]="${macOSupdateosver[$index]}.${macOSupdatebuildver[$index]}"
      macOSuptime[$index]=`cat ${catalogfile} | grep -A 5 PostDate | grep -B 7 ${macOSUpdkeydistribution[$index]} | grep \<date\> | sed 's/<date>//g' | sed 's/<\/date>//g' | awk '{print $1;}' | sed 's/T/ /g' | sed 's/Z//g' | awk NR==1 `
      macOSupdate[$index]="${macOSuptime[$index]} .. ${macOSUpdkeydistribution[$index]} .. ${macOSupdatebuildver[$index]} ${macOSupdatebeta[$index]}"
      macOSlist[$index]=`echo ${macOSdmglist} `
      let index++
    fi
  done

  index=0
  for list in "${macOSupdate[@]}"
  do
    echo "${macOSlist[$index]}"
    let index++
  done
}
function selectfullappversion()
{
  indexupdatever=0
  Latestupdatever=0
  for updatever in "${macOSupdatebuildver[@]}"
  do
    if [[ $updatever > $Latestupdatever ]]; then
      Latestupdatever=${macOSupdatebuildver[$indexupdatever]}
      Latestupdatebeta=${macOSupdatebeta[$indexupdatever]}
    fi
    let indexupdatever++
  done

  echo
  printf "最新版本 The latest version: \e[1;32m$Latestupdatever $Latestupdatebeta\e[0m\n"

  echo
  echo "可選擇下載的版本 Available version to downlaod:"
  echo

  indexmenu=0
  for updateselect in "${macOSupdate[@]}"
  do
    if [[ ${macOSupdatebuildver[$indexmenu]} == $Latestupdatever ]]; then
      printLatest "[ $indexmenu ] ${updateselect}"
      echo
    else
      echo "[ $indexmenu ] ${updateselect}"
    fi
    checkdownloadver[$indexmenu]=$indexmenu
    let indexmenu++
  done

  echo
  read -p "選擇要下載的版本 Select one version to downlaod: " downloadver
  if [[ ! $downloadver ]]; then
    echo
    echo "發生錯誤！！！                          Error!!!"
    echo
    echo "請選擇正確下載的版本。                  Please select right version to downlaod."
    echo
    rm -f ${catalogfile}
    exit 0
  fi

  checkfine=no
  checkindex=0
  for checkindex in "${checkdownloadver[@]}"
  do
    if [[ $downloadver == $checkindex ]]; then
      checkfine=yes
    fi
    let checkindex++
  done
  if [[ $checkfine == no ]]; then
    echo
    echo "發生錯誤！！！                          Error!!!"
    echo
    echo "請選擇正確下載的版本。                  Please select right version to downlaod."
    echo
    rm -f ${catalogfile}
    exit 0
  fi
}
function downloadfullapp()
{
  updatever="${macOSUpdver[$downloadver]}"
  version="${macOSUpdversion[$downloadver]}"
  key="${macOSUpdkey[$downloadver]}"
  salt="${macOSUpdsalt[$downloadver]}"
  echo "                                               [ $downloadver ] ${macOSupdate[$downloadver]}"

  distribution=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep English | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' `

    targetFiles[0]=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep -v integrityData | grep InstallAssistantAuto.pkg | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `
    targetFiles[1]=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep -v integrityData | grep AppleDiagnostics.chunklist | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `
    targetFiles[2]=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep -v integrityData | grep AppleDiagnostics.dmg | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `
    targetFiles[3]=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep -v integrityData | grep BaseSystem.chunklist | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `
    targetFiles[4]=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep -v integrityData | grep BaseSystem.dmg | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `
    targetFiles[5]=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep -v integrityData | grep InstallESDDmg.pkg | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `

  rm -f ${catalogfile}
  cd

  #
  # Initialisation of a variable (our target folder).
  #
  tmpDirectory="/private/tmp"

  #
  # URL copied from sucatalog.gz (think CatalogURL).
  #
  url="https://swdist.apple.com/content/downloads/${version}/${key}/${salt}/"

  #
  # Target distribution language.
  #
  keydistribution=`echo ${key} | sed 's/.\{9\}/& /g' | awk '{print $1;}' `
  distribution="${keydistribution}.English.dist"

  #
  # Check target directory.
  #
  if [[ -d "${tmpDirectory}/${key}" ]]; then
    rm -rf "${tmpDirectory}/${key}"
    mkdir "${tmpDirectory}/${key}"
  fi
  if [[ ! -d "${tmpDirectory}/${key}" ]]; then
    mkdir "${tmpDirectory}/${key}"
  fi
  open "${tmpDirectory}/${key}"

  echo 
  echo "準備進行下載。Prepare to download the files.   [ $downloadver ] ${macOSupdate[$downloadver]}."
  echo 
  echo "${url}${distribution}"
  for filename in "${targetFiles[@]}"
  do
    if [[ ! $filename == "" ]]; then
      echo "${url}$filename"
    fi
  done
  echo

  printred "如果你已經發生下載錯誤，可以 預先手動下載 上列網址文件，並將文件放入 以下 正確的文件夾 即可繼續進行。\n"
  printred "If get errors of downloading before, you can download files as above URL manually and put into correct folder as below before continuing.\n"
  echo

  echo "${tmpDirectory}/${key}/${distribution}"
  for filename in "${targetFiles[@]}"
  do
    if [[ ! $filename == "" ]]; then
      echo "${tmpDirectory}/${key}/$filename"
    fi
  done
  echo

  read -p "手動下載放入上列文件，或由腳本自動下載文件，繼續進行？   Put files as above manually or download files automatically, continue? (y/n) " downloadyesno
  case "$downloadyesno" in
    y|Y)
      echo
    ;;
    *)
      echo
      echo "停止進行下載！！！               Stop downloading!!!"
      echo
      exit 0
    ;;
  esac

  #
  # Download distribution file.
  #
  if [[ ! -e "${tmpDirectory}/${key}/${distribution}" ]]; then
    echo "Downloading: ${distribution} ..."
    curl "${url}${distribution}" -o "${tmpDirectory}/${key}/${distribution}"
    #
    # Remove root only restriction/allow us to install on any target volume.
    #
    cat "${tmpDirectory}/${key}/${distribution}" | sed -e 's|rootVolumeOnly="true"|allow-external-scripts="true"|' > "${tmpDirectory}/${key}/new.dist"

    if [[ -e "${tmpDirectory}/${key}/new.dist" ]]; then
      mv "${tmpDirectory}/${key}/new.dist" "${tmpDirectory}/${key}/${distribution}"
    fi
  else
    echo "File: ${distribution} already there, skipping this download."
  fi

  #
  # Change to working directory (otherwise it will fail to locate the packages).
  #
  cd "${tmpDirectory}/${key}"

  #
  # Download target files.
  #
  for filename in "${targetFiles[@]}"
  do
    if [[ ! $filename == "" ]]; then
      if [[ ! -e "${tmpDirectory}/${key}/${filename}" ]]; then
        echo "Downloading: ${filename} ..."
        curl "${url}${filename}" -o "${tmpDirectory}/${key}/${filename}"
      else
        echo "File: ${filename} already there, skipping this download."
      fi
    fi
  done

  pkgutil --expand-full InstallAssistantAuto.pkg Installapp

  cd "${tmpDirectory}/${key}/Installapp/Payload/"
  fullappnames=(*)

  echo
  echo "找到 Found ...... ${fullappnames}"
  echo

  for appname in "${fullappnames[@]}"
  do
        if [[ -e "${tmpDirectory}/${key}/Installapp/Payload/${appname}/Contents/SharedSupport/" ]]; then
          mv "${tmpDirectory}/${key}/AppleDiagnostics.chunklist" "${tmpDirectory}/${key}/Installapp/Payload/${appname}/Contents/SharedSupport/"
          mv "${tmpDirectory}/${key}/AppleDiagnostics.dmg" "${tmpDirectory}/${key}/Installapp/Payload/${appname}/Contents/SharedSupport/"
          mv "${tmpDirectory}/${key}/BaseSystem.chunklist" "${tmpDirectory}/${key}/Installapp/Payload/${appname}/Contents/SharedSupport/"
          mv "${tmpDirectory}/${key}/BaseSystem.dmg" "${tmpDirectory}/${key}/Installapp/Payload/${appname}/Contents/SharedSupport/"
          mv "${tmpDirectory}/${key}/InstallESDDmg.pkg" "${tmpDirectory}/${key}/Installapp/Payload/${appname}/Contents/SharedSupport/InstallESD.dmg"
          rm -rf "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}"
          mkdir -p "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}"
          mv "${tmpDirectory}/${key}/Installapp/Payload/${appname}" "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
          newappname="${appname}"
        fi
  done

  echo "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  ls -la "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  echo
  echo "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/${newappname}/Contents/SharedSupport/"
  ls -la "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/${newappname}/Contents/SharedSupport/"
  open "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"

  echo
  echo "完整安裝app 存放在 $HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  echo "The full installer app is located on $HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  echo
  printf "\e[1;34mMake sure you get the full installer without any errors during the downloading process.\e[0m\n"
  printf "\e[1;34m1.check the received sizes of each file, make sure they’re all 100 downloaded.\e[0m\n"
  printf "\e[1;34m2.if any one of the files \e[0m\e[1;31mgets error\e[0m\e[1;34m during the downloading process,\e[0m\n"
  printf "\e[1;34m  and\e[0m \e[1;31mdidn’t get 100 downloaded,\e[0m\e[1;34m you\e[0m \e[1;31mneed to re-download the full installer app again.\e[0m\n"
  echo
  if [[ -d "${tmpDirectory}/${key}" ]]; then
    rm -rf "${tmpDirectory}/${key}"
  fi
}
function checkspace()
{
  RootDisk="/"

  # 10.11-
  TotalSpace=`diskutil info "${RootDisk}" | grep "Total Size" | awk '{print $3;}' `
  # 10.12+
  if [[ ${TotalSpace} == "" ]]; then
  	TotalSpace=`diskutil info "${RootDisk}" | grep "Volume Total Space" | awk '{print $4;}' `
  fi
  # 10.14 APFS
  if [[ ${TotalSpace} == "" ]]; then
  	TotalSpace=`diskutil info "${RootDisk}" | grep "Container Total Space" | awk '{print $4;}' `
  fi

  # All exclude 10.12
  FreeSpace=`diskutil info "${RootDisk}" | grep "Volume Free Space" | awk '{print $4;}' `
  # 10.12
  if [[ ${FreeSpace} == "" ]]; then
  FreeSpace=`diskutil info "${RootDisk}" | grep "Volume Available Space" | awk '{print $4;}' `
  fi
  # 10.14 APFS
  if [[ ${FreeSpace} == "" ]]; then
  FreeSpace=`diskutil info "${RootDisk}" | grep "Container Free Space" | awk '{print $4;}' `
  fi

  printf "  開機系統分區 \e[1;34m${RootDisk}\e[0m 分區 可用/全部 容量大小: \e[1;34m${FreeSpace}/${TotalSpace}\e[0m GB\n"
  printf "  System space \e[1;34m${RootDisk}\e[0m Volume Free/Total Space: \e[1;34m${FreeSpace}/${TotalSpace}\e[0m GB\n"  
  echo 
  # if [[ ${FreeSpace} < "30.0" ]]; then
  #  printf "  開機系統分區 \e[1;34m${RootDisk}\e[0m 分區 可用容量大小: 至少 \e[1;31m30.0\e[0m GB .......... 可用容量小於 30 GB         .. \e[1;31m建議停止下載\e[0m\n"
  #  printf "  System space \e[1;34m${RootDisk}\e[0m Volume Free Space: need \e[1;31m30.0\e[0m GB .......... Free space less than 30 GB .. \e[1;31msuggest to stop downloading.\e[0m\n"
  #  echo
  #fi
}
function downloadfullappbigsur()
{
  updatever="${macOSUpdver[$downloadver]}"
  version="${macOSUpdversion[$downloadver]}"
  key="${macOSUpdkey[$downloadver]}"
  salt="${macOSUpdsalt[$downloadver]}"
  echo "                                               [ $downloadver ] ${macOSupdate[$downloadver]}"

  distribution=`cat ${catalogfile} | grep ${macOSUpdkey[$downloadver]} | grep English.dist | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `

  targetFiles[0]=`cat ${catalogfile} | grep "${version}" | grep "${key}" | grep "${salt}" | grep -v integrityData | grep InstallAssistant.pkg | sed 's/<string>//g' | sed 's/<\/string>//g' | sed 's/\// /g' | awk '{print $9;}' | awk NR==1 `

  rm -f ${catalogfile}
  cd

  #
  # Initialisation of a variable (our target folder).
  #
  tmpDirectory="/private/tmp"

  #
  # URL copied from sucatalog.gz (think CatalogURL).
  #
  url="https://swdist.apple.com/content/downloads/${version}/${key}/${salt}/"

  #
  # Target distribution language.
  #
  keydistribution=`echo ${key} | sed 's/.\{9\}/& /g' | awk '{print $1;}' `

  #
  # Check target directory.
  #
  if [[ -d "${tmpDirectory}/${key}" ]]; then
    rm -rf "${tmpDirectory}/${key}"
    mkdir "${tmpDirectory}/${key}"
  fi
  if [[ ! -d "${tmpDirectory}/${key}" ]]; then
    mkdir "${tmpDirectory}/${key}"
  fi
  open "${tmpDirectory}/${key}"

  echo 
  echo "準備進行下載。Prepare to download the files.   [ $downloadver ] ${macOSupdate[$downloadver]}."
  echo 
  echo "${url}${distribution}"
  for filename in "${targetFiles[@]}"
  do
    if [[ ! $filename == "" ]]; then
      echo "${url}$filename"
    fi
  done
  echo

  printred "如果你已經發生下載錯誤，可以 預先手動下載 上列網址文件，並將文件放入 以下 正確的文件夾 即可繼續進行。\n"
  printred "If get errors of downloading before, you can download files as above URL manually and put into correct folder as below before continuing.\n"
  echo

  echo "${tmpDirectory}/${key}/${distribution}"
  for filename in "${targetFiles[@]}"
  do
    if [[ ! $filename == "" ]]; then
      echo "${tmpDirectory}/${key}/$filename"
    fi
  done
  echo
  
  checkspace

  read -p "手動下載放入上列文件，或由腳本自動下載文件，繼續進行？   Put files as above manually or download files automatically, continue? (y/n) " downloadyesno
  case "$downloadyesno" in
    y|Y)
      echo
    ;;
    *)
      echo
      echo "停止進行下載！！！               Stop downloading!!!"
      echo
      exit 0
    ;;
  esac

  #
  # Download distribution file.
  #
  if [[ ! -e "${tmpDirectory}/${key}/${distribution}" ]]; then
    echo "Downloading: ${distribution} ..."
    curl "${url}${distribution}" -o "${tmpDirectory}/${key}/${distribution}"
    #
    # Remove root only restriction/allow us to install on any target volume.
    #
    cat "${tmpDirectory}/${key}/${distribution}" | sed -e 's|rootVolumeOnly="true"|allow-external-scripts="true"|' > "${tmpDirectory}/${key}/new.dist"

    if [[ -e "${tmpDirectory}/${key}/new.dist" ]]; then
      mv "${tmpDirectory}/${key}/new.dist" "${tmpDirectory}/${key}/${distribution}"
    fi
  else
    echo "File: ${distribution} already there, skipping this download."
  fi

  #
  # Change to working directory (otherwise it will fail to locate the packages).
  #
  cd "${tmpDirectory}/${key}"

  #
  # Download target files.
  #
  for filename in "${targetFiles[@]}"
  do
    if [[ ! $filename == "" ]]; then
      if [[ ! -e "${tmpDirectory}/${key}/${filename}" ]]; then
        echo "Downloading: ${filename} ..."
        curl "${url}${filename}" -o "${tmpDirectory}/${key}/${filename}"
      else
        echo "File: ${filename} already there, skipping this download."
      fi
    fi
  done

  rm -rf "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}"
  mkdir -p "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}"
  echo

  mkdir -p "$HOME/Desktop/FullInstallerAppBackup"
  sudo mv /Applications/Install* "$HOME/Desktop/FullInstallerAppBackup" 2>/dev/null

  sudo /usr/sbin/installer -pkg "${tmpDirectory}/${key}/InstallAssistant.pkg" -target "/"
  sudo mv /Applications/Install* "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"

  sudo mv ~/Desktop/FullInstallerAppBackup/Install* /Applications/ 2>/dev/null
  rm -rf "$HOME/Desktop/FullInstallerAppBackup"

  echo
  echo "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  ls -la "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  echo
  open "$HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"

  echo
  echo "完整安裝app 存放在 $HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  echo "The full installer app is located on $HOME/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
  echo
  printf "\e[1;34mMake sure you get the full installer without any errors during the downloading process.\e[0m\n"
  printf "\e[1;34m1.check the received sizes of each file, make sure they’re all 100 downloaded.\e[0m\n"
  printf "\e[1;34m2.if any one of the files \e[0m\e[1;31mgets error\e[0m\e[1;34m during the downloading process,\e[0m\n"
  printf "\e[1;34m  and\e[0m \e[1;31mdidn’t get 100 downloaded,\e[0m\e[1;34m you\e[0m \e[1;31mneed to re-download the full installer app again.\e[0m\n"
  echo
  if [[ -d "${tmpDirectory}/${key}" ]]; then
    rm -rf "${tmpDirectory}/${key}"
  fi
}
function main()
{
  updatescript
  headline
  catalogselect
  fullapparray
  fullapplist
  selectfullappversion
  macOSver=`echo ${macOSupdateosver[$downloadver]} | sed 's/.\{5\}/& /g' | awk '{print $1;}' `
  if [[ ${macOSver} < 10.16 ]]; then
    downloadfullapp
  elif [[ ${macOSver} > 10.15 ]]; then
    downloadfullappbigsur
  fi  
}

main

exit 0