#!/bin/sh

# Client script for LXC container images.
#
# Copyright © 2014 Stéphane Graber <stgraber@ubuntu.com>
#
#  This library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public
#  License as published by the Free Software Foundation; either
#  version 2.1 of the License, or (at your option) any later version.

#  This library is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Lesser General Public License for more details.

#  You should have received a copy of the GNU Lesser General Public
#  License along with this library; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
#  USA

set -eu

LOCALSTATEDIR=/var
LXC_HOOK_DIR=/usr/share/lxc/hooks
LXC_TEMPLATE_CONFIG=/usr/share/lxc/config

# Defaults
DOWNLOAD_ARCH=
DOWNLOAD_BUILD=
DOWNLOAD_COMPAT_LEVEL=7
DOWNLOAD_DIST=
DOWNLOAD_FLUSH_CACHE="false"
DOWNLOAD_FORCE_CACHE="false"
DOWNLOAD_INTERACTIVE="false"
DOWNLOAD_LIST_IMAGES="false"
DOWNLOAD_MODE="system"
DOWNLOAD_RELEASE=
DOWNLOAD_SERVER="images.linuxcontainers.org"
DOWNLOAD_TARGET="system"
DOWNLOAD_URL=
DOWNLOAD_USE_CACHE="false"
DOWNLOAD_VARIANT="default"
DOWNLOAD_TEMP=

LXC_MAPPED_GID=
LXC_MAPPED_UID=
LXC_NAME=
LXC_PATH=
LXC_ROOTFS=

# Make sure the usual locations are in PATH
export PATH="$PATH:/usr/sbin:/usr/bin:/sbin:/bin"

# Some useful functions
cleanup() {
  if [ -d "${DOWNLOAD_TEMP}" ]; then
    rm -Rf "${DOWNLOAD_TEMP}"
  fi
}

wget_wrapper() {
  for _ in $(seq 3); do
    if wget "$@"; then
      return 0
    fi
  done

  return 1
}

in_userns() {
  [ -e /proc/self/uid_map ] || { echo no; return; }
  while read -r line; do
    fields="$(echo "$line" | awk '{ print $1 " " $2 " " $3 }')"
    if [ "${fields}" = "0 0 4294967295" ]; then
      echo no;
      return;
    fi
    if echo "${fields}" | grep -q " 0 1$"; then
      echo userns-root;
      return;
    fi
  done < /proc/self/uid_map

  if [ -e /proc/1/uid_map ]; then
    if [ "$(cat /proc/self/uid_map)" = "$(cat /proc/1/uid_map)" ]; then
      echo userns-root
      return
    fi
  fi
  echo yes
}

relevant_file() {
  FILE_PATH="${LXC_CACHE_PATH}/$1"

  if [ -e "${FILE_PATH}-${DOWNLOAD_MODE}" ]; then
    FILE_PATH="${FILE_PATH}-${DOWNLOAD_MODE}"
  fi

  if [ -e "${FILE_PATH}.${DOWNLOAD_COMPAT_LEVEL}" ]; then
    FILE_PATH="${FILE_PATH}.${DOWNLOAD_COMPAT_LEVEL}"
  fi

  echo "${FILE_PATH}"
}

usage() {
  cat <<EOF

EOF
  return 0
}

if ! options=$(getopt -o d:r:a:hl -l dist:,release:,arch:,help,list,variant:,\
server:,flush-cache,force-cache,name:,path:,\
rootfs:,mapped-uid:,mapped-gid: -- "$@"); then
  usage
  exit 1
fi
eval set -- "$options"

while :; do
  case "$1" in
    -h|--help)     usage && exit 1;;
    -l|--list)     DOWNLOAD_LIST_IMAGES="true"; shift 1;;
    -d|--dist)     DOWNLOAD_DIST="$2"; shift 2;;
    -r|--release)  DOWNLOAD_RELEASE="$2"; shift 2;;
    -a|--arch)     DOWNLOAD_ARCH="$2"; shift 2;;
    --variant)     DOWNLOAD_VARIANT="$2"; shift 2;;
    --server)      DOWNLOAD_SERVER="$2"; shift 2;;
    --flush-cache) DOWNLOAD_FLUSH_CACHE="true"; shift 1;;
    --force-cache) DOWNLOAD_FORCE_CACHE="true"; shift 1;;
    --name)        LXC_NAME="$2"; shift 2;;
    --path)        LXC_PATH="$2"; shift 2;;
    --rootfs)      LXC_ROOTFS="$2"; shift 2;;
    --mapped-uid)  LXC_MAPPED_UID="$2"; shift 2;;
    --mapped-gid)  LXC_MAPPED_GID="$2"; shift 2;;
    *)             break;;
  esac
done

# Check for required binaries
for bin in tar xz wget; do
  if ! command -V "${bin}" >/dev/null 2>&1; then
    echo "ERROR: Missing required tool: ${bin}" 1>&2
    exit 1
  fi
done

# Check that we have all variables we need
echo "=== LXC Template Parameters ==="
echo "LXC_NAME: ${LXC_NAME}"
echo "LXC_PATH: ${LXC_PATH}"
echo "LXC_ROOTFS: ${LXC_ROOTFS}"
echo "=============================="

if [ -z "${LXC_NAME}" ] || [ -z "${LXC_PATH}" ] || [ -z "${LXC_ROOTFS}" ]; then
  if [ "${DOWNLOAD_LIST_IMAGES}" != "true" ]; then
    echo "ERROR: Please pass the name, path, and rootfs for the container" 1>&2
    exit 1
  fi
fi

# Verify LXC_PATH directory exists
if [ ! -d "${LXC_PATH}" ]; then
  echo "ERROR: LXC_PATH directory does not exist: ${LXC_PATH}" 1>&2
  exit 1
fi
echo "LXC_PATH directory exists"

USERNS="$(in_userns)"

if [ "${USERNS}" != "no" ]; then
  if [ "${USERNS}" = "yes" ]; then
    if [ -z "${LXC_MAPPED_UID}" ] || [ "${LXC_MAPPED_UID}" = "-1" ]; then
      echo "ERROR: In a user namespace without a map" 1>&2
      exit 1
    fi
    DOWNLOAD_MODE="user"
    DOWNLOAD_TARGET="user"
  else
    DOWNLOAD_MODE="user"
    DOWNLOAD_TARGET="system"
  fi
fi

# Trap all exit signals
trap cleanup EXIT HUP INT TERM

# /tmp may be mounted in tmpfs or noexec
if mountpoint -q /tmp; then
  DOWNLOAD_TEMP="${LXC_PATH}"
fi

if ! command -V mktemp >/dev/null 2>&1; then
  DOWNLOAD_TEMP="${DOWNLOAD_TEMP}/tmp/lxc-download.$$"
elif [ -n "${DOWNLOAD_TEMP}" ]; then
  mkdir -p "${DOWNLOAD_TEMP}"
  DOWNLOAD_TEMP="$(mktemp -p "${DOWNLOAD_TEMP}" -d)"
else
  DOWNLOAD_TEMP="${DOWNLOAD_TEMP}$(mktemp -d)"
fi

# Setup the cache
if [ "${DOWNLOAD_TARGET}" = "system" ]; then
  LXC_CACHE_BASE="${LOCALSTATEDIR}/cache/lxc/"
else
  LXC_CACHE_BASE="${HOME}/.cache/lxc/"
fi

# Allow the setting of the LXC_CACHE_PATH with the usage of environment variables.
LXC_CACHE_PATH="${LXC_CACHE_PATH:-"${LXC_CACHE_BASE}"}"
# For local cache with 'default' dist, use simple path structure
if [ "${DOWNLOAD_DIST}" = "default" ] && [ "${DOWNLOAD_RELEASE}" = "default" ]; then
  LXC_CACHE_PATH="${LXC_CACHE_PATH}/download/default"
else
  LXC_CACHE_PATH="${LXC_CACHE_PATH}/download/${DOWNLOAD_DIST}"
  LXC_CACHE_PATH="${LXC_CACHE_PATH}/${DOWNLOAD_RELEASE}/${DOWNLOAD_ARCH}"
  LXC_CACHE_PATH="${LXC_CACHE_PATH}/${DOWNLOAD_VARIANT}"
fi

# Check if local cache has rootfs - if yes, always use it (no download)
if [ -f "${LXC_CACHE_PATH}/rootfs.tar.xz" ]; then
  echo "Found local rootfs cache at ${LXC_CACHE_PATH}/rootfs.tar.xz"
  DOWNLOAD_USE_CACHE="true"
  DOWNLOAD_FORCE_CACHE="true"
elif [ -d "${LXC_CACHE_PATH}" ]; then
  if [ "${DOWNLOAD_FLUSH_CACHE}" = "true" ]; then
    echo "Flushing the cache..."
    rm -Rf "${LXC_CACHE_PATH}"
  elif [ "${DOWNLOAD_FORCE_CACHE}" = "true" ]; then
    DOWNLOAD_USE_CACHE="true"
  else
    DOWNLOAD_USE_CACHE="true"
    if [ -e "$(relevant_file expiry)" ]; then
      if [ "$(cat "$(relevant_file expiry)")" -lt "$(date +%s)" ]; then
        echo "The cached copy has expired, re-downloading..."
        DOWNLOAD_USE_CACHE="false"
      fi
    fi
  fi
fi

# Download what's needed
if [ "${DOWNLOAD_USE_CACHE}" = "false" ]; then
  # Grab the index
  DOWNLOAD_INDEX_PATH="/meta/1.0/index-${DOWNLOAD_MODE}"
  echo "Downloading the image index"
  if [ -d "${LXC_CACHE_PATH}" ] && [ -f "${LXC_CACHE_PATH}/build_id" ] && \
     [ "$(cat "${LXC_CACHE_PATH}/build_id")" = "${DOWNLOAD_BUILD}" ]; then
    echo "The cache is already up to date"
    echo "Using image from local cache"
  else
    DOWNLOAD_FILE="$DOWNLOAD_TEMP/downloaded_file.tar.gz"
    # Download the actual files
    wget -O "$DOWNLOAD_FILE" "$DOWNLOAD_SERVER"
    # Extract the tar.gz file
    tar -xzf "$DOWNLOAD_FILE" -C "$DOWNLOAD_TEMP"
    if [ -d "${LXC_CACHE_PATH}" ]; then
      rm -Rf "${LXC_CACHE_PATH}"
    fi
    mkdir -p "${LXC_CACHE_PATH}"
    mv "${DOWNLOAD_TEMP}/rootfs/gryphon_rootfs.tar.xz" "${LXC_CACHE_PATH}/rootfs.tar.xz"
    if ! tar Jxf "${DOWNLOAD_TEMP}/metadata/meta.tar.xz" -C "${LXC_CACHE_PATH}"; then
      echo "ERROR: Invalid rootfs tarball." 2>&1
      exit 1
    fi

    echo "${DOWNLOAD_BUILD}" > "${LXC_CACHE_PATH}/build_id"

    if [ -n "${LXC_MAPPED_UID}" ] && [ "${LXC_MAPPED_UID}" != "-1" ]; then
      chown -R "${LXC_MAPPED_UID}" "${LXC_CACHE_BASE}" >/dev/null 2>&1 || :
    fi
    if [ -n "${LXC_MAPPED_GID}" ] && [ "${LXC_MAPPED_GID}" != "-1" ]; then
      chgrp -R "${LXC_MAPPED_GID}" "${LXC_CACHE_BASE}" >/dev/null 2>&1 || :
    fi
    echo "The image cache is now ready"
  fi
else
  echo "Using image from local cache"
fi

# Unpack the rootfs
echo "Unpacking the rootfs"

EXCLUDES=""
excludelist=$(relevant_file excludes)
if [ -f "${excludelist}" ]; then
  while read -r line; do
    EXCLUDES="${EXCLUDES} --exclude=${line}"
  done < "${excludelist}"
fi

# Do not surround ${EXCLUDES} by quotes. This does not work. The solution could
# use array but this is not POSIX compliant. The only POSIX compliant solution
# is to use a function wrapper, but the latter can't be used here as the args
# are dynamic. We thus need to ignore the warning brought by shellcheck.
# shellcheck disable=SC2086
tar  --anchored ${EXCLUDES} --numeric-owner -xpJf "${LXC_CACHE_PATH}/rootfs.tar.xz" -C "${LXC_ROOTFS}"
echo "Rootfs extraction completed successfully"

mkdir -p "${LXC_ROOTFS}/dev/pts/"
echo "Created /dev/pts/ directory"

# Setup the configuration
echo "Looking for config file..."
configfile="$(relevant_file config)"
echo "Config file path: ${configfile}"
fstab="$(relevant_file fstab)"
echo "Fstab file path: ${fstab}"

if [ ! -e "${configfile}" ]; then
  echo "ERROR: meta tarball is missing the configuration file at ${configfile}" 1>&2
  echo "Contents of LXC_CACHE_PATH (${LXC_CACHE_PATH}):" 1>&2
  ls -la "${LXC_CACHE_PATH}" 1>&2
  exit 1
fi

echo "Config file found, proceeding..."
echo "Creating ${LXC_PATH}/config from cached config..."
cp "${configfile}" "${LXC_PATH}/config"
echo "Config created at ${LXC_PATH}/config"

## Extract all the network config entries
echo "Extracting network config entries..."
sed -i -e "/lxc.net.0/{w ${LXC_PATH}/config-network" -e "d}" "${LXC_PATH}/config"
echo "Network config extraction done"

## Extract any other config entry
echo "Extracting other config entries..."
sed -i -e "/lxc./{w ${LXC_PATH}/config-auto" -e "d}" "${LXC_PATH}/config"
echo "Other config extraction done"

## Append the defaults
echo "Appending distribution configuration..."
{
  echo ""
  echo "# Distribution configuration"
  cat "$configfile"
} >> "${LXC_PATH}/config"
echo "Distribution config appended"

## Add the container-specific config
echo "Adding container-specific configuration..."
{
  echo ""
  echo "# Container specific configuration"
  if [ -e "${LXC_PATH}/config-auto" ]; then
    cat "${LXC_PATH}/config-auto"
    rm "${LXC_PATH}/config-auto"
  fi
  if [ -e "${fstab}" ]; then
    echo "lxc.mount.fstab = ${LXC_PATH}/fstab"
  fi
  echo "lxc.uts.name = ${LXC_NAME}"
  echo "lxc.environment = CONTAINER_NAME=${LXC_NAME}"
  # Get the default network interface
  echo "Getting network interface info..."
  DEFAULT_IFACE=$(ip route | grep default | awk '{print $5}')
  echo "Default interface: ${DEFAULT_IFACE}"
  DEFAULT_IFACE_IP=$(ip addr show ${DEFAULT_IFACE} | grep 'inet ' | awk '{print $2}' | cut -d/ -f1 | head -n1)
  echo "Default interface IP: ${DEFAULT_IFACE_IP}"

  echo "lxc.environment = BRIDGE_INTF=${DEFAULT_IFACE}"
  echo "lxc.environment = BRIDGE_IP=${DEFAULT_IFACE_IP}"

} >> "${LXC_PATH}/config"
echo "Container-specific config added"

## Re-add the previously removed network config
echo "Re-adding network configuration..."
if [ -e "${LXC_PATH}/config-network" ]; then
  {
    echo ""
    echo "# Network configuration"
    cat "${LXC_PATH}/config-network"
    rm "${LXC_PATH}/config-network"
  } >> "${LXC_PATH}/config"
  echo "Network config re-added"
else
  echo "No network config to re-add"
fi

echo "Adding final network settings..."
echo "lxc.net.0.type = none" >> ${LXC_PATH}/config
echo "lxc.net.0.link = lxcbr0" >> ${LXC_PATH}/config
echo "lxc.net.0.flags = up" >> ${LXC_PATH}/config
echo "Final network settings added"
#echo "lxc.net.0.hwaddr = 00:16:3e:xx:xx:xx" >> ${LXC_PATH}/config


TEMPLATE_FILES="${LXC_PATH}/config"

# Setup the fstab
if [ -e "${fstab}" ]; then
  cp "${fstab}" "${LXC_PATH}/fstab"
  TEMPLATE_FILES="${TEMPLATE_FILES};${LXC_PATH}/fstab"
fi

mkdir -p ${LXC_PATH}/persistent-data

echo "Adding custom mount entries and hooks..."
echo "lxc.mount.entry = /gryphon_sockets gryphon_sockets none bind,create=dir 0 0" >> ${LXC_PATH}/config
echo "lxc.mount.entry = /etc/parameter_values.json etc/parameter_values.json none bind,create=file 0 0" >> ${LXC_PATH}/config
echo "lxc.mount.entry = mkdir -p ${LXC_PATH}/persistent-data persistent-data none bind,create=dir 0 0
#echo "lxc.hook.pre-start = mkdir -p ${LXC_PATH}/persistent-data" >> ${LXC_PATH}/config
echo "lxc.hook.post-stop = ${LXC_PATH}/rootfs/sbin/kick_clients.sh" >> ${LXC_PATH}/config
echo "Custom mount entries and hooks added"

# Look for extra templates
echo "Looking for extra templates..."
if [ -e "$(relevant_file templates)" ]; then
  echo "Found templates file, processing..."
  while read -r line; do
    fullpath="${LXC_ROOTFS}/${line}"
    [ ! -e "${fullpath}" ] && continue
    TEMPLATE_FILES="${TEMPLATE_FILES};${fullpath}"
  done < "$(relevant_file templates)"
  echo "Extra templates processed"
else
  echo "No extra templates file found"
fi

# Replace variables in all templates
echo "Replacing variables in template files..."
OLD_IFS=${IFS}
IFS=";"
for file in ${TEMPLATE_FILES}; do
    [ ! -f "${file}" ] && continue
  sed -i "s#LXC_NAME#${LXC_NAME}#g" "${file}"
  sed -i "s#LXC_PATH#${LXC_PATH}#g" "${file}"
  sed -i "s#LXC_ROOTFS#${LXC_ROOTFS}#g" "${file}"
  sed -i "s#LXC_TEMPLATE_CONFIG#${LXC_TEMPLATE_CONFIG}#g" "${file}"
  sed -i "s#LXC_HOOK_DIR#${LXC_HOOK_DIR}#g" "${file}"
done
IFS=${OLD_IFS}
echo "Variable replacement completed"

# prevent mingetty from calling vhangup(2) since it fails with userns on CentOS / Oracle
if [ -f "${LXC_ROOTFS}/etc/init/tty.conf" ]; then
  sed -i 's|mingetty|mingetty --nohangup|' "${LXC_ROOTFS}/etc/init/tty.conf"
fi

echo "Setting ownership if needed..."
if [ -n "${LXC_MAPPED_UID}" ] && [ "${LXC_MAPPED_UID}" != "-1" ]; then
  chown "${LXC_MAPPED_UID}" "${LXC_PATH}/config" "${LXC_PATH}/fstab" >/dev/null 2>&1 || :
  echo "UID ownership set"
fi

if [ -n "${LXC_MAPPED_GID}" ] && [ "${LXC_MAPPED_GID}" != "-1" ]; then
  chgrp "${LXC_MAPPED_GID}" "${LXC_PATH}/config" "${LXC_PATH}/fstab" >/dev/null 2>&1 || :
  echo "GID ownership set"
fi

echo "Checking for create-message..."
if [ -e "$(relevant_file create-message)" ]; then
  echo ""
  echo "---"
  cat "$(relevant_file create-message)"
fi

echo "=== Final container config ==="
cat "${LXC_PATH}/config"
echo "=== End config ==="

echo "Verifying container directory structure..."
ls -la "${LXC_PATH}/" 2>&1
echo "Verifying rootfs directory..."
ls -la "${LXC_ROOTFS}/" 2>&1 | head -20

echo "Removing partial marker file..."
rm -f "${LXC_PATH}/partial"
echo "Partial marker removed"

echo "Container creation completed successfully!"
exit 0
