#cloud-config
autoinstall:
  version: 1
  interactive-sections:
    - network
    - storage
  locale: "ru_RU.UTF-8"
  keyboard:
    layout: us,ru
    toggle: alt_shift_toggle
  apt:
    primary:
      - arches: [default]
        uri: mirror://mirrors.ubuntu.com/mirrors.txt
  debconf-selections: |
    ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true
  packages:
      - openssh-server
      - openssh-client
      - mosh
      - mc
      - htop
      - ca-certificates
      - curl
      - wget
      - apt-transport-https
      - apt-utils
      - locales-all
      - language-pack-ru
      - language-pack-ru-base
      - unixodbc
      - libfreetype6
      - fontconfig
      - t1utils
      - apache2
      - nginx
      - unzip
      - libc6-i386
      - git
      - build-essential
      - python-is-python3
      - python3-pip
      - python3-virtualenv
      - dkms
      - samba
      - fusesmb
      - samba-vfs-modules
      - cifs-utils
      - avahi-daemon
      - avahi-dnsconfd
      - libnss-winbind
      - libnss-mdns
      - cups
      - wsdd
      - libxt6
      - libtcmalloc-minimal4
  late-commands:
    - stat /cdrom/1c/install >/dev/null 2>/dev/null && sh -exc "mkdir -p /target/var/install/1c && cp /cdrom/1c/install/* /target/var/install/1c/" || echo skip 1c distr copy
    - sync
    - echo --- done! ---
  user-data:
    hostname: srv1c
    
    groups:
      - postgres
      - grp1cv8
      - www-data
    
    users:
      - default
      - name: admin1c
        gecos: Admin 1C
        shell: /bin/bash
        primary_group: admin1c
        groups: users, adm, cdrom, sudo, dip, plugdev, lxd, postgres, grp1cv8, www-data
        lock_passwd: false
        sudo: ALL=(ALL) NOPASSWD:ALL
        passwd: $6$rounds=4096$X0PCsEEYkoirzYwF$vFfmCzOhzPQUsdXbrlt0cyX0wEiuRc2WecIUMyO2ZkTYzSh8oz2Sp87OFVxCHp0sPklRDmdwkK56EZCar.N1o/
        ssh_import_id:
          - gh:b4tman
        #ssh_authorized_keys:
        #  - <ssh pub key 1>
      - name: postgres
        primary_group: postgres
        groups: grp1cv8
        system: true
        passwd: $6$rounds=4096$7HbuIwc5Gbm.$eDOOBbMBh9teE82CE9MGJXJuK3nRuJpjIbkUqOmPN7FyH/Nj.3bgDosdM1WoztBXHYwgCyd1dhya/5aR36Njm1
    
    locale: "ru_RU.UTF-8"
    timezone: Europe/Moscow
    ntp:
      enabled: true
      ntp_client: auto
    
    package_update: true
    package_upgrade: true
    
    write_files:
      - path: /etc/systemd/system/srv1cv83@.service
        encoding: gzip+base64
        owner: root:root
        permissions: '0644'
        content: |
          H4sIAAAAAAAAA61VS2/aQBC++1es2kZqpfJwEyIaaQ+EWAilIQhMekgjtNgDrLLedXfXJKjiv3d2
          bQuS+lgfQJ7HN49vZvy4kNw+BTdgEs1zy5Wk4fAqkhZ0rrkBMge9A0367XPy+Wz8JZjB74JrMFSC
          fVH6uW2Z3oANgkdnyRN4CuJ9DtTwLBcQLAxoWhgdJrt+MNKqyOlG5/4t+EimzG6JVSRFxMQqvScv
          HCWJYAYTICmzLIjkjmslM5CWzmcP4fChv7wZxAPa2aoMOhV2p+1/w2HH/zvwSZGtEEStid0CYhYe
          M1fakkQDs5CS1Z6ksGaFsCQtNJcbsubaWHQWrJDJ1jlrtsHQjWlM72cxDXsX3bfh6lDekWSMSx+1
          TeItN2UC+F+YMgFMDr1rn0RJowS4prA0xT6bMntE0kwQ49lok+FpCHSvQZkwipgcEr7mCM9K7/G0
          NKha4WhztVZgjaXNolFdXeiZcv6ayQ2QtfJpSmQMxwWRlWiGGExGEQJcdq/C3nePMocE22z3RMAO
          xBVKuqRFCplrZREOMz4CG9SGqG3UESXF3mfiCrI8A1cctlSjFz6sQLm0PGHOHGXfHBLojEkUo2tz
          xKYy5tHwR/RAPcdvV6PsnwNY802hfSicp1WxIZlKHasrweQzRq6HrHWidnSp9RqtWqXwHyXm3Tz9
          0fViRF0+wy0kz64urtL3vAiFs5OC9Yv1lWRcCEwaDdLmOqfjyWg5jWbj+xsadru+3hmYHPtSdlgV
          9r/EiMd30f0ipr0qSGNTn2Fv2QrXUUAbbY4NrPb9vH1iQXDDmlDKWSgfLo1lQlQk1ffmTZa3s+ve
          8jaeDO4i2lG5LU/Ja/9yeXnRORvXp6aKHATRKyRzPH+WdlZcdsyWtBLyocmzvCFINPn05/SGHUjL
          L+ZR6pYOpRo27xTVQjqd38ITjduzA/kVtLD1uFgnqnJ2XRTc92k5JiexjoxXJnFF8zubirHDafZu
          Bg8f8HNgfAeYeGF7U7/intNeMNV8h2c2znIqFX4gxiUF7mvj2fTvMgGKR0G7O/aTIYPp9Z5mqOUt
          t87V5+UvY8op1KcGAAA=
      - path: /etc/systemd/system/srv1cv83-ras@.service
        encoding: gzip+base64
        owner: root:root
        permissions: '0644'
        content: |
          H4sIAAAAAAAAA11QwWpCMRC85yuCILSHNAgqUsjBtiKPQik+pQeRksZ9djEvSTeJ1b9vfFQPHmd2
          Z3Zm1yuHacNeIBrCkNA7NXh+nLkEFAgj8AW0PgGfblt0GBPp8w6vgQ5ogN/1q3u2gJ+MBFE5SL+e
          9g9J0w4SmzbF5Ybk1PmJJl4IF6Ow3u9zuOjY+t9+w5anACpiGyywVSxuOdLAHCZsTj4HtaPQITY7
          gqmLPCn5hU7Gby7gaHgPCs+lD0me9+RxMv4cD2W/kqQjNzbHkpALEXxRDkbDUY+9orU17py2qq7m
          1duSvRMedIJlG1SiDKVu7C55JxqNNtOVqsGoUYlfuQKtPb+10dmmDjsDymQicIl96PLg7dNJtWWK
          Ipdm1/J/2tGhvJIBAAA=
      - path: /etc/nginx/sites-available/apache-proxy
        encoding: gzip+base64
        owner: root:root
        permissions: '0644'
        content: |
          H4sIAAAAAAAAA41VXW/aMBR9z6+4YrxNIV+0Q4n6gLpurdauVbOHTtMUmeQCHokd2aaDTvvvu46B
          Qj+2OSgk95xz4/ge3yxbbRSyBljLyjnCLw9oaFT3qCCK3w1COqI0SZJRmHXYArFlNb9HOB5m3m/P
          c+TCyAUKDXI6zTyv5g03RSmFKB6kQOhPuGBqXShspMGCVZUCC5y0qHibRmGTPddsEgvW4I7sYk7g
          lTVHYYqJrNbFZDmdElnzBwSIjj9lW3SOrCJgHx8udmjDVk7fAVEYD69oJkzNsHhJryGGJCa59wa4
          MKgarDgzCDTtKZ8tFTNcCk/rumiVNLKUtYYvl/l9NIg3/0nWwSVv5zbf2en78zOfzvnYH5/lUTzy
          P55e+fn5OD46Th16+xdsp6TQFk1Gw0Pli5hTnp6P6ReH/s315dcoCY/2lM+x12fz6tMy741bDuzW
          39V0+/bOLRbXqDUtXVF2NtRzprBK8/wyPbKltgwsq3lRLklP/ixbSq0iEivUsrZuHQ26w9Zm9sBb
          kCLz7EVh1i1qMLgyQVszLsjrbc3LrlTBDy2Fw0qtDxF2z3RJ9jQH4ZW/B3TCp/erpj5UPLlXWr99
          GmNGNm9XfTfhhouiRjEzc3JkGG5egwy14lgBE2t6R9pCG2vCnf9B0R7xr1ubSkM+vjq7vr34ePE5
          O6SdSrKsMP4XWpAdW0gtuC3DAfUuz/0bcjCWlgW9KINGVngyqWW56GXbXb/pFzXXlBjcGIVQ4ZQt
          a7Opdvac8y1Nv6f/QxwOE6Diw9yYNn4t0Quk/d4BNGdWz6U2DnMEuwdRGT61JUCXLUBTBmLGxSog
          PLD4oMUme0lRLHD9TEGxR0F32lvV3Che0uorJnQrlfFzJDtzs4YetSGfzfDkOAnfxbbk1F3Kellh
          vpxUsiHT6gxoC9WSVb297I89E7pOSi17tA9LZy8INoWyw/rIduKKK6ou7Ea3Fw9JGrf9bxu/82+R
          1f7FDfT3evn/6D5I9ZOpCit7BX1HtKuzKqZbyF79O9c5VRL6j/V85FoDFFR320lcPBpE/05I+0Js
          jd57Sm8Z9YWDYZ+SBoH7YgaO/5u+hH8Ao392zUwHAAA=
    runcmd:
      # --- force locale install ---
      - |
        set -x
        locale-gen ru_RU.UTF-8 en_US.UTF-8
        update-locale LANG=ru_RU.UTF-8
        export LC_ALL=ru_RU.UTF-8
        export LANG=ru_RU.UTF-8
      
      # --- force set timezone ---
      - timedatectl set-timezone Europe/Moscow
      
      # --- force apt update --- 
      - |
        set -x  
        apt-get update
        apt-get -y dist-upgrade
        apt-get clean
      
      # --- install hasp ---
      - |
        set -x  
        mkdir -p /tmp/ldk
        curl -SLo /tmp/ldk/installer.tar.gz https://b4tman.ru/_static/Sentinel_LDK_Ubuntu_DEB_Runtime_Installer.tar.gz
        tar xzf /tmp/ldk/installer.tar.gz --strip-components=1 -C /tmp/ldk
        sh -xc 'dpkg -i $(find /tmp/ldk -name "aksusb*amd64.deb" -type f)'
        rm -rf /tmp/ldk
      
      # --- install ttf-mscorefonts ---
      - |
        set -x
        export DEBIAN_FRONTEND=noninteractive
        mkdir -p /var/lib/update-notifier/package-data-downloads/partial
        chown _apt:root /var/lib/update-notifier/package-data-downloads/partial/
        apt-get install --no-install-recommends --no-install-suggests -y ttf-mscorefonts-installer
        rm -rf /var/lib/update-notifier/package-data-downloads/partial/*
      
      # --- install postgres ---
      - |
        set -x  
        curl -SLo /tmp/pgpro-repo-add.sh https://repo.postgrespro.ru/1c-15/keys/pgpro-repo-add.sh
        sh /tmp/pgpro-repo-add.sh
        rm -f /tmp/pgpro-repo-add.sh
        apt-get install -y postgrespro-1c-15-contrib postgrespro-1c-15-jit
      
      # --- postgres init ---
      - |
        set -x  
        echo postgres > /tmp/pgpswd
        /opt/pgpro/1c-15/bin/pg-setup initdb --tune=1c -k -E UTF8 -g --locale ru_RU.UTF-8 -T russian --pwfile=/tmp/pgpswd
        rm -f /tmp/pgpswd
        sed -i 's%\=\s0MB%\=\ 1GB%g' /var/lib/pgpro/1c-15/data/postgresql.conf
        echo  >> /var/lib/pgpro/1c-15/data/postgresql.conf
        echo \#--- >> /var/lib/pgpro/1c-15/data/postgresql.conf
        echo row_security=off >> /var/lib/pgpro/1c-15/data/postgresql.conf
        echo max_wal_senders=0 >> /var/lib/pgpro/1c-15/data/postgresql.conf
        echo wal_level=minimal >> /var/lib/pgpro/1c-15/data/postgresql.conf
        /opt/pgpro/1c-15/bin/pg-setup service enable
        /opt/pgpro/1c-15/bin/pg-setup service start
        apt-get install -y postgrespro-1c-15
      
      # --- install 1c ---
      - |
        set -x
        # install deps
        mkdir -p /tmp/deps1c
        curl --output-dir /tmp/deps1c -SL --remote-name-all http://archive.ubuntu.com/ubuntu/pool/universe/e/enchant/libenchant1c2a_1.6.0-11.3build1_amd64.deb
        dpkg -i $(find /tmp/deps1c -type f -name  \*.deb) || apt-get install -f -y
        rm -rf /tmp/deps1c
        # extract distrs
        stat /var/install/1c >/dev/null 2>/dev/null && mkdir -p /tmp/1c || echo skip 1c install
        stat /var/install/1c >/dev/null 2>/dev/null && tar xzf $(find /var/install/1c -name "server64_*.tar.gz" -type f) -C /tmp/1c || echo skip 1c install
        # install only server (without GUI)
        stat /var/install/1c >/dev/null 2>/dev/null && $(find /tmp/1c -name "setup-full-*.run" -type f) --mode unattended --enable-components additional_admin_functions,integrity_monitoring,config_storage_server,liberica_jre,server,server_admin,ws,ru || echo skip 1c install
        # install with GUI (with all X deps)
        # stat /var/install/1c >/dev/null 2>/dev/null && $(find /tmp/1c -name "setup-full-*.run" -type f) --mode unattended --enable-components additional_admin_functions,integrity_monitoring,config_storage_server,client_full,client_thin_fib,liberica_jre,server,server_admin,ws,ru || echo skip 1c install
        stat /tmp/1c >/dev/null 2>/dev/null && rm -rf /tmp/1c || echo skip 1c install
        stat /opt/1cv8/x86_64 >/dev/null 2>/dev/null && ln -s $(find /opt/1cv8/x86_64 -name "8.3.*" -type d) /opt/1cv8/x86_64/current || echo skip 1c install
        
      # --- 1c config ---
      - |
        echo "JavaHome=/opt/1cv8/x86_64/current/jre" >> /opt/1cv8/conf/conf.cfg
        echo "JAVA_HOME=/opt/1cv8/x86_64/current/jre" >> /opt/1cv8/conf/conf.cfg
        echo "UpdateDBCfg=v2" >> /opt/1cv8/conf/conf.cfg

      # --- 1c web init ---
      - |
        set -x  
        # stop services
        systemctl stop apache2
        systemctl stop nginx
        # remove defaul sites
        rm -f /etc/apache2/sites-enabled/000-default.conf
        rm -f /etc/nginx/sites-enabled/default
        # dirs and files
        mkdir -p /var/www-1c/html
        mkdir -p /etc/nginx/ssl
        echo Hello 1C > /var/www-1c/html/index.html
        #create apache cfg from default
        cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/001-1c.conf
        sed -i 's%VirtualHost\s\*\:80%VirtualHost\ \*\:33380%' /etc/apache2/sites-available/001-1c.conf
        sed -i 's%DocumentRoot\s\/var\/www\/html%DocumentRoot \/var\/www-1c\/html%' /etc/apache2/sites-available/001-1c.conf
        sed -i 's%\#Include.*$%Include /etc/apache2/conf-available/1c.conf%' /etc/apache2/sites-available/001-1c.conf
        # load 1c handler module 
        echo LoadModule _1cws_module "/opt/1cv8/x86_64/current/wsap24.so" >> /etc/apache2/conf-available/1c.conf
        # allow www root
        echo \<Directory\ \"/var/www-1c/html\"\> >> /etc/apache2/conf-available/1c.conf
        echo \ \ \ \ Options Indexes Includes >> /etc/apache2/conf-available/1c.conf
        echo \ \ \ \ AllowOverride All >> /etc/apache2/conf-available/1c.conf
        echo \ \ \ \ Require all granted >> /etc/apache2/conf-available/1c.conf
        echo \</Directory\> >> /etc/apache2/conf-available/1c.conf
        # set apache http port
        sed -i 's%Listen\s80%Listen\ 33380%' /etc/apache2/ports.conf
        # gen self signed ssl cert
        openssl req -x509 -newkey rsa:4096 -keyout /etc/nginx/ssl/key.pem -out /etc/nginx/ssl/cert.pem -days 3650 -nodes -subj "/C=RU/ST=Tula/L=Novomoskovsk/O=Company Name/OU=Org/CN=$(hostname)"
        # set apache hostname
        sed -i "s%server_name\slocalhost;%server_name $(hostname);%" /etc/nginx/sites-available/apache-proxy
        sed -i "s%\#ServerName.*$%ServerName $(hostname)%" /etc/apache2/sites-available/001-1c.conf
        # fix 1c thin client auto update (with url_path=/1c/test1)
        sed -E '/^\s*location\s+\/\s+/i\ \ \ \ rewrite ^/1c/e1cibdst/(.*) /1c/test1/e1cibdst/$1 last;\n' -i /etc/nginx/sites-available/apache-proxy
        # enable new configs
        ln -s /etc/apache2/sites-available/001-1c.conf /etc/apache2/sites-enabled/001-1c.conf
        ln -s /etc/nginx/sites-available/apache-proxy /etc/nginx/sites-enabled/apache-proxy
        # start services
        systemctl enable apache2 --now
        systemctl enable nginx --now
        # enable+start 1c service
        stat /opt/1cv8/x86_64/current/ragent >/dev/null 2>/dev/null && systemctl enable srv1cv83@current --now || echo ignoring 1c service
        stat /opt/1cv8/x86_64/current/ras >/dev/null 2>/dev/null && systemctl enable srv1cv83-ras@current --now || echo ignoring 1c ras service
      
      # --- install & config webpub1c ---
      - |
        set -x  
        sudo -u admin1c sh -exc "git clone --branch v0.0.1 https://github.com/b4tman/webpub1c /home/admin1c/webpub1c && cd /home/admin1c/webpub1c && virtualenv venv && . venv/bin/activate && pip install -r requirements.txt"
        sed -i "s%apache_config:.*\$%apache_config: /etc/apache2/conf-available/1c.conf%" /home/admin1c/webpub1c/webpub1c.yml
        mkdir -p /var/www-1c/vrd
        mkdir -p /var/www-1c/pub
        chown admin1c:www-data /var/www-1c/vrd
        chown admin1c:www-data /var/www-1c/pub
        chown admin1c:root /etc/apache2/conf-available/1c.conf
        sed -i "s%vrd_path:.*\$%vrd_path: /var/www-1c/vrd%" /home/admin1c/webpub1c/webpub1c.yml
        sed -i "s%dir_path:.*\$%dir_path: /var/www-1c/pub%" /home/admin1c/webpub1c/webpub1c.yml
      
      # --- install opt tools ---
      - |
        set -x
        snap install ripgrep --classic
        snap install lsd
        snap install yq
        snap install jq
        snap install nvim --classic
        apt-get install -y bat fd-find exa fzf
        echo "alias bat=batcat" >> /home/admin1c/.bashrc
        
      # --- install onescript ---
      - |
        set -x
        apt-get install -y mono-runtime libmono-i18n4.0-all
        curl -SLo /tmp/onescript-engine.deb https://github.com/EvilBeaver/OneScript/releases/download/v1.8.3/onescript-engine_1.8.3_all.deb
        dpkg -i /tmp/onescript-engine.deb
      
      # --- install wsdd ---
      #- |
      #  set -x
      #  apt-key adv --fetch-keys https://pkg.ltec.ch/public/conf/ltec-ag.gpg.key
      #  echo "deb https://pkg.ltec.ch/public/ $(lsb_release -cs) main" >> /etc/apt/sources.list.d/wsdd.list
      #  apt-get update
      #  apt-get install -y wsdd
      #  systemctl enable wsdd.service --now
      
      # --- create bases ---
      - |
        set -x
        export PATH="$PATH:/opt/1cv8/x86_64/current"
        export DB_ADDR=localhost
        export CLUSTER_ADDR=localhost
        export CLUSTER_ID=$(rac cluster list $CLUSTER_ADDR | rg -e "^cluster\s*:" -m 1 | rg -e "[[:xdigit:]-]{36}" -o)
        rac infobase --cluster=$CLUSTER_ID create --create-database --name=test1 --dbms=PostgreSQL --db-server=$DB_ADDR --db-name=test1 --locale=ru --db-user=postgres --db-pwd=postgres --license-distribution=allow $CLUSTER_ADDR
        rac infobase --cluster=$CLUSTER_ID create --create-database --name=test2 --dbms=PostgreSQL --db-server=$DB_ADDR --db-name=test2 --locale=ru --db-user=postgres --db-pwd=postgres --license-distribution=allow $CLUSTER_ADDR
        rac infobase --cluster=$CLUSTER_ID create --create-database --name=test3 --dbms=PostgreSQL --db-server=$DB_ADDR --db-name=test3 --locale=ru --db-user=postgres --db-pwd=postgres --license-distribution=allow $CLUSTER_ADDR

        sudo -u admin1c sh -exc "cd /home/admin1c/webpub1c && . venv/bin/activate && python webpub1c.py add_module && python webpub1c.py add test1 && python webpub1c.py add test2 && python webpub1c.py add test3"
        systemctl restart apache2


      # --- final ---
      - |
        set -x
        # disable boot to GUI
        systemctl set-default multi-user.target
        # remove default user folder
        rm -rf /home/ubuntu
        echo -- done! ---