#!/bin/bash

# this param can receive a 1 and will look for backups or can receive
# a path to save the backup for that path
BACKUP_TO_NORMAL_PEN=$1
MODE=$2

if [ -e "/opt/pos/.hardlock" ]; then
  TMP=`cat /opt/pos/.hardlock`
fi

if [ "$TMP" = "" ]; then
  echo "No /opt/pos/.hardlock found... maybe POS isn't running with an hardlock..."
  exit
fi

# if called from cron, sleeps some secs before backing up. usefull when
# using cloud backups.
if [ "$MODE" = "cron" ]; then
  MIN=10
  MAX=60
  RND=$(( $RANDOM % ($MAX + 1 - $MIN) + $MIN ))
  echo "$0> Will sleep $RND seconds..."
  sleep $RND
fi

function echoerr() { echo "$@" 1>&2; }

function do_backup {
  folder=$1
  network_backup=$2

  echo "backup to - $folder"

  files_to_keep=8

  "/opt/pos/common/bin/backup" "$folder" 0 1

  COUNT=0

  file_to_send_network=""

  find "$folder" -type f | grep "\.zip" | sort -n -r | while read -r file
  do
    COUNT=$(($COUNT+1))

    if [ $COUNT -gt $files_to_keep ]; then
      rm -rf "$file"
    else
      if [ "$file_to_send_network" = "" ] && [ "$file" != "" ]; then
        file_to_send_network="$file"
        echo -n $file > /tmp/.networkbackup.$$
      fi
    fi
  done

  if [ -e "/tmp/.networkbackup.$$" ]; then
    file_to_send_network=`cat /tmp/.networkbackup.$$ | xargs basename`
    rm -rf /tmp/.networkbackup.$$
  fi

  sync

  # send backup to network
  #echo "---- $network_backup - $folder"

  if [ "$network_backup" = "1" ]; then
    station=`cat /opt/pos/etc/config.ini | grep "STATION_NUMBER" | cut -f2 -d=`

    if [ "$station" = "0" ]; then
      has_cloud_backups=`cat /opt/pos/etc/config.ini | grep "INTERNET_BACKUP" | cut -f2 -d=`

      if [ "$has_cloud_backups" = "1" ]; then
        has_network=`timeout 5s /opt/pos/common/bin/has_network`

        if [ "$has_network" = "YES" ]; then

          # when using pen drive hardlocks, we allways use a local hdd backup
          # to send to the cloud... this allows us to send to the cloud allways
          # even if the the pen drive has problems
          if [ "$folder" != "/opt/backups" ] && [[ $folder == *"media"* ]]; then
            folder="/opt/backups"
            do_backup "/opt/backups" 1
          fi

          if [ -d "$folder" ]; then
            hardlock=`/opt/pos/common/bin/machine_id`
            find $folder -type f | sort -k 2 | tr '\n' ',' > /tmp/$$.txt
            files_to_get=`curl --progress-bar --connect-timeout 5 -F "files=@/tmp/$$.txt" -F "hardlock=$hardlock" http://www.ptcert.com/hardlock_backup`
            rm -f /tmp/$$.txt

            if [ "$files_to_get" != "" ]; then
              for file in $(echo $files_to_get | sed "s/,/ /g"); do
                if [ "$file" = "$file_to_send_network" ] || [[ $file = *"dump"* ]]; then
                  echoerr "Will upload - $file"
                  curl --progress-bar --connect-timeout 5 -F "files_to_keep=$files_to_keep" -F "file=@$folder/$file" -F "file_upload=$file" -F "hardlock=$hardlock" http://www.ptcert.com/hardlock_backup

                  if [ "$?" = "0" ]; then
                    echoerr "  success..."
                  else
                    echoerr "  error..."
                  fi
                fi

                #echo "### $?"
              done
            fi
          fi
        fi
      fi
    fi
  fi
}

MACHINE_ID2=`/opt/pos/common/bin/machine_id 2`

# we've passed a path to this param, lets try to backup to hdd
if [ "$BACKUP_TO_NORMAL_PEN" != "" ] && [ "$BACKUP_TO_NORMAL_PEN" != "1" ]; then
  do_backup "$BACKUP_TO_NORMAL_PEN" 1
  exit
fi

# we passed 1 to this param, lets find a pen
if [ "$BACKUP_TO_NORMAL_PEN" != "" ]; then
  if [ ! -e "/opt/pos/.hardlock" ]; then
    echo "Machine is in demo... aborting..."
    exit
  fi

  did_normal=0
  station=`cat /opt/pos/etc/config.ini | grep "STATION_NUMBER" | cut -f2 -d=`
  demo_or_local_lic=`/opt/pos/common/bin/machine_id | grep MAC`

  for pen in `ls /media`; do
    is_mounted=`mount | grep $pen | grep vfat`

    if [ "$is_mounted" != "" ]; then
      did_normal=1

      # demo or local lics will go to normal backups folder
      if [ "$demo_or_local_lic" != "" ]; then
        tmp_dir="/media/$pen/pos/backups/auto/$station"
      # normal lics will go to hardlock backups folder
      else
        tmp_dir="/media/$pen/pos/data/backups"
      fi

      if [ ! -d "$tmp_dir" ]; then
        mkdir -p "$tmp_dir"
      fi

      do_backup "$tmp_dir"
    fi
  done

  if [ $did_normal -eq 0 ]; then
    echo "Didn't find a pen to put backup in..."
  fi

  exit
fi

# since new hardlocks are hardware based, need to look for a normal pen
# to backup to
if [ -e "/opt/pos/hardlock2" ] && [ "$MACHINE_ID2" != "" ]; then

  found=0

  # find the first pen with the backups folder on it
  for pen in `mount | grep "/media" | awk '{ print $3 }'`; do
    echo 1 > $pen/.check.$$

    if [ $? -eq 0 ]; then
      rm -f $pen/.check.$$

      if [ -d "$pen/backups" ]; then
        found=1

        do_backup "$pen/backups" 1
        echo "OK"
        break
      fi
    fi
  done

  if [ $found -eq 0 ]; then
    for pen in `mount | grep "/media" | awk '{ print $3 }'`; do
      echo 1 > $pen/.check.$$

      if [ $? -eq 0 ]; then
        rm -f $pen/.check.$$

        if [ ! -d "$pen/backups" ]; then
          mkdir $pen/backups
        fi

        found=1

        do_backup "$pen/backups" 1
        echo "OK"
        break
      fi
    done

    if [ $found -eq 0 ]; then
      do_backup "/opt/backups" 1
      echo "OK"
    fi
  fi

  exit
fi

BACKUP_FOLDER=""
TMP=""

if [ -e "/opt/pos/.hardlock" ]; then
  TMP=`cat /opt/pos/.hardlock`
fi

if [ "$TMP" = "" ]; then
  echo "No /opt/pos/.hardlock found... maybe POS isn't running with an hardlock..."
  exit
else
  FF=`dirname $TMP`
  BACKUP_FOLDER="$FF/data/backups"
fi

if [ "$BACKUP_FOLDER" = "" ]; then
  echo "Can't find backup folder to put backups in... check why /opt/pos/.hardlock isn't created..."
  exit
fi

HRD_FOLDER=`echo $TMP | cut -f3 -d/`

# hardlock is in the hdd and not in the pen
if [ "$TMP" = "/opt/pos/hardlock" ]; then
  BACKUP_FOLDER="/opt/backups"
else
  if [ ! -d "/media/$HRD_FOLDER/pos" ]; then
    echo "Hardlock should be in /media/$HRD_FOLDER but isn't... aborting..."
    exit
  fi
fi

if [ ! -d "$BACKUP_FOLDER" ]; then
  mkdir -p "$BACKUP_FOLDER"
fi

if [ -e "/tmp/server_error.txt" ]; then
  echo "Can't backup to hardlock, /tmp/server_error.txt exists..."
  exit
fi

if [ -e "/tmp/server_db_error.txt" ]; then
  echo "Can't backup to hardlock, /tmp/server_db_error.txt exists..."
  exit
fi

do_backup $BACKUP_FOLDER 1

echo "OK"

