#!/usr/bin/env bash
# Resume v2: download public images using a temporary anonymous client config.
# The user's existing Docker credential configuration is not edited.
set -Eeuo pipefail
trap 'printf "\nSTOP: resume failed at line %s. Keep this window open.\n" "$LINENO"' ERR
umask 077
printf '\n[Resume 1/3] Checking the existing Dify configuration...\n'
cd -- "$HOME/dify-training/dify-1.19.0/docker"
test -f .env
test -f docker-compose.override.yaml
docker info --format 'Docker server: {{.ServerVersion}}'
docker compose config --quiet
printf '\n[Resume 2/3] Downloading public images without a Docker login...\n'
python3 -u - <<'PY'
import json,os,pathlib,subprocess,tempfile
config=json.loads(subprocess.check_output(['docker','compose','config','--format','json'],text=True))
images=set()
profiles={'weaviate','postgresql','collaboration'}
for service in config['services'].values():
    selected=service.get('profiles',[])
    if selected and not profiles.intersection(selected):
        continue
    for port in service.get('ports',[]):
        if port.get('host_ip')!='127.0.0.1':
            raise SystemExit('STOP: unexpected non-local port binding. Nothing was started.')
    if service.get('image'): images.add(service['image'])
if not images: raise SystemExit('STOP: no images found in the existing configuration.')
print('Configuration verified. Existing Docker credentials will not be edited.',flush=True)
with tempfile.TemporaryDirectory(prefix='dify-public-pull-') as tmp:
    pathlib.Path(tmp,'config.json').write_text(json.dumps({'auths':{}}))
    env=os.environ.copy()
    env.pop('DOCKER_CONTEXT',None)
    for i,image in enumerate(sorted(images),1):
        print(f'\nImage {i}/{len(images)}: {image}',flush=True)
        result=subprocess.run(['docker','--config',tmp,'--host','unix:///var/run/docker.sock','image','pull',image],env=env)
        if result.returncode:
            raise SystemExit('STOP: image download failed. Keep the final error visible. Re-running this script can reuse completed downloads.')
print('\nAll public images downloaded.',flush=True)
PY
printf '\n[Resume 3/3] Starting the downloaded Dify components...\n'
docker compose up -d --pull never --no-build
docker compose ps --all
printf '\nStartup command completed. The web application may need more time to become ready.\n'
printf 'Open: http://localhost:8080/install\n'
printf 'Keep this terminal open. Report the final messages, not credentials or .env contents.\n'
