#!/bin/bash # SANU engineer workstation bootstrap, stage 1. # # bash -c "$(curl -fsSL https://setup.sanu-dev.com)" # # Options (with the curl form, pass them after a "--" placeholder for $0): # --config-only Ask the questions and write the config, then stop before # installing packages, apps, tools and repos. # # bash -c "$(curl -fsSL https://setup.sanu-dev.com)" -- --config-only # # This file is published at setup.sanu-dev.com, so it must hold nothing about the # company beyond the GitHub org and the MDM enrollment page (which needs company # credentials anyway). It installs Homebrew, enrolls the Mac in MDM, installs # Chrome (unless MDM manages it), mise, gum and gh, signs in to GitHub, sets up the SSH key and clones the private sa-nu/eng-bootstrap # repo to ~/src/eng-bootstrap. It then hands over to that repo's setup.sh, which # holds everything else (account IDs, URLs, modules) and can be re-run on its own. # # Written for the stock macOS bash 3.2. set -euo pipefail GITHUB_ORG="sa-nu" BOOTSTRAP_REPO="$HOME/src/eng-bootstrap" LOG_FILE="$HOME/Library/Logs/sanu-bootstrap.log" BREW_PREFIX="/opt/homebrew" SSH_KEY="$HOME/.ssh/id_ed25519" # Scopes beyond gh's defaults, needed to upload the SSH and signing keys. GH_SCOPES="admin:public_key,admin:ssh_signing_key" # Here rather than only in setup.sh: Chrome depends on enrollment, and Chrome has # to come before the GitHub sign-in so that it opens in Chrome. Same as setup.sh. MDM_ENROLL_URL="https://sanu.jamfcloud.com/enroll" CONFIG_ONLY=false for arg in "$@"; do case "$arg" in --config-only) CONFIG_ONLY=true ;; -h | --help) sed -n '2,/^set -euo/{/^set -euo/d;s/^# \{0,1\}//;p;}' "$0" 2>/dev/null \ || echo "使い方: install.sh [--config-only]" exit 0 ;; *) echo "不明なオプションです: ${arg}(--help を参照)" >&2 exit 2 ;; esac done # --------------------------------------------------------------------------- # Output and logging (setup.sh has the same helpers) # --------------------------------------------------------------------------- # Brand accent #FA4616. Terminals without 24-bit color get the closest 256-color value. case "${COLORTERM:-}" in truecolor | 24bit) BRAND=$'\033[38;2;250;70;22m' ;; *) BRAND=$'\033[38;5;202m' ;; esac RESET=$'\033[0m' mkdir -p "$(dirname "$LOG_FILE")" log() { printf '%s %s\n' "$(date '+%H:%M:%S')" "$*" >>"$LOG_FILE"; } say() { printf '\n%s==>%s \033[1m%s%s\n' "$BRAND" "$RESET" "$*" "$RESET" log "==> $*" } warn() { printf '\033[1;33m注意:\033[0m %s\n' "$*" >&2 log "warning: $*" } die() { printf '\033[1;31mエラー:\033[0m %s\n' "$*" >&2 log "error: $*" echo "ログ: $LOG_FILE" >&2 exit 1 } # Run a non-interactive command, showing its output and appending it to the log. run_logged() { local status=0 log "\$ $*" "$@" 2>&1 | tee -a "$LOG_FILE" || status=$? return "$status" } # `bash -c "$(curl ...)"` keeps the terminal on stdin; `curl | bash` does not. if [ ! -t 0 ] && (exec /dev/null; then exec &2 exit 1 fi splash() { printf '%s' "$BRAND" cat <<'LOGO' ▟▀▜ ▗▟███▙ ▗██▙ ▗▟█▄ ▐██ ███ ▟██ ▀▘▀ ▟█ ▝▀▘ ▗████▖ ▐███▙ ▐██ ███ ███ ▗▄▄▄▄▄▄▄▖ ▐██▙ ▟█ ▜██ ▐█▛███▖ ▐██ ███ ███ ▄ ▀███▙▄ ▟█▘ ▝██▙ ▐█▌ ▜██▖ ▐█▌ ███ ███ ▟▜▙ ▀▜███▖ ▗█▌ ▐██▌ ▐█▌ ▜██▙▐█▌ ███ ███ ▗▌ █▌ ▝▜██ ▗█▛ ▜██▖ ▐█▌ ▝████▌ ███ ███ ▗▛ ▝█▖ ▗█▙▄▖ ▗█▘ ▟█▘ ▝██▙ ▐█▌ ▝███▌ ▜██▄ ▄███ ▟▘ ▜█ ▀▜████▀ ▟█▘ ▐██▌ ▐█▌ ▜█▌ ▀▜███▛▘▜██ LOGO printf '%s\n \033[1m%s%s\n' "$RESET" "SANUテックチームへようこそ!" "$RESET" printf ' %s\n' "ワークステーションの初期設定を行います" if $CONFIG_ONLY; then printf ' %s\n' "設定のみモード: 設定ファイルを書き出して終了します。"; fi } # --------------------------------------------------------------------------- # Steps # --------------------------------------------------------------------------- # One password prompt for the whole run. setup.sh stops the loop (and drops the # cached sudo) once the Homebrew installs are done, before any repo code runs. keep_sudo_alive() { say "パスワードを入力してください(Homebrew とアプリのインストールに一度だけ必要です)" sudo -v # `|| true`: the loop inherits set -e, and a single failed refresh would end it. while true; do sudo -n true || true; sleep 50; kill -0 "$$" || exit; done 2>/dev/null & export SANU_SUDO_KEEPALIVE_PID=$! } install_homebrew() { say "Homebrew をインストールしています" if [ -x "$BREW_PREFIX/bin/brew" ]; then echo "インストール済みです。" else # Also installs the Xcode Command Line Tools. The installer drops the cached # sudo on exit (`sudo -k`) unless `sudo -n -v` succeeds when it starts, so # refresh it first; that keeps the one password prompt for the whole run. sudo -n -v 2>/dev/null || true NONINTERACTIVE=1 run_logged /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" fi eval "$("$BREW_PREFIX/bin/brew" shellenv)" } mdm_enrolled() { profiles status -type enrollment 2>/dev/null | grep -q "MDM enrollment: Yes"; } # Enrollment comes before Chrome, which depends on it. setup.sh checks again and # adds a follow-up step if the Mac is still not enrolled. enroll_mdm() { say "MDM の登録を確認しています" if mdm_enrolled; then echo "登録済みです。" return fi echo "この Mac は MDM に登録されていません。Safari で登録ページを開きます..." # Always Safari for enrollment, whatever the default browser is. open -a Safari "$MDM_ENROLL_URL" || true read -rp "システム設定 → プライバシーとセキュリティ → プロファイル でプロファイルを承認してから Enter を押してください(後で行う場合はそのまま Enter)。" _ # Tells setup.sh not to open the page again in this run. export SANU_MDM_ASKED=1 # The status can lag the approval by a few seconds, and Chrome relies on it. local _i for _i in 1 2 3 4 5; do if mdm_enrolled; then echo "登録できました。" return fi sleep 2 done warn "MDM にまだ登録されていません。このまま続行します。" } # Chrome goes in before the GitHub sign-in, so that page and the later ones open # in Chrome once it is the default browser. The MDM profile installs and manages # its own Chrome, which conflicts with Homebrew's, so Homebrew installs Chrome # only on a Mac that is not enrolled. setup.sh keeps Chrome in the Brewfile only # if Homebrew manages it. setup_chrome() { say "Google Chrome" if brew list --cask google-chrome >/dev/null 2>&1; then echo "Homebrew でインストール済みです。" return fi if mdm_enrolled; then echo "MDM のプロファイルが Chrome をインストール・管理するため、Homebrew ではインストールしません。" return fi # --adopt takes over a Chrome that was installed by hand instead of failing. if ! run_logged brew install --cask --adopt google-chrome; then warn "Chrome をインストールできませんでした。ページは現在の既定のブラウザで開きます。" return fi # Open by path: right after the install, Launch Services may not know the app # by name yet ("Unable to find application named 'Google Chrome'"). open "/Applications/Google Chrome.app" 2>/dev/null || open -a "Google Chrome" 2>/dev/null \ || warn "Chrome を開けませんでした。アプリケーションフォルダから開いてください。" echo "Chrome が開いたら:" echo " 1. 会社の Google アカウント(@sa-nu.com)で Chrome にログインしてください。" echo " ブックマークや拡張機能が同期され、社内の Google サービスにもすぐ入れます。" echo " 2. 既定のブラウザにするか尋ねられたら「既定に設定」を選んでください" echo " (またはシステム設定 → デスクトップと Dock → デフォルトの Web ブラウザ)。" read -rp "終わったら Enter を押してください。" _ } install_tools() { say "mise、gum、gh をインストールしています" run_logged brew install mise gum gh } github_login() { say "GitHub にサインインしています" local status if ! status="$(gh auth status 2>&1)"; then # Git uses the SSH key set up next; --skip-ssh-key stops gh making its own. gh auth login --web --git-protocol ssh --skip-ssh-key --scopes "$GH_SCOPES" else case "$status" in *admin:ssh_signing_key*) ;; *) echo "SSH 鍵を GitHub に登録するため、追加の権限が必要です。" gh auth refresh --hostname github.com --scopes "$GH_SCOPES" ;; esac fi gh config set --host github.com git_protocol ssh log "GitHub user: $(gh api user --jq .login 2>/dev/null || echo unknown)" } # One ed25519 key for git over SSH and for commit signing (setup.sh configures # signing). It must be on GitHub before the private repo can be cloned. setup_ssh_key() { say "GitHub 用の SSH 鍵を設定しています" local key="$SSH_KEY" pub title mkdir -p "$HOME/.ssh" chmod 700 "$HOME/.ssh" if [ ! -f "$key" ]; then echo "SSH 鍵を作成します。パスフレーズを決めてください(macOS のキーチェーンに保存されます)。" ssh-keygen -t ed25519 -C "$(gh api user --jq .login 2>/dev/null || id -un)@$(scutil --get ComputerName 2>/dev/null || hostname -s)" -f "$key" fi if [ ! -f "$key.pub" ]; then echo "秘密鍵から $key.pub を作り直します(聞かれたらパスフレーズを入力してください)。" if ! ssh-keygen -y -f "$key" >"$key.pub.tmp"; then rm -f "$key.pub.tmp" die "$key を読み込めませんでした。鍵を修正するか作り直してから、もう一度実行してください。" fi mv "$key.pub.tmp" "$key.pub" fi if ! grep -qx "Host github.com" "$HOME/.ssh/config" 2>/dev/null; then printf '\nHost github.com\n AddKeysToAgent yes\n UseKeychain yes\n IdentityFile ~/.ssh/id_ed25519\n' >>"$HOME/.ssh/config" chmod 600 "$HOME/.ssh/config" fi # Load the key into the agent (and its passphrase into the keychain) while we # can ask for the passphrase. Over SSH there is often no agent; that is not # fatal, because the check below can ask for the passphrase itself. ssh-add --apple-use-keychain "$key" || warn "ssh-agent に鍵を追加できませんでした(SSH 経由でログインしている場合など)。続行します。" # Trust GitHub's host keys as published by its API over HTTPS, instead of # accepting whatever answers on first connect. if ! ssh-keygen -F github.com >/dev/null 2>&1; then gh api meta --jq '.ssh_keys[]' 2>/dev/null | sed 's/^/github.com /' >>"$HOME/.ssh/known_hosts" \ || warn "GitHub の SSH ホスト鍵を取得できませんでした。" fi pub="$(cut -d' ' -f1,2 "$key.pub")" title="SANU $(scutil --get ComputerName 2>/dev/null || hostname -s)" if gh api user/keys --jq '.[].key' 2>/dev/null | grep -qxF "$pub"; then echo "SSH 鍵: GitHub に登録済みです。" else gh ssh-key add "$key.pub" --type authentication --title "$title" || warn "SSH 鍵を GitHub に登録できませんでした。" fi if gh api user/ssh_signing_keys --jq '.[].key' 2>/dev/null | grep -qxF "$pub"; then echo "署名鍵: GitHub に登録済みです。" else gh ssh-key add "$key.pub" --type signing --title "$title" || warn "署名鍵を GitHub に登録できませんでした。" fi # Test with this key explicitly, since an existing "Host github.com" entry may # point elsewhere. No BatchMode: when neither the agent nor the keychain has # the passphrase (e.g. over SSH, where the keychain is locked), ssh asks for it # on the terminal. ssh -T exits 1 even on success; GitHub's greeting tells. local greeting echo "SSH で GitHub への接続を確認しています(聞かれたら SSH 鍵のパスフレーズを入力してください)..." greeting="$(ssh -T -o IdentityFile="$key" -o IdentitiesOnly=yes -o AddKeysToAgent=yes -o UseKeychain=yes \ -o ConnectTimeout=15 git@github.com 2>&1 /dev/null || echo '?') に登録済みですが、この Mac から使えませんでした。 よくある原因: パスフレーズの入力ミス、または SSH 経由のログインでキーチェーンがロックされている。 詳しく調べるには: ssh -vT -i $key git@github.com" ;; *"timed out"* | *"Connection refused"* | *"Could not resolve"* | *"unreachable"*) die "GitHub に SSH(ポート 22)で接続できませんでした: $greeting このネットワークでポート 22 がブロックされている可能性があります。別のネットワークで試すか、 ~/.ssh/config の Host github.com に「Hostname ssh.github.com」と「Port 443」を追加してから、もう一度実行してください。" ;; *) die "SSH で GitHub に接続できませんでした: $greeting 'ssh -vT -i $key git@github.com' で原因を確認してから、もう一度実行してください。" ;; esac # The clones that follow use ~/.ssh/config, not the options above. # ssh -G prints the path as written in the config, usually with a "~". if ! ssh -G github.com 2>/dev/null | grep -qix -e "identityfile $key" -e "identityfile ~${key#"$HOME"}"; then warn "$HOME/.ssh/config の Host github.com が別の鍵を使う設定になっています。リポジトリの取得に失敗する場合は $key を使うように直してください。" fi } fetch_bootstrap_repo() { say "SANU のセットアップ定義を取得しています" mkdir -p "$(dirname "$BOOTSTRAP_REPO")" if [ ! -d "$BOOTSTRAP_REPO/.git" ]; then run_logged git clone "git@github.com:$GITHUB_ORG/eng-bootstrap.git" "$BOOTSTRAP_REPO" \ || die "$GITHUB_ORG/eng-bootstrap を取得できませんでした。GitHub の $GITHUB_ORG に参加しているか確認してください。" elif [ -z "$(git -C "$BOOTSTRAP_REPO" status --porcelain)" ]; then run_logged git -C "$BOOTSTRAP_REPO" pull --ff-only || warn "$BOOTSTRAP_REPO を更新できませんでした。現在の内容で続行します。" else warn "$BOOTSTRAP_REPO に未コミットの変更があります。現在の内容で続行します。" fi [ -f "$BOOTSTRAP_REPO/setup.sh" ] || die "$BOOTSTRAP_REPO/setup.sh がありません。リポジトリを最新にしてから、もう一度実行してください。" log "eng-bootstrap at $(git -C "$BOOTSTRAP_REPO" rev-parse --short HEAD)" } main() { { echo echo "=== SANU bootstrap $(date '+%Y-%m-%d %H:%M:%S') ===" echo "macOS $(sw_vers -productVersion), $(uname -m), user $(id -un), args: ${*:-none}" } >>"$LOG_FILE" splash # --config-only needs sudo only for the Homebrew installer. if ! $CONFIG_ONLY || [ ! -x "$BREW_PREFIX/bin/brew" ]; then keep_sudo_alive; fi install_homebrew enroll_mdm setup_chrome install_tools github_login setup_ssh_key fetch_bootstrap_repo # Same process (and $$), so the sudo loop above keeps running until setup.sh stops it. exec /bin/bash "$BOOTSTRAP_REPO/setup.sh" "$@" } main "$@"