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

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

########################################################################################################################
# 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)                                             #
########################################################################################################################

#
# 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)
#
# Updates:
#
#       - Creates a seedEnrollement.plist when missing.
#       - Volume picker for seedEnrollement.plist added.
#       - Added sudo to 'open installer.pkg' to remedy authorisation problems.
#       - Fix for volume names with a space in it. Thanks to:
#       - https://pikeralpha.wordpress.com/2017/06/22/script-to-upgrade-macos-high-sierra-dp1-to-dp2/#comment-10216)
#       - Add file checks so that we only download the missing files.
#       - Polished up comments.
#       - Changed key, salt, target files and version (now v1.5).
#       - Now calling the installer.app with -pkg -target instead of open to prevent failures.
#       - Fixed path to distribution file.
#       - Checks for missing files added.
#       - Updated version number (now v1.6).
#       - Removing unused (initialisation of a) variable.
#       - Improved verbose output.
#       - Updated version number (now v1.7).
#       - Fix installer breakage.
#       - Updated version number (now v1.8).
#       - Opt out for firmware added.
#       - Changed version number (now v1.9).
#       - Opt in/out for APFS conversion added.
#       - Changed version number (now v2.0).
#       - Variables 'version' and 'salt' added.
#       - Checks for newly added variables added.
#       - Changed version number (now v2.1).
#

# CatalogURL for Developer Program Members
# https://swscan.apple.com/content/catalogs/others/index-10.13seed-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz
#
# CatalogURL for Beta Program Members
# https://swscan.apple.com/content/catalogs/others/index-10.13beta-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz
#
# CatalogURL for Regular Software Updates
# https://swscan.apple.com/content/catalogs/others/index-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz
#
#  CatalogURL for Customer Seed Updates
# https://swscan.apple.com/content/catalogs/others/index-10.13customerseed-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz

#
# Tip: In case you run into the ERROR_7E7AEE96CA error then you need to change the ProductVersion and 
# in /System/Library/CoreServices/SystemVersion.plist to 10.13
#

#
# http://telegra.ph/Download-macOS-Mojave-Beta-2-wo-Accessing-Mac-App-Store-06-24
#

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"
}

echo 
printf "从 swscan.apple.com 下载完整安装app.    Download the full installer app from swscan.apple.com.\n"
echo 

# CatalogURL for Regular Software Updates
CatalogURLRegular="https://swscan.apple.com/content/catalogs/others/index-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.14beta-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.14seed-10.14-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz"

echo
echo "1.选用 正式版 下载渠道。"
echo "1.Use CatalogURL for Regular Software Updates"
echo "  ${CatalogURLRegular}"
echo
echo "2.选用 公開测试版 下载渠道。"
echo "2.Use CatalogURL for Public Beta Program Members"
echo "  ${CatalogURLPublic}"
echo
echo "3.选用 开发者测试版 下载渠道。"
echo "3.Use CatalogURL for Developer Beta Program Members"
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 "正在搜寻更新，请耐心等候！ Searching for updates from catalogs of swscan.apple.com. Be patient!"
echo 

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

found404=`cat update-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 update-catalogs.gz

macOSdmg[0]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==1 `
macOSdmg[1]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==2 `
macOSdmg[2]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==3 `
macOSdmg[3]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==4 `
macOSdmg[4]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==5 `
macOSdmg[5]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==6 `
macOSdmg[6]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==7 `
macOSdmg[7]=`cat /tmp/update-catalogs | grep BaseSystem.dmg | grep -v integrityData | sed 's/<string>//' | sed 's/<\/string>//' | awk '{print $1;}' | awk NR==8 `

index=0
for macOSdmglist in "${macOSdmg[@]}"
do
  if [ ! $macOSdmglist == "" ]; then

    macOSUpdver[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $9;}' | sed 's/macOSUpd//' | sed 's/.pkg//' `

    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;}' `
    macOSUpdsalt[$index]=`echo $macOSdmglist | sed 's/\// /g' | awk '{print $8;}' `

    url="https://swdist.apple.com/content/downloads/${macOSUpdversion[$index]}/${macOSUpdkey[$index]}/${macOSUpdsalt[$index]}/"
    distribution="${macOSUpdkey[$index]}.English.dist"
    rm -f *dist
    curl $url$distribution -o ${macOSUpdkey[$index]}.English.dist 2>/dev/null
    macOSupdateosver[$index]=`cat ${macOSUpdkey[$index]}.English.dist  | grep OSInstall.mpkg | grep version  | awk '{print $4;}' | sed 's/version=\"//' | sed 's/"\/>//' | sed 's/.\{7\}/& /g' | awk '{print $1;}' `
    macOSupdatebeta[$index]=`cat ${macOSUpdkey[$index]}.English.dist  | grep SU_TITLE | grep strings | grep macOS | sed 's/<strings language="English">"SU_TITLE" = "//' | sed 's/";//' | sed 's/Install//' | sed 's/  //' | sed 's/  //' | sed 's/  //' | sed 's/  //' `

    rm -f *dist

    OSInstallmpkg="OSInstall.mpkg"
    rm -rf OSInstallmpkgTemp
    curl $url$OSInstallmpkg -o $OSInstallmpkg 2>/dev/null
    mkdir OSInstallmpkgTemp
    cd OSInstallmpkgTemp
    xar -xf ../$OSInstallmpkg
    macOSupdatebuildver[$index]=`cat Distribution  | grep osBuildVersion | sed 's/<options//' | sed 's/\/>//' | sed 's/allow-external-scripts="yes"//' | sed 's/hostArchitectures="x86_64"//' | sed 's/installsOS="true"//' | sed 's/osBuildVersion="//'  | sed 's/"//' | awk '{print $1;}' `
    cd ..
    rm -f $OSInstallmpkg
    rm -rf OSInstallmpkgTemp

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

    BaseSystem[$index]=`cat /tmp/update-catalogs | grep "${macOSUpdversion[$index]}" | grep "${macOSUpdkey[$index]}" | grep "${macOSUpdsalt[$index]}" | grep BaseSystem.dmg | grep -v integrityData | sed 's/.dmg//' | sed 's/<string>//' | sed 's/<\/string>//' | sed 's/\// /g' | awk '{print $9;}' `
#    macOSuptime[$index]=`cat /tmp/update-catalogs | grep -B 7 $url${macOSUpdkey[$index]}.hi.dist | grep \<date\>  | sed 's/<date>//' | sed 's/<\/date>//' | awk '{print $1;}' | sed 's/T/ /' | sed 's/Z//' `
    macOSuptime[$index]=`cat /tmp/update-catalogs | grep -A 5 PostDate | grep -B 7 $url${macOSUpdkey[$index]} | grep \<date\>  | sed 's/<date>//' | sed 's/<\/date>//' | awk '{print $1;}' | sed 's/T/ /' | sed 's/Z//' `
    macOSupdate[$index]="${macOSuptime[$index]} .. ${macOSUpdkey[$index]} .. ${macOSupdatebuildver[$index]} ${macOSupdatebeta[$index]}"

    macOSlist[$index]=`echo ${macOSdmglist} `

    #echo "${macOSlist[$index]}"
    #cat /tmp/update-catalogs | grep "${macOSUpdversion[$index]}" | grep "${macOSUpdkey[$index]}" | grep "${macOSUpdsalt[$index]}" | grep English | sed 's/<string>//' | sed 's/<\/string>//' | sed 's/\// /g' | awk '{print $9;}'
    #cat /tmp/update-catalogs | grep "${macOSUpdversion[$index]}" | grep "${macOSUpdkey[$index]}" | grep "${macOSUpdsalt[$index]}" | grep -v .dist | sed 's/<string>//' | sed 's/<\/string>//' | sed 's/\// /g' | awk '{print $9;}'
    #echo

    let index++
  fi
done

index=0
for list in "${macOSupdate[@]}"
do
  echo "${macOSlist[$index]}"
  #cat /tmp/update-catalogs | grep "${macOSUpdversion[$index]}" | grep "${macOSUpdkey[$index]}" | grep "${macOSUpdsalt[$index]}" | grep English | sed 's/<string>//' | sed 's/<\/string>//' | sed 's/\// /g' | awk '{print $9;}'
  #cat /tmp/update-catalogs | grep "${macOSUpdversion[$index]}" | grep "${macOSUpdkey[$index]}" | grep "${macOSUpdsalt[$index]}" | grep -v .dist | sed 's/<string>//' | sed 's/<\/string>//' | sed 's/\// /g' | awk '{print $9;}'
  #echo
  let index++
done

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 update-catalogs
  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 update-catalogs
  exit 0
fi

updatever="${macOSUpdver[$downloadver]}"
version="${macOSUpdversion[$downloadver]}"
key="${macOSUpdkey[$downloadver]}"
salt="${macOSUpdsalt[$downloadver]}"
echo "                                               [ $downloadver ] ${macOSupdate[$downloadver]}"

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

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

rm -f update-catalogs
cd

#
# You may need VolumeCheck() to return true (and thus skip checks)
#
export __OS_INSTALL=1

#
# Skip firmware update (OSInstaller).
#
export __FIRMWARE_UPDATE_OPTOUT

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

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

#
# Target distribution language.
#
distribution="${key}.English.dist"

#
# Target files copied from sucatalog.gz (think CatalogURL).
#
#targetFiles=(
#BridgeOSBrain.pkg
#EmbeddedOSFirmware.pkg
#FirmwareUpdate.pkg
#BridgeOSUpdateCustomer.pkg
#FullBundleUpdate.pkg
#macOSUpd10.13.3.pkg
#macOSUpd10.13.3.RecoveryHDUpdate.pkg
#091-57567.English.dist
#)

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

echo 
echo "即将下载的档案。The files to download. [ $downloadver ] ${macOSupdate[$downloadver]}."
echo 
echo "${distribution}"
for filename in "${targetFiles[@]}"
do
  if [ ! $filename == "" ]; then
    echo "$filename"
  fi
done
echo

read -p "选择要下载的版本正确？   The version is selected, is it right？(y/n) " versionyesno
  case "$versionyesno" in
    y|Y)
      echo
    ;;
    *)
      echo
      echo "发生错误！！！               Error!!!"
      echo
      echo "选择要下载的版本不正确。 The selected version is not right."
      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

echo
username=`whoami`
pkgutil --expand-full InstallAssistantAuto.pkg Installapp

fullappnames=(
"Install macOS 10.13 Beta.app"
"Install macOS 10.14 Beta.app"
"Install macOS High Sierra.app"
"Install macOS High Sierra Beta.app"
"Install macOS Mojave.app"
"Install macOS Mojave Beta.app"
)

for appname in "${fullappnames[@]}"
do
    if [ ! $filename == "" ]; then
      if [ -e "${tmpDirectory}/${key}/Installapp/Payload/${appname}" ]; 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 "/Users/${username}/Desktop/App-${macOSupdatebuildver[$downloadver]}"
        mkdir -p "/Users/${username}/Desktop/App-${macOSupdatebuildver[$downloadver]}"
        mv "${tmpDirectory}/${key}/Installapp/Payload/${appname}" "/Users/${username}/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
        newappname="${appname}"
      fi
   fi
done

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

echo
echo "完整安装app 存放在 /Users/${username}/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
echo "The full installer app is located on /Users/${username}/Desktop/App-${macOSupdatebuildver[$downloadver]}/"
echo
exit 0