#!/bin/sh
# Скрипт создает
export TEXTDOMAINDIR='/usr/share/locale'
export TEXTDOMAIN='podsec'

export cmd=$0
if [ $# -lt 1 ]
then
  echo $(gettext 'The IP address of the registry and signature server is not specified') >&2
  echo "$(gettext 'Format'):\n\t$cmd $(gettext '<ip_address_of_registrar_and_signature_server>')\n" >&2
  exit 1
fi

if [ $# -gt 1 ]
then
  echo $(gettext 'Only one IP address of the registry and signature server must be specified.') >&2
  echo "$(gettext 'Format'):\n\t$cmd $(gettext '<ip_address_of_registrar_and_signature_server>')\n" >&2
  exit 1
fi

export regIP=$1

case $regIP in
  '127.0.0.1')
    echo "$(gettext 'The IP address of the registry and signature server must not be local'): $regIP" >&2
    exit 1;;
esac

ifs=$IFS IFS=.
set -- $regIP
IFS=$ifs
if [ $# -ne 4 ]
then
  echo "$(gettext 'Invalid IP address'): $regIP" >&2
  exit 2
fi

for ip
do
  if [[ "$a" =~ $re && "$a" -ge 0 && "$a" -lt 256 ]]
  then :;
  else
    echo "$(gettext 'Invalid IP address'): $regIP" >&2
    exit 3
  fi
done

# Создание групп
groupadd -r podman >/dev/null 2>&1
groupadd -r podman_dev >/dev/null 2>&1

# Поддержка возможности работа в rootless режиме
echo kernel.unprivileged_userns_clone=1 > /etc/sysctl.d/99-podman.conf
sysctl -w kernel.unprivileged_userns_clone=1

control newgidmap podmanonly
control newuidmap podmanonly

localIP=
if ip a  | grep $regIP >/dev/null 2>&1
then
  localIP='yes'
fi


if line=$(grep $regIP /etc/hosts 2>/dev/null)
then
  set -- $line
  export ip=$1
  shift
  for domain
  do
    if [ "$domain" = 'registry.local' ] || [ "$domain" = 'sigstore.local' ] || [ "$domain" = 'trivy.local'  ]
    then
      echo "$(gettext 'Domains registry.local sigstore.local trivy.local are already bound to IP address') $ip" >&2
      echo $(gettext 'Remove the binding and run the script again')  >&2
      exit 1
    fi
  done
fi
echo "$(gettext 'Adding a binding of domains registry.local sigstore.local trivy.local to IP address') $regIP" >&2
echo "$regIP registry.local sigstore.local trivy.local" >> /etc/hosts

# Создание группы podman
echo $(gettext 'Creating podman group')  >&2
groupadd -r podman >/dev/null 2>&1
echo "$(gettext 'Initializing the') /var/sigstore/ $(gettext 'directory and subdirectories for storing public keys and image signatures')" >&2

# Создание каталога и подкаталогов /var/sigstore/ если IP-адрес узла совпадает с IP-адресом сервера подписей storage.local
echo "$(gettext 'Creating the directory and subdirectories') /var/sigstore/" >&2
mkdir -p -m 0775 /var/sigstore/keys/
if [ -n "$localIP" ]
then
  #IP-адрес узла совпадает с IP-адресом сервера подписей storage.local
  echo $(gettext 'Creating the podman_dev group') >&2
  groupadd -r podman_dev >/dev/null 2>&1
  # Создать каталог sogstore с подкаталогами
  chown root:podman_dev /var/sigstore/keys/
  mkdir -p -m 0775 /var/sigstore/sigstore/
  chown root:podman_dev /var/sigstore/sigstore/
  echo '<html><body><h1>SigStore works!</h1></body></html>' > /var/sigstore/index.html
else
  chown root:podman /var/sigstore/keys/
fi

# Создание файла политик /etc/containers/policy.json и файла /etc/containers/registries.d/default.yaml описания доступа к открытым ключам подписантов
cd /etc/containers

# Создание registries.d/default.yaml

suffix=$(date '+%Y-%m-%d_%H:%M:%S')
policyFile='policy.json'
yesterday=$(date '+%Y-%m-%d_%H:%M:%S' -d "yesterday")
now=$(date '+%Y-%m-%d_%H:%M:%S')

# Создание с сохранением предыдущего файла политик /etc/containers/policy.json
echo "$(gettext 'Creating with preservation of the previous policy file') /etc/containers/policy.json" >&2
if [ ! -L $policyFile ]
then :;
  mv $policyFile "policy_${yesterday}"
fi
linkedPolicyFile="policy_${now}"
if [ -n "$localIP" ]
then
  echo '{"default":[{"type":"reject"}], "transports":{"docker": {}}}' |
  jq . > $linkedPolicyFile
else
  # Копирование ключей и policy.json с sigstore
  mkdir -p /var/sigstore/keys/
  files=$(curl -s  http://sigstore.local:81/keys/ | jq '.[].name')
  for file in $files
  do
    file=${file:1:-1}
    curl -s  http://sigstore.local:81/keys/$file -o /var/sigstore/keys/$file
  done
  cp /var/sigstore/keys/policy.json  $linkedPolicyFile
fi
ln -sf $linkedPolicyFile $policyFile

# Создание с сохранением предыдущего файла `/etc/containers/registries.d/default.yaml` описания доступа к открытым ключам подписантов
echo "$(gettext 'Creating with preservation of the previous file') /etc/containers/registries.d/default.yaml $(gettext 'description of access to public keys of signatories')" >&2
cd /etc/containers/registries.d
defaultYaml='default.yaml'
if [ ! -L $defaultYaml ]
then :;
  mv $defaultYaml ${defaultYaml}.${yesterday}
fi
linkedDefaultYaml="default_${now}"
sigStoreURL="http://sigstore.local:81/sigstore/"
refs="\"lookaside\":\"$sigStoreURL\", \"sigstore\":\"$sigStoreURL\""
refs="{$refs}"
echo "{\"default-docker\":$refs}" | yq -y . > $linkedDefaultYaml
ln -sf $linkedDefaultYaml $defaultYaml

cd /etc/containers
# Добавление insecure-доступа к регистратору registry.local в файле /etc/containers/registries.conf
echo "$(gettext 'Adding insecure access to the registry.local registry in the') /etc/containers/registries.conf file" >&2
registriesConf="registries.conf"
if [ ! -L $registriesConf ]
then :;
  cp $registriesConf ${registriesConf}.${yesterday}
fi
linkedRegistriesConf="registries_${now}"
if grep '^location.*=.*registry.local' $registriesConf > /dev/nul 2>&1
then :;
else
  cp $registriesConf $linkedRegistriesConf
  echo -ne "\n[[registry]]\nlocation = \"registry.local\"\ninsecure = true\n" >> $linkedRegistriesConf
  ln -sf $linkedRegistriesConf  $registriesConf
fi







