#!/bin/sh
echo $PATH
ACTION=${1}
shift 1

usage() {
  echo "usage: $0 sub-command"
  echo "where sub-command is one of:"
  echo "      install                Install the docker-backup"
}

do_install() {
  local backup=`uci get docker-backup.@docker-backup[0].backup 2>/dev/null`
  local restore=`uci get docker-backup.@docker-backup[0].restore 2>/dev/null`
  local restore_container=`uci get docker-backup.@docker-backup[0].restore_container 2>/dev/null`
  local backup_container=`uci get docker-backup.@docker-backup[0].backup_container 2>/dev/null`
  local config_path=`uci get docker-backup.@docker-backup[0].config_path 2>/dev/null`

  if [ "$backup" = "1" ]; then
      echo "backing up containers!"
       /usr/libexec/apps/docker-backup/docker-backup backup "$backup_container"
       mv *.backup.files /opt/docker2/compose/docker-backup
       mv *.backup.json /opt/docker2/compose/docker-backup
       mv *.tar /opt/docker2/compose/docker-backup
  fi

  if [ "$restore" = "1" ]; then
       echo "restoring containers!"
       result=`/usr/libexec/apps/docker-backup/docker-backup restore ${config_path}"$restore_container" 2>&1`
       if echo "$result" | grep -q "No such image"; then
           image_name=$(echo "$result" | sed -n 's/.*No such image: \(.*\)\s*/\1/p')
           echo "Pulling missing image: $image_name"
           /usr/bin/docker pull $image_name
           while ! /usr/bin/docker image inspect $image_name >/dev/null 2>&1; do
              echo "Waiting for image to download..."
              sleep 1
           done
       fi

       /usr/libexec/apps/docker-backup/docker-backup restore ${config_path}"$restore_container"
       if [ $? -eq 0 ]; then
           echo "Restore successful"
       else
           echo "Restore failed"
           exit 1
       fi
  fi
}

case ${ACTION} in
  "install")
    do_install
  ;;
  "upgrade")
    do_install
  ;;
  "rm")
    opkg remove luci-app-docker-backup
  ;;
  "start" | "stop" | "restart")
    do_install
  ;;
  "status")
    do_install
  ;;
  "port")
    do_install
  ;;
  *)
    usage
    exit 1
  ;;
esac
