shell

ネットワークに応じて処理を振り分けるスクリプト

#!/bin/zsh
 
# ネットワーク環境を切り替える
switchNetwork() {
  local location=$1
  currentLocation=$(networksetup -getcurrentlocation)
  if test $currentLocation = $location; then
    return
  fi
 
  scselect $(scselect | grep $location | awk '{ print $1 }')
  osascript -e 'display notification "'"Switch network location to ${1}"'" with title "'"${0##*/}"'" '
}
 
# Git リポジトリ設定を切り替える
switchGitConfig() {
  local location=$1
 
  case "$location" in
    Home)
      git config --global --replace-all http.$GIT_REPO_URL_HTTPS.proxy $PROXY_URL
      git config --global --replace-all url.$GIT_REPO_URL_HTTPS.insteadOf $GIT_REPO_URL_SSH
      git config --global --replace-all url.$GIT_REPO_URL_HTTPS.insteadOf ssh://$GIT_REPO_URL_SSH --add
      ;;
    Office)
      git config --global --unset-all http.$GIT_REPO_URL_HTTPS.proxy
      git config --global --unset-all url.$GIT_REPO_URL_HTTPS.insteadOf
      ;;
  esac
}
 
main() {
  set -x
  ADAPTER=en0
 
  # Wi-FiがONになっているか
  airportpower=$(networksetup -getairportpower $ADAPTER | awk -F': ' '{ print $2 }')
  if test ${airportpower} = 'Off'; then
    echo 'Wifi is Off.'
    exit
  fi
 
  # SSIDを取得
  ssid=$(networksetup -getairportnetwork $ADAPTER | awk -F': ' '{ print $2 }')
 
  location=Automatic
  case "$ssid" in
    $SSID_HOME)
      location=Home
      ;;
    $SSID_OFFICE)
      location=Office
      ;;
  esac
 
  switchNetwork $location
  switchGitConfig $location
  set +x
}
 
main