about summary refs log tree commit diff
path: root/home/profiles/base/scripts/airport.nix
blob: 996d8969a29ac0b347b0c6bbea465c514bf8e24d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
''
  # airport.sh - shared file store
  #
  # # Environment variables
  # `AIRPORT_HOST`   - host to rsync to
  # `AIRPORT_USER`   - username to connect with
  # `AIRPORT_DIR`    - defaults to `~/airport`, directory to use
  # `AIRPORT_SAFEOP` - 'safe operations' mode, which doesn't delete files

  set -euo pipefail

  die () {
      echo >&2 "$@"
      exit 1
  }

  confirm() {
      read -r -p "''${1:-Proceed?} [y/N] " response
      case "$response" in
          [yY][eE][sS]|[yY])
              true
              ;;
          *)
              false
              ;;
      esac
  }

  delay() {
      DELAY_SECONDS=''${2:-5}
      echo "''${1:-This script will perform some potentionally destructive actions.}"
      echo "Waiting $DELAY_SECONDS second(s) before proceeding..."
      sleep $DELAY_SECONDS
  }

  bin_exists() {
      [ -z $1 ] && die "FATAL: called bin_exists() without arguments (expected 1)"
      if command -v $1 &> /dev/null
      then
          true
      else
          false
      fi
  }

  [ -f $HOME/.airport-env ] && source $HOME/.airport-env

  HOST=''${AIRPORT_HOST:?"AIRPORT_HOST needs to be set"}
  USER=''${AIRPORT_USER:?"AIRPORT_USER needs to be set"}
  DIR=''${AIRPORT_DIR:-"$HOME/airport"}
  SAFEOP=''${AIRPORT_SAFEOP:-1}

  [ "$#" -eq 0 ] && die "FATAL: expected exactly 1 argument, $# provided"

  if [ ! -d $DIR ]
  then
      confirm "$DIR doesn't exist, create and proceed?" || die "FATAL: $DIR doesn't exist"
      mkdir -p $DIR
  fi

  bin_exists "rsync" || die "FATAL: couldn't find rsync"

  opts=(-au --stats --info=progress2)
  [ $SAFEOP -eq 1 ] && opts+=(--delete-after)
  case "$1" in
      send)
          delay "Airport will run 'rsync -au' to $DIR to SEND"
          rsync ''${opts[@]} --mkpath $DIR/ $USER@$HOST:airport
      ;;

      recv)
          delay "Airport will run 'rsync -au' to $DIR to RECV"
          rsync ''${opts[@]} $USER@$HOST:airport/ $DIR
      ;;

      configure)
          delay "Will write configuration to $HOME/.airport-env"
          cat >$HOME/.airport-env <<EOF
AIRPORT_USER=$USER
AIRPORT_HOST=$HOST
AIRPORT_DIR=$DIR
EOF
      ;;

      *) printf "Unknown subcommand $1, supported subcommands:\n"
          printf '\tsend\n'
          printf '\trecv\n'
          printf '\tconfigure'
          die
      ;;
  esac

  exit 0
''