#!/bin/sh
# It just swaps two files

export DAISY_INTERNAL=1
. $(dirname $(realpath $0))/daisy.source

FILE1=$1
FILE2=$2

function helpFn()
{
  ERROR=$?
  if [[ $ERROR -gt 0 ]];
  then
    ERROR_TEXT=$(perl -E 'say $!=shift' $ERROR)
    echo "$DAISY_BIN error ($ERROR): $ERROR_TEXT"
  fi
  echo "Usage: $DAISY_BIN <file1> <file2>"
  echo Swap two files in a filesystem.
  exit $ERROR
}

if [[ $@ == *"--help"*  ]];
then
  helpFn
elif [[ $@ == '' ]];
then
  echo "No arguments specified."
  helpFn
fi

# We set a trap here, together with 'set -e' above,
# this makes sure we exit gracefully if we have an
# error in one of the ls or mv calls.
trap helpFn ERR

# We want to swap two files
# Easy, but let's be safe about it
ls "$FILE1" >/dev/null
ls "$FILE2" >/dev/null

# Files should exist, now we move
mv "$FILE1" "$FILE1.sw"
mv "$FILE2" "$FILE2.sw"

# We got our moved copies, now we simply rename
mv "$FILE1.sw" "$FILE2"
mv "$FILE2.sw" "$FILE1"

