#!/bin/sh
export TEXTDOMAINDIR='/usr/share/locale'
export TEXTDOMAIN='podsec'

# Создание пользователя $user
createImageMaker() {
  ifs=$IFS
  IFS=@
  set -- $1
  IFS=$ifs
  export user=$1
  regPath=$2
  adduser $user -g podman -G podman_dev

  echo "$(gettext 'Enter the password for user') $user - $(gettext 'the container image developer')" >&2
  passwd $user

  cd /home/$user

  mkdir -p .config/containers/

  # Сформировать новый системный policy.json
  TMPFILE="/tmp/createImageMakerUser.$$"
  jq '.transports.docker."'$regPath'"=[{"type": "signedBy","keyType":"GPGKeys","keyPath": "/var/sigstore/keys/'$user'.pgp"}]' /etc/containers/$linkedPolicyFile > $TMPFILE &&
  cp $TMPFILE /var/sigstore/keys/policy.json &&
  mv $TMPFILE /etc/containers/$linkedPolicyFile

  echo '{"default":[{"type":"insecureAcceptAnything"}]}' |
  jq . > .config/containers/policy.json
  mkdir -p .config/containers/registries.d
  sigStoreURL="http://sigstore.local:81/sigstore/"
  refs="{\"lookaside\":\"$sigStoreURL\""
  refs+=", \"sigstore\":\"$sigStoreURL\""
  refs+=", \"lookaside-staging\": \"file:///var/sigstore/sigstore/\""
  refs+=", \"sigstore-staging\": \"file:///var/sigstore/sigstore/\"}"
  echo "{\"default-docker\":$refs}" | yq -y . > .config/containers/registries.d/default.yaml
#   echo "{\"docker\":{\"registry.local\":$refs}}" | yq -y . > .config/containers/registries.d/sigstore_local.yaml
  chown -R $user:podman .

  su - -c 'gpg2 --full-generate-key'  $user
  set -- $(su - -c 'gpg2 --list-keys'  $user)
  if [ $# -lt 1 ]
  then
    echo "$(gettext 'Public key not found')" >&2
#     echo "Не найден открытый ключ"
    exit 1
  fi
  # Вытащить uid из ключа
  while [ $# -gt 1 ]; do shift; if [ ${1:0:1} == '<' ]; then break; fi  done
  uid=$1
  su - -c "gpg2 --output /var/sigstore/keys/$user.pgp  --armor --export '$uid'" $user
}

testRepoPath() {
  ifs=$IFS
  if [ $# -eq 0 ]
  then
    users="imagemaker@registry.local"
  else
    if [ $# -eq 1 ]
    then
      users=$1
      IFS=@
      set -- $1
      IFS=$ifs
      if [ $# -eq 1 ]
      then
        users="$1@registry.local"
      fi
    else
      users="$*"
    fi
  fi

  repoPaths=
  for User in $users
  do
    IFS=@
    set -- $User
    IFS=$ifs
    user=$1 repoPath=$2
    if [ $# -ne 2 -o -z "$user" -o -z "$repoPath" ]
    then
      echo "$(gettext 'Invalid repository path description format for user') $user; $(gettext 'Format'): <user>@<repository_path>\n" >&2
      exit 1
    fi
    repoPaths+="\n$repoPath"
  done

  for repoPath in $(echo -ne $repoPaths)
  do
    same=$(echo -ne $repoPaths | grep $repoPath)
    n=0
    for repopath in $same
    do
      if [ "$repoPath" == "$repopath" ]
      then
        if [ $n -eq 0 ]
        then
          let n=$n+1
        else
          echo "$(gettext 'Two matching repository paths') $repoPath" >&2
          exit 2
        fi
      fi
    done
  done
  echo $users
}

#MAIN

if [ $(id -u) -ne 0 ]
then
  echo "$(gettext 'The script must be run by a user with root rights.')" >&2
  exit 1
fi

. podsec-functions

# Проверка. Является ли текущий сервер сервером, поддерживающий регистратор (registry.local) и сервер подписи образов (sigstore.local)
echo "$(gettext 'Check if the current server is a server that supports the registry (registry.local) and the image signing server (sigstore.local)')" >&2
mes=$(isSigstoreServer)
if [ -n "$mes" ]
then
  echo $mes >&2
  echo "$(gettext 'It is not possible to create users of the container image developer class')" >&2
  exit 1
fi

users=$(testRepoPath $*)

if [ ! -d "/var/sigstore/" ]
then
  echo "$(gettext 'Signature server directory /var/sigstore/ not created')" >&2
  echo "$(gettext 'Call the podsec-create-policy script to initialize it')" >&2
  exit 1
fi

# Запомнить текущую политику
yesterday=$(date '+%Y-%m-%d_%H:%M:%S' -d "yesterday")
if [ ! -L $policyFile ]
then :;
  mv $policyFile ${policyFile}_${yesterday}
fi
now=$(date '+%Y-%m-%d_%H:%M:%S')
export linkedPolicyFile="policy_${now}"
cd /etc/containers/
cp -L policy.json $linkedPolicyFile

# Сформировать конфигурации для пользователей
for user in $users
do
  createImageMaker $user
done

cd /etc/containers/
# Привязать policy.json
if jq . $linkedPolicyFile >/dev/null 2>&1
then
  ln -sf $linkedPolicyFile policy.json
fi

# Скопировать в policy.json системный, заменив в default[0].type с reject  на insecureAcceptAnything
for policyFile in /home/*/.config/containers/policy.json
do
  jq '.default[0].type="insecureAcceptAnything"' /etc/containers/policy.json > $policyFile
done
