#!/bin/sh

## DO NOT USE UNLESS INSTRUCTED BY REMOTE.IT SUPPORT ##
# Default package name
package='remoteit'
if [ -n "$R3_PACKAGE" ]; then
  package=$R3_PACKAGE
fi
echo "package: $package"

remoteit_config_dir="/etc/${package}"

if [ -n "$R3_CONFIG_DIR" ]; then
  remoteit_config_dir=$R3_CONFIG_DIR
fi

remoteit_version_dir='latest'
remoteit_version=''
if [ -n "$R3_VERSION" ] && [ "$R3_VERSION" != "latest" ]; then
  echo "Setting R3_VERSION=$R3_VERSION"
  remoteit_version_dir="v$R3_VERSION"
  remoteit_version="$R3_VERSION"
fi

repository_url="downloads.remote.it"
if [ -n "$REPO_URL" ]; then
  repository_url="$REPO_URL"
fi

regfile_exists='false'
regfile_licensekey=''
if [ -f $remoteit_config_dir/registration ]; then
  regfile_exists='true'
  regfile_licensekey=$(cat $remoteit_config_dir/registration)
fi

licensekey=
if [ -n "$LICENSE_KEY" ]; then
  licensekey=$LICENSE_KEY
fi
if [ -n "$R3_LICENSE_KEY" ]; then
  licensekey=$R3_LICENSE_KEY
fi
if [ -n "$R3_REGISTRATION_CODE" ]; then
  licensekey=$R3_REGISTRATION_CODE
fi
if [ -n "$R3_BULK_REGISTRATION_CODE" ]; then
  licensekey=$R3_BULK_REGISTRATION_CODE
fi

echo "licensekey: $licensekey"

# Root user detection
if [ $(id -u) -eq 0 ]; then
  sudo_cmd=''
else
  sudo_cmd='sudo -E'
fi

# Check for existing claim code in the config file
claimcode=""
if [ -f $remoteit_config_dir/config.json ]; then
  claimcode=$(grep -o '"claim": *"[^"]*"' $remoteit_config_dir/config.json)
fi

if [ ! "$claimcode" = "" ]; then
  echo "There is already a claim code so skipping license key registration"
elif [ "$regfile_exists" = "true" ]; then
  echo "There is already a registration file so skipping license key registration"
elif [ ! -z "$licensekey" ]; then
  echo "Creating $remoteit_config_dir/registration file"
  $sudo_cmd mkdir -p ${remoteit_config_dir}
  $sudo_cmd sh -c "echo $licensekey > $remoteit_config_dir/registration"
else
  echo "No R3_LICENSE_KEY or R3_REGISTRATION_CODE variable set for new install so look for CLAIM CODE"
fi

# OS/Distro Detection
KNOWN_DISTRIBUTION="(debian|ubuntu|redhat|centos|opensuse|amazon|arista|suse|raspbian|openwrt|archlinux|oracle|manjaro|\bedgeos\b|alpine|photon|milk-v|buildroot)"
DISTRIBUTION=""

LSB_RELEASE=$(lsb_release -d 2>/dev/null | grep -i -Eo $KNOWN_DISTRIBUTION | head -n1 | tr '[A-Z]' '[a-z]')
ETC_ISSUE=$(grep -i -Eo $KNOWN_DISTRIBUTION /etc/issue 2>/dev/null | head -n1 | tr '[A-Z]' '[a-z]')
ETC_EOS_RELEASE=$(grep -Eo $KNOWN_DISTRIBUTION /etc/Eos-release 2>/dev/null | head -n1 | tr '[A-Z]' '[a-z]')
ETC_OS_RELEASE=$(grep -i -m1 -Eo $KNOWN_DISTRIBUTION /etc/os-release 2>/dev/null | head -n1 | tr '[A-Z]' '[a-z]')
OPENWRT_RELEASE=$(grep -i -m1 -Eo $KNOWN_DISTRIBUTION /etc/openwrt_release 2>/dev/null | head -n1 | tr '[A-Z]' '[a-z]')
UNAME_S=$(uname -s 2>/dev/null | tr '[A-Z]' '[a-z]')

if [ ! -z "$LSB_RELEASE" ]; then
  DISTRIBUTION=$LSB_RELEASE
elif [ ! -z "$ETC_ISSUE" ]; then
  DISTRIBUTION=$ETC_ISSUE
elif [ ! -z "$ETC_EOS_RELEASE" ]; then
  DISTRIBUTION=$ETC_EOS_RELEASE
elif [ ! -z "$ETC_OS_RELEASE" ]; then
  DISTRIBUTION=$ETC_OS_RELEASE
elif [ ! -z "$OPENWRT_RELEASE" ]; then
  DISTRIBUTION=$OPENWRT_RELEASE
else
  DISTRIBUTION=$UNAME_S
fi

echo "* Distribution: $DISTRIBUTION"
echo ""

if [ "$DISTRIBUTION" = "darwin" ]; then
  OS="macOS"
elif [ "$DISTRIBUTION" = "linux" ]; then
  OS="Raspbian"
elif [ "$DISTRIBUTION" = "raspbian" ]; then
  OS="Raspbian"
elif [ "$DISTRIBUTION" = "milk-v" ]; then
  OS="MilkV"
elif [ "$DISTRIBUTION" = "buildroot" ]; then
  # Buildroot is generic; check if this is actually a Milk-V system
  if [ -f /proc/device-tree/model ]; then
    if [ "$(tr -d '\0' < /proc/device-tree/model | grep -io 'milk-v')" != "" ]; then
      OS="MilkV"
    fi
  fi
elif [ "$DISTRIBUTION" = "debian" ] || [ "$DISTRIBUTION" = "ubuntu" ]; then
  OS="Debian"
  if [ "$DISTRIBUTION" = "ubuntu" ]; then
    # Check if this is actually a Jetson system
    if [ -f /etc/nv_tegra_release ]; then
      if [ "$(cat /etc/nv_tegra_release | grep -io 'BOARD')" != "" ]; then
        OS="Jetson"
      fi
    fi
  fi
  if [ "$DISTRIBUTION" = "debian" ]; then
    # Check if this is actually a Raspberry Pi system
    if [ -f /proc/cpuinfo ]; then
      if [ "$(cat /proc/cpuinfo | grep -io 'raspberry')" != "" ]; then
        OS="Raspbian"
      fi
    fi
    if [ -f /proc/device-tree/model ]; then
      if [ "$(cat /proc/device-tree/model | grep -aio 'tinker board')" != "" ]; then
        OS="Tinkerboard"
      fi
    fi
  fi
elif [ "$DISTRIBUTION" = "edgeos" ]; then
  OS="EdgeOS"
elif [ -f /etc/redhat-release ] || [ "$DISTRIBUTION" = "redhat" ] || [ "$DISTRIBUTION" = "centos" ] || [ "$DISTRIBUTION" = "amazon" ]; then
  OS="RedHat"
# Some newer distros like Amazon may not have a redhat-release file
elif [ -f /etc/system-release ] || [ "$DISTRIBUTION" = "amazon" ]; then
  OS="RedHat"
# Arista is based off of Fedora14/18 but do not have /etc/redhat-release
elif [ -f /etc/Eos-release ] || [ "$DISTRIBUTION" = "arista" ]; then
  OS="RedHat"
# Photon is made by VMWare and is a liteweight linux for cloud.
elif [ -f /etc/photon-release ] || [ "$DISTRIBUTION" = "photon" ]; then
  OS="RedHat"
# openSUSE and SUSE use /etc/SuSE-release or /etc/os-release
elif [ -f /etc/SuSE-release ] || [ "$DISTRIBUTION" = "suse" ] || [ "$DISTRIBUTION" = "opensuse" ]; then
  OS="SUSE"
elif [ "$DISTRIBUTION" = "openwrt" ]; then
  OS="OpenWrt"
elif [ "$DISTRIBUTION" = "archlinux" ] || [ "$DISTRIBUTION" = "manjaro" ]; then
  OS="ArchLinux"
elif [ "$DISTRIBUTION" = "alpine" ]; then
  OS="Alpine"
fi

echo "* OS: $OS"
echo ""

# Install the necessary package sources
if [ "$OS" = "RedHat" ] || [ "$OS" = "SUSE" ]; then
  UNAME_M=$(uname -m)
  if [ "$UNAME_M" = "i686" ] || [ "$UNAME_M" = "i386" ] || [ "$UNAME_M" = "x86" ]; then
    ARCHI="i386"
  elif [ "$UNAME_M" = "aarch64" ]; then
    ARCHI="aarch64"
  else
    ARCHI="x86_64"
  fi

  PKG_MANAGER_UPDATE_CMD=""
  PKG_MANAGER_INSTALL_CMD=""
  if [ $(command -v yum) ]; then
    PKG_MANAGER_UPDATE_CMD="yum check-update"
    PKG_MANAGER_INSTALL_CMD="yum install -y"
  elif [ $(command -v zypper) ]; then
    PKG_MANAGER_UPDATE_CMD="zypper --non-interactive refresh"
    PKG_MANAGER_INSTALL_CMD="zypper --non-interactive install --allow-unsigned-rpm"
  elif [ $(command -v dnf) ]; then
    PKG_MANAGER_UPDATE_CMD="dnf makecache -y"
    PKG_MANAGER_INSTALL_CMD="dnf install -y"
  fi
  echo "update command: $sudo_cmd $PKG_MANAGER_UPDATE_CMD"
  $sudo_cmd $PKG_MANAGER_UPDATE_CMD

  echo "* Installing the remoteit Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}.${ARCHI}.rpm"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}-1.${ARCHI}.rpm"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.rpm"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.rpm"
  echo "$sudo_cmd $PKG_MANAGER_INSTALL_CMD /tmp/${package}.rpm"
  $sudo_cmd $PKG_MANAGER_INSTALL_CMD /tmp/${package}.rpm
elif [ "$OS" = "Debian" ]; then
  echo ""
  echo "* Installing apt-transport-https and jq"
  echo ""
  $sudo_cmd apt-get update || echo "'apt-get update' failed, the script will not install the latest version of apt-transport-https."
  if [ -z "$sudo_cmd" ]; then
    # if $sudo_cmd is empty, doing `$sudo_cmd X=Y command` fails with
    # `X=Y: command not found`; therefore we don't prefix the command with
    # $sudo_cmd at all in this case
    DEBIAN_FRONTEND=noninteractive apt-get install -y apt-transport-https jq
  else
    $sudo_cmd DEBIAN_FRONTEND=noninteractive apt-get install -y apt-transport-https jq
  fi

  ARCHI=$(dpkg --print-architecture)

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}.${ARCHI}.deb"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}.${ARCHI}.deb"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd apt-get install -y /tmp/${package}.deb
elif [ "$OS" = "EdgeOS" ]; then
  echo ""
  echo "* Installing apt-transport-https and jq"
  echo ""
  $sudo_cmd apt-get update || echo "'apt-get update failed', the script will not install the latest version of apt-transport-https."
  if [ -z "$sudo_cmd" ]; then
    # if $sudo_cmd is empty, doing `$sudo_cmd X=Y command` fails with
    # `X=Y: command not found`; therefore we don't prefix the command with
    # $sudo_cmd at all in this case
    DEBIAN_FRONTEND=noninteractive apt-get install -y apt-transport-https jq
  else
    $sudo_cmd DEBIAN_FRONTEND=noninteractive apt-get install -y apt-transport-https jq
  fi

  ARCHI=$(dpkg --print-architecture)

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}.${ARCHI}.edgerouter.deb"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}.${ARCHI}.edgerouter.deb"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd apt-get install -y /tmp/${package}.deb
elif [ "$OS" = "Raspbian" ]; then
  ARCHI=$(dpkg --print-architecture)

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}.${ARCHI}.rpi.deb"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}.${ARCHI}.rpi.deb"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd apt-get install -y /tmp/${package}.deb
elif [ "$OS" = "Jetson" ]; then
  ARCHI=$(dpkg --print-architecture)

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}.${ARCHI}.jetson.deb"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}.${ARCHI}.jetson.deb"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd apt-get install -y /tmp/${package}.deb
elif [ "$OS" = "Tinkerboard" ]; then
  ARCHI=$(dpkg --print-architecture)

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}.${ARCHI}.tinkerboard.deb"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}.${ARCHI}.tinkerboard.deb"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.deb"
  $sudo_cmd apt-get install -y /tmp/${package}.deb
elif [ "$OS" = "OpenWrt" ]; then
  . /etc/openwrt_release
  ARCHI=${DISTRIB_ARCH:-arm_cortex-a9}

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  PKG_MANAGER_UPDATE_CMD=""
  PKG_MANAGER_INSTALL_CMD=""
  package_ext=""
  download_filename=""
  if [ $(command -v opkg) ]; then
    echo "* Using opkg"
    PKG_MANAGER_UPDATE_CMD="opkg update"
    PKG_MANAGER_INSTALL_CMD="opkg install"
    package_ext="ipk"
    download_filename="${package}.${package_ext}"
    if [ "$remoteit_version_dir" != "latest" ]; then
      download_filename="${package}_${remoteit_version}.${package_ext}"
    fi
  elif [ $(command -v apk) ]; then
    echo "* Using apk"
    PKG_MANAGER_UPDATE_CMD="apk update"
    PKG_MANAGER_INSTALL_CMD="apk add --allow-untrusted"
    package_ext="apk"
    download_filename="${package}-openwrt.${package_ext}"
    if [ "$remoteit_version_dir" != "latest" ]; then
      download_filename="${package}-${remoteit_version}-openwrt.${package_ext}"
    fi
  fi
  echo "update command: $sudo_cmd $PKG_MANAGER_UPDATE_CMD"
  $sudo_cmd $PKG_MANAGER_UPDATE_CMD

  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.${package_ext}"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.${package_ext}"
  if [ -z "$sudo_cmd" ]; then
    # if $sudo_cmd is empty, doing `$sudo_cmd X=Y command` fails with
    # `X=Y: command not found`; therefore we don't prefix the command with
    # $sudo_cmd at all in this case
    DISTRIB_ARCH=${ARCHI} ${PKG_MANAGER_INSTALL_CMD} /tmp/${package}.${package_ext}
  else
    $sudo_cmd DISTRIB_ARCH=${ARCHI} ${PKG_MANAGER_INSTALL_CMD} /tmp/${package}.${package_ext}
  fi
elif [ "$OS" = "ArchLinux" ]; then
  UNAME_M=$(uname -m)
  PACKAGE_EXTENSION="pkg.tar.xz"
  if [ "$UNAME_M" = "i686" ] || [ "$UNAME_M" = "i386" ] || [ "$UNAME_M" = "x86" ]; then
    # ARCHI="i386"
    echo "Unsupported Arch Linux machine type: $UNAME_M"
    echo ""
    exit;
  elif [ "$UNAME_M" = "aarch64" ]; then
    ARCHI="aarch64"
  else
    ARCHI="x86_64"
    PACKAGE_EXTENSION="pkg.tar.zst"
  fi

  $sudo_cmd pacman -Sy

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}-${ARCHI}.${PACKAGE_EXTENSION}"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}-${ARCHI}.${PACKAGE_EXTENSION}"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.${PACKAGE_EXTENSION}"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.${PACKAGE_EXTENSION}"
  $sudo_cmd pacman -U --noconfirm /tmp/${package}.${PACKAGE_EXTENSION}
elif [ "$OS" = "Alpine" ]; then
  UNAME_M=$(uname -m)
  ARCHI=$UNAME_M

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}-${ARCHI}.apk"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}-r1-${ARCHI}.apk"
  fi
  echo "command: curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.apk"
  $sudo_cmd sh -c "curl -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output /tmp/${package}.apk"
  $sudo_cmd apk add --allow-untrusted /tmp/${package}.apk
elif [ "$OS" = "MilkV" ]; then
  UNAME_M=$(uname -m)
  ARCHI=$UNAME_M

  echo "* Installing the ${package} Agent package for ${ARCHI}"
  echo ""

  download_filename="${package}-${ARCHI}-musl.tar.gz"
  if [ "$remoteit_version_dir" != "latest" ]; then
    download_filename="${package}-${remoteit_version}-${ARCHI}-musl.tar.gz"
  fi
  # Download and extract inside a fresh private staging directory so only the
  # files fetched by this run are ever executed; install.sh uses paths
  # relative to the package root, so run it from there
  staging_dir=$($sudo_cmd mktemp -d /tmp/${package}.XXXXXX) || { echo "ERROR: could not create staging directory"; exit 1; }
  echo "command: curl -f -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output ${staging_dir}/${package}.tar.gz"
  $sudo_cmd sh -c "curl -f -L https://${repository_url}/remoteit/${remoteit_version_dir}/${download_filename} --output ${staging_dir}/${package}.tar.gz" || { echo "ERROR: download failed"; $sudo_cmd rm -rf ${staging_dir}; exit 1; }
  $sudo_cmd tar -xzf ${staging_dir}/${package}.tar.gz -C ${staging_dir} || { echo "ERROR: extraction failed"; $sudo_cmd rm -rf ${staging_dir}; exit 1; }
  $sudo_cmd sh -c "cd ${staging_dir} && sh ./install.sh"
  install_status=$?
  $sudo_cmd rm -rf ${staging_dir}
  exit $install_status
else
  if [ "$OS" = "macOS" ]; then
    echo "The ${package} device package cannot be installed directly onto a macOS system."
    echo ""
    echo "Please try one of the following other options:"
    echo "- Remoteit Desktop (https://www.remote.it/getting-started/mac)"
    echo "- Remoteit CLI (https://www.remote.it/download-list?platform-list=mac&products=cli#Download-Results)"
    echo "- remoteit-agent for Docker (https://hub.docker.com/r/remoteit/remoteit-agent)"
  else
    sh -c "$(curl -sL https://downloads.remote.it/remoteit/distributiontest.sh)"
  fi
  echo ""
  exit;
fi
