summaryrefslogtreecommitdiff
path: root/automv.sh
blob: fae371e07c054d7ca441ec8e81428cf10c0ebf07 (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
#!/usr/bin/env bash

if [[ -n "$AUTOMV_DIR" ]]; then
  automvdir=$AUTOMV_DIR
else
  if [[ -d "/usr/local/etc/automv.d" ]]; then
    automvdir=/usr/local/etc/automv.d
  else
    echo 'Missing automv.d location: please create confs in /usr/local/etc/automv.d
          or supply a directory in $AUTOMV_DIR'
    exit 1
  fi
fi

function extract {
  local file=$1
  local prop=$2
  grep "^${prop}=.*$" $file | cut -d '=' -f2
}

function fn_find {
  find $1 -type f \( -regex "${2}" ! -iname ".*" \)
}

function automv {
  local query=$1
  local source=$2
  local target=$3

  file_cnt=$(fn_find $source $query | wc -l)
  if [[ $file_cnt > 0 ]]; then
    echo "Moving $file_cnt files in $source that match '$query' to $target"
    fn_find $source $query
    fn_find $source $query | xargs -I '{}' mv {} $target/
  else
    echo "No files matching '$query' in $source"
  fi
}

echo "Executing automv functions from $automvdir"
for file in $automvdir/*.conf
do
  echo "found $file"
  if [[ -f $file ]]; then
    # Extract file configs
    query=$(extract $file "query")
    sourced=$(extract $file "source")
    target=$(extract $file "target")

    automv $query $sourced $target
  fi
done